1
0
Fork 0
mirror of https://codeberg.org/Mercury-IM/Smack synced 2025-12-05 12:41:08 +01:00

Prefix subprojects with 'smack-'

instead of using the old baseName=smack appendix=project.name approach,
we are now going convention over configuration and renaming the
subprojects directories to the proper name.

Having a prefix is actually very helpful, because the resulting
libraries will be named like the subproject. And a core-4.0.0-rc1.jar is
not as explicit about what it actually *is* as a
smack-core-4.0.0-rc1.jar.

SMACK-265
This commit is contained in:
Florian Schmaus 2014-04-28 19:27:53 +02:00
parent b6fb1f3743
commit 91fd15ad86
758 changed files with 42 additions and 42 deletions

View file

@ -0,0 +1,116 @@
/**
*
* Copyright 2003-2005 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.packet.Version;
/**
* Ensure that stream compression (JEP-138) is correctly supported by Smack.
*
* @author Gaston Dombiak
*/
public class CompressionTest extends SmackTestCase {
public CompressionTest(String arg0) {
super(arg0);
}
/**
* Test that stream compression works fine. It is assumed that the server supports and has
* stream compression enabled.
*/
public void testSuccessCompression() throws XMPPException {
// Create the configuration for this new connection
ConnectionConfiguration config = new ConnectionConfiguration(getHost(), getPort());
config.setCompressionEnabled(true);
config.setSASLAuthenticationEnabled(true);
XMPPTCPConnection connection = new XMPPConnection(config);
connection.connect();
// Login with the test account
connection.login("user0", "user0");
assertTrue("XMPPConnection is not using stream compression", connection.isUsingCompression());
// Request the version of the server
Version version = new Version();
version.setType(IQ.Type.GET);
version.setTo(getServiceName());
// Create a packet collector to listen for a response.
PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(version.getPacketID()));
connection.sendPacket(version);
// Wait up to 5 seconds for a result.
IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Close the collector
collector.cancel();
assertNotNull("No reply was received from the server", result);
assertEquals("Incorrect IQ type from server", IQ.Type.RESULT, result.getType());
// Close connection
connection.disconnect();
}
protected int getMaxConnections() {
return 0;
}
/**
* Just create an account.
*/
protected void setUp() throws Exception {
super.setUp();
XMPPTCPConnection setupConnection = new XMPPConnection(getServiceName());
setupConnection.connect();
if (!setupConnection.getAccountManager().supportsAccountCreation())
fail("Server does not support account creation");
// Create the test account
try {
setupConnection.getAccountManager().createAccount("user0", "user0");
} catch (XMPPException e) {
// Do nothing if the accout already exists
if (e.getXMPPError().getCode() != 409) {
throw e;
}
}
}
/**
* Deletes the created account for the test.
*/
protected void tearDown() throws Exception {
super.tearDown();
XMPPTCPConnection setupConnection = createConnection();
setupConnection.connect();
setupConnection.login("user0", "user0");
// Delete the created account for the test
setupConnection.getAccountManager().deleteAccount();
// Close the setupConnection
setupConnection.disconnect();
}
}

View file

@ -0,0 +1,119 @@
/**
*
* Copyright 2006 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.filetransfer.*;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.concurrent.SynchronousQueue;
/**
*
*/
public class FileTransferTest extends SmackTestCase {
int receiveCount = -1;
Exception exception;
public FileTransferTest(String arg0) {
super(arg0);
}
public void testInbandFileTransfer() throws Exception {
FileTransferNegotiator.IBB_ONLY = true;
try {
testFileTransfer();
}
finally {
FileTransferNegotiator.IBB_ONLY = false;
}
}
public void testFileTransfer() throws Exception {
final byte [] testTransfer = "This is a test transfer".getBytes();
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
FileTransferManager manager1 = new FileTransferManager(getConnection(0));
manager1.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(final FileTransferRequest request) {
new Thread(new Runnable() {
public void run() {
IncomingFileTransfer transfer = request.accept();
InputStream stream;
try {
stream = transfer.recieveFile();
}
catch (XMPPException e) {
exception = e;
return;
}
byte [] testRecieve = new byte[testTransfer.length];
int receiveCount = 0;
try {
while (receiveCount != -1) {
receiveCount = stream.read(testRecieve);
}
}
catch (IOException e) {
exception = e;
}
finally {
try {
stream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
try {
queue.put(testRecieve);
}
catch (InterruptedException e) {
exception = e;
}
}
}).start();
}
});
// Send the file from user1 to user0
FileTransferManager manager2 = new FileTransferManager(getConnection(1));
OutgoingFileTransfer outgoing = manager2.createOutgoingFileTransfer(getFullJID(0));
OutputStream stream =
outgoing.sendFile("test.txt", testTransfer.length, "The great work of robin hood");
stream.write(testTransfer);
stream.flush();
stream.close();
if(exception != null) {
exception.printStackTrace();
fail();
}
byte [] array = queue.take();
assertEquals("Recieved file not equal to sent file.", testTransfer, array);
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,157 @@
/**
*
* Copyright 2004 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.ThreadFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.test.SmackTestCase;
/**
* Tests the DataForms extensions.
*
* @author Gaston Dombiak
*/
public class FormTest extends SmackTestCase {
public FormTest(String arg0) {
super(arg0);
}
/**
* 1. Create a form to fill out and send it to the other user
* 2. Retrieve the form to fill out, complete it and return it to the requestor
* 3. Retrieve the completed form and check that everything is OK
*/
public void testFilloutForm() {
Form formToSend = new Form(Form.TYPE_FORM);
formToSend.setInstructions(
"Fill out this form to report your case.\nThe case will be created automatically.");
formToSend.setTitle("Case configurations");
// Add a hidden variable
FormField field = new FormField("hidden_var");
field.setType(FormField.TYPE_HIDDEN);
field.addValue("Some value for the hidden variable");
formToSend.addField(field);
// Add a fixed variable
field = new FormField();
field.addValue("Section 1: Case description");
formToSend.addField(field);
// Add a text-single variable
field = new FormField("name");
field.setLabel("Enter a name for the case");
field.setType(FormField.TYPE_TEXT_SINGLE);
formToSend.addField(field);
// Add a text-multi variable
field = new FormField("description");
field.setLabel("Enter a description");
field.setType(FormField.TYPE_TEXT_MULTI);
formToSend.addField(field);
// Add a boolean variable
field = new FormField("time");
field.setLabel("Is this your first case?");
field.setType(FormField.TYPE_BOOLEAN);
formToSend.addField(field);
// Add a text variable where an int value is expected
field = new FormField("age");
field.setLabel("How old are you?");
field.setType(FormField.TYPE_TEXT_SINGLE);
formToSend.addField(field);
// Create the chats between the two participants
Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null);
PacketCollector collector = getConnection(0).createPacketCollector(
new ThreadFilter(chat.getThreadID()));
PacketCollector collector2 = getConnection(1).createPacketCollector(
new ThreadFilter(chat.getThreadID()));
Message msg = new Message();
msg.setBody("To enter a case please fill out this form and send it back to me");
msg.addExtension(formToSend.getDataFormToSend());
try {
// Send the message with the form to fill out
chat.sendMessage(msg);
// Get the message with the form to fill out
Message msg2 = (Message)collector2.nextResult(2000);
assertNotNull("Messge not found", msg2);
// Retrieve the form to fill out
Form formToRespond = Form.getFormFrom(msg2);
assertNotNull(formToRespond);
assertNotNull(formToRespond.getField("name"));
assertNotNull(formToRespond.getField("description"));
// Obtain the form to send with the replies
Form completedForm = formToRespond.createAnswerForm();
assertNotNull(completedForm.getField("hidden_var"));
// Check that a field of type String does not accept booleans
try {
completedForm.setAnswer("name", true);
fail("A boolean value was set to a field of type String");
}
catch (IllegalArgumentException e) {
}
completedForm.setAnswer("name", "Credit card number invalid");
completedForm.setAnswer(
"description",
"The ATM says that my credit card number is invalid. What's going on?");
completedForm.setAnswer("time", true);
completedForm.setAnswer("age", 20);
// Create a new message to send with the completed form
msg2 = new Message();
msg2.setTo(msg.getFrom());
msg2.setThread(msg.getThread());
msg2.setType(Message.Type.chat);
msg2.setBody("To enter a case please fill out this form and send it back to me");
// Add the completed form to the message
msg2.addExtension(completedForm.getDataFormToSend());
// Send the message with the completed form
getConnection(1).sendPacket(msg2);
// Get the message with the completed form
Message msg3 = (Message) collector.nextResult(2000);
assertNotNull("Messge not found", msg3);
// Retrieve the completed form
completedForm = Form.getFormFrom(msg3);
assertNotNull(completedForm);
assertNotNull(completedForm.getField("name"));
assertNotNull(completedForm.getField("description"));
assertEquals(
completedForm.getField("name").getValues().next(),
"Credit card number invalid");
assertNotNull(completedForm.getField("time"));
assertNotNull(completedForm.getField("age"));
assertEquals("The age is bad", "20", completedForm.getField("age").getValues().next());
}
catch (XMPPException ex) {
fail(ex.getMessage());
}
finally {
collector.cancel();
collector2.cancel();
}
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,84 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketExtensionFilter;
/**
*
*
* @author Matt Tucker
*/
public class GroupChatInvitationTest extends SmackTestCase {
private PacketCollector collector = null;
/**
* Constructor for GroupChatInvitationTest.
* @param arg0
*/
public GroupChatInvitationTest(String arg0) {
super(arg0);
}
public void testInvitation() {
try {
GroupChatInvitation invitation = new GroupChatInvitation("test@" + getChatDomain());
Message message = new Message(getBareJID(1));
message.setBody("Group chat invitation!");
message.addExtension(invitation);
getConnection(0).sendPacket(message);
Thread.sleep(250);
Message result = (Message)collector.pollResult();
assertNotNull("Message not delivered correctly.", result);
GroupChatInvitation resultInvite = (GroupChatInvitation)result.getExtension("x",
"jabber:x:conference");
assertEquals("Invitation not to correct room", "test@" + getChatDomain(),
resultInvite.getRoomAddress());
}
catch (Exception e) {
fail(e.getMessage());
}
}
protected void setUp() throws Exception {
super.setUp();
// Register listener for groupchat invitations.
PacketFilter filter = new PacketExtensionFilter("x", "jabber:x:conference");
collector = getConnection(1).createPacketCollector(filter);
}
protected void tearDown() throws Exception {
// Cancel the packet collector so that no more results are queued up
collector.cancel();
super.tearDown();
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,157 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smack.TCPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.packet.LastActivity;
public class LastActivityManagerTest extends SmackTestCase {
/**
* This is a test to check if a LastActivity request for idle time is
* answered and correct.
*/
public void testOnline() {
TCPConnection conn0 = getConnection(0);
TCPConnection conn1 = getConnection(1);
// Send a message as the last activity action from connection 1 to
// connection 0
conn1.sendPacket(new Message(getBareJID(0)));
// Wait 1 seconds to have some idle time
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
fail("Thread sleep interrupted");
}
LastActivity lastActivity = null;
try {
lastActivity = LastActivityManager.getLastActivity(conn0, getFullJID(1));
} catch (XMPPException e) {
e.printStackTrace();
fail("An error occurred requesting the Last Activity");
}
// Asserts that the last activity packet was received
assertNotNull("No last activity packet", lastActivity);
// Asserts that there is at least a 1 second of idle time
assertTrue(
"The last activity idle time is less than expected: " + lastActivity.getIdleTime(),
lastActivity.getIdleTime() >= 1);
}
/**
* This is a test to check if a denied LastActivity response is handled correctly.
*/
public void testOnlinePermisionDenied() {
TCPConnection conn0 = getConnection(0);
TCPConnection conn2 = getConnection(2);
// Send a message as the last activity action from connection 2 to
// connection 0
conn2.sendPacket(new Message(getBareJID(0)));
// Wait 1 seconds to have some idle time
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
fail("Thread sleep interrupted");
}
try {
LastActivityManager.getLastActivity(conn0, getFullJID(2));
fail("No error was received from the server. User was able to get info of other user not in his roster.");
} catch (XMPPException e) {
assertNotNull("No error was returned from the server", e.getXMPPError());
assertEquals("Forbidden error was not returned from the server", 403,
e.getXMPPError().getCode());
}
}
/**
* This is a test to check if a LastActivity request for last logged out
* lapsed time is answered and correct
*/
public void testLastLoggedOut() {
TCPConnection conn0 = getConnection(0);
LastActivity lastActivity = null;
try {
lastActivity = LastActivityManager.getLastActivity(conn0, getBareJID(1));
} catch (XMPPException e) {
e.printStackTrace();
fail("An error occurred requesting the Last Activity");
}
assertNotNull("No last activity packet", lastActivity);
assertTrue("The last activity idle time should be 0 since the user is logged in: " +
lastActivity.getIdleTime(), lastActivity.getIdleTime() == 0);
}
/**
* This is a test to check if a LastActivity request for server uptime
* is answered and correct
*/
public void testServerUptime() {
TCPConnection conn0 = getConnection(0);
LastActivity lastActivity = null;
try {
lastActivity = LastActivityManager.getLastActivity(conn0, getHost());
} catch (XMPPException e) {
if (e.getXMPPError().getCode() == 403) {
//The test can not be done since the host do not allow this kind of request
return;
}
e.printStackTrace();
fail("An error occurred requesting the Last Activity");
}
assertNotNull("No last activity packet", lastActivity);
assertTrue("The last activity idle time should be greater than 0 : " +
lastActivity.getIdleTime(), lastActivity.getIdleTime() > 0);
}
public LastActivityManagerTest(String name) {
super(name);
}
@Override
protected int getMaxConnections() {
return 3;
}
@Override
protected void setUp() throws Exception {
super.setUp();
try {
getConnection(0).getRoster().createEntry(getBareJID(1), "User1", null);
Thread.sleep(300);
} catch (Exception e) {
fail(e.getMessage());
}
}
}

View file

@ -0,0 +1,239 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import java.util.ArrayList;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.test.SmackTestCase;
/**
*
* Test the MessageEvent extension using the high level API.
*
* @author Gaston Dombiak
*/
public class MessageEventManagerTest extends SmackTestCase {
public MessageEventManagerTest(String name) {
super(name);
}
/**
* High level API test.
* This is a simple test to use with a XMPP client and check if the client receives the
* message
* 1. User_1 will send a message to user_2 requesting to be notified when any of these events
* occurs: offline, composing, displayed or delivered
*/
public void testSendMessageEventRequest() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
// Create the message to send with the roster
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("An interesting body comes here...");
// Add to the message all the notifications requests (offline, delivered, displayed,
// composing)
MessageEventManager.addNotificationsRequests(msg, true, true, true, true);
// Send the message that contains the notifications request
try {
chat1.sendMessage(msg);
} catch (Exception e) {
fail("An error occured sending the message");
}
}
/**
* High level API test.
* This is a simple test to use with a XMPP client, check if the client receives the
* message and display in the console any notification
* 1. User_1 will send a message to user_2 requesting to be notified when any of these events
* occurs: offline, composing, displayed or delivered
* 2. User_2 will use a XMPP client (like Exodus) to display the message and compose a reply
* 3. User_1 will display any notification that receives
*/
public void testSendMessageEventRequestAndDisplayNotifications() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
MessageEventManager messageEventManager = new MessageEventManager(getConnection(0));
messageEventManager
.addMessageEventNotificationListener(new MessageEventNotificationListener() {
public void deliveredNotification(String from, String packetID) {
System.out.println("From: " + from + " PacketID: " + packetID + "(delivered)");
}
public void displayedNotification(String from, String packetID) {
System.out.println("From: " + from + " PacketID: " + packetID + "(displayed)");
}
public void composingNotification(String from, String packetID) {
System.out.println("From: " + from + " PacketID: " + packetID + "(composing)");
}
public void offlineNotification(String from, String packetID) {
System.out.println("From: " + from + " PacketID: " + packetID + "(offline)");
}
public void cancelledNotification(String from, String packetID) {
System.out.println("From: " + from + " PacketID: " + packetID + "(cancelled)");
}
});
// Create the message to send with the roster
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("An interesting body comes here...");
// Add to the message all the notifications requests (offline, delivered, displayed,
// composing)
MessageEventManager.addNotificationsRequests(msg, true, true, true, true);
// Send the message that contains the notifications request
try {
chat1.sendMessage(msg);
// Wait a few seconds so that the XMPP client can send any event
Thread.sleep(200);
} catch (Exception e) {
fail("An error occured sending the message");
}
}
/**
* High level API test.
* 1. User_1 will send a message to user_2 requesting to be notified when any of these events
* occurs: offline, composing, displayed or delivered
* 2. User_2 will receive the message
* 3. User_2 will simulate that the message was displayed
* 4. User_2 will simulate that he/she is composing a reply
* 5. User_2 will simulate that he/she has cancelled the reply
*/
public void testRequestsAndNotifications() {
final ArrayList<String> results = new ArrayList<String>();
ArrayList<String> resultsExpected = new ArrayList<String>();
resultsExpected.add("deliveredNotificationRequested");
resultsExpected.add("composingNotificationRequested");
resultsExpected.add("displayedNotificationRequested");
resultsExpected.add("offlineNotificationRequested");
resultsExpected.add("deliveredNotification");
resultsExpected.add("displayedNotification");
resultsExpected.add("composingNotification");
resultsExpected.add("cancelledNotification");
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
MessageEventManager messageEventManager1 = new MessageEventManager(getConnection(0));
messageEventManager1
.addMessageEventNotificationListener(new MessageEventNotificationListener() {
public void deliveredNotification(String from, String packetID) {
results.add("deliveredNotification");
}
public void displayedNotification(String from, String packetID) {
results.add("displayedNotification");
}
public void composingNotification(String from, String packetID) {
results.add("composingNotification");
}
public void offlineNotification(String from, String packetID) {
results.add("offlineNotification");
}
public void cancelledNotification(String from, String packetID) {
results.add("cancelledNotification");
}
});
MessageEventManager messageEventManager2 = new MessageEventManager(getConnection(1));
messageEventManager2
.addMessageEventRequestListener(new DefaultMessageEventRequestListener() {
public void deliveredNotificationRequested(
String from,
String packetID,
MessageEventManager messageEventManager) {
super.deliveredNotificationRequested(from, packetID, messageEventManager);
results.add("deliveredNotificationRequested");
}
public void displayedNotificationRequested(
String from,
String packetID,
MessageEventManager messageEventManager) {
super.displayedNotificationRequested(from, packetID, messageEventManager);
results.add("displayedNotificationRequested");
}
public void composingNotificationRequested(
String from,
String packetID,
MessageEventManager messageEventManager) {
super.composingNotificationRequested(from, packetID, messageEventManager);
results.add("composingNotificationRequested");
}
public void offlineNotificationRequested(
String from,
String packetID,
MessageEventManager messageEventManager) {
super.offlineNotificationRequested(from, packetID, messageEventManager);
results.add("offlineNotificationRequested");
}
});
// Create the message to send with the roster
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("An interesting body comes here...");
// Add to the message all the notifications requests (offline, delivered, displayed,
// composing)
MessageEventManager.addNotificationsRequests(msg, true, true, true, true);
// Send the message that contains the notifications request
try {
chat1.sendMessage(msg);
messageEventManager2.sendDisplayedNotification(getBareJID(0), msg.getPacketID());
messageEventManager2.sendComposingNotification(getBareJID(0), msg.getPacketID());
messageEventManager2.sendCancelledNotification(getBareJID(0), msg.getPacketID());
// Wait up to 2 seconds
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
(!results.containsAll(resultsExpected))) {
Thread.sleep(100);
}
assertTrue(
"Test failed due to bad results (1)" + resultsExpected,
resultsExpected.containsAll(results));
assertTrue(
"Test failed due to bad results (2)" + results,
results.containsAll(resultsExpected));
} catch (Exception e) {
fail("An error occured sending the message");
}
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,41 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smackx.packet.MessageEventTest;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
*
* Test suite that runs all the Message Event extension tests
*
* @author Gaston Dombiak
*/
public class MessageEventTests {
public static Test suite() {
TestSuite suite = new TestSuite("High and low level API tests for message event extension");
//$JUnit-BEGIN$
suite.addTest(new TestSuite(MessageEventManagerTest.class));
suite.addTest(new TestSuite(MessageEventTest.class));
//$JUnit-END$
return suite;
}
}

View file

@ -0,0 +1,251 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.packet.MultipleAddresses;
import java.util.Arrays;
import java.util.List;
/**
* Tests that JEP-33 support in Smack is correct.
*
* @author Gaston Dombiak
*/
public class MultipleRecipientManagerTest extends SmackTestCase {
public MultipleRecipientManagerTest(String arg0) {
super(arg0);
}
/**
* Ensures that sending and receiving of packets is ok.
*/
public void testSending() throws XMPPException {
PacketCollector collector1 =
getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
PacketCollector collector2 =
getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
PacketCollector collector3 =
getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
Message message = new Message();
message.setBody("Hola");
List<String> to = Arrays.asList(new String[]{getBareJID(1)});
List<String> cc = Arrays.asList(new String[]{getBareJID(2)});
List<String> bcc = Arrays.asList(new String[]{getBareJID(3)});
MultipleRecipientManager.send(getConnection(0), message, to, cc, bcc);
Packet message1 = collector1.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection 1 never received the message", message1);
MultipleRecipientInfo info1 = MultipleRecipientManager.getMultipleRecipientInfo(message1);
assertNotNull("Message 1 does not contain MultipleRecipientInfo", info1);
assertFalse("Message 1 should be 'replyable'", info1.shouldNotReply());
List<?> addresses1 = info1.getTOAddresses();
assertEquals("Incorrect number of TO addresses", 1, addresses1.size());
String address1 = ((MultipleAddresses.Address) addresses1.get(0)).getJid();
assertEquals("Incorrect TO address", getBareJID(1), address1);
addresses1 = info1.getCCAddresses();
assertEquals("Incorrect number of CC addresses", 1, addresses1.size());
address1 = ((MultipleAddresses.Address) addresses1.get(0)).getJid();
assertEquals("Incorrect CC address", getBareJID(2), address1);
Packet message2 = collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection 2 never received the message", message2);
MultipleRecipientInfo info2 = MultipleRecipientManager.getMultipleRecipientInfo(message2);
assertNotNull("Message 2 does not contain MultipleRecipientInfo", info2);
assertFalse("Message 2 should be 'replyable'", info2.shouldNotReply());
List<MultipleAddresses.Address> addresses2 = info2.getTOAddresses();
assertEquals("Incorrect number of TO addresses", 1, addresses2.size());
String address2 = ((MultipleAddresses.Address) addresses2.get(0)).getJid();
assertEquals("Incorrect TO address", getBareJID(1), address2);
addresses2 = info2.getCCAddresses();
assertEquals("Incorrect number of CC addresses", 1, addresses2.size());
address2 = ((MultipleAddresses.Address) addresses2.get(0)).getJid();
assertEquals("Incorrect CC address", getBareJID(2), address2);
Packet message3 = collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection 3 never received the message", message3);
MultipleRecipientInfo info3 = MultipleRecipientManager.getMultipleRecipientInfo(message3);
assertNotNull("Message 3 does not contain MultipleRecipientInfo", info3);
assertFalse("Message 3 should be 'replyable'", info3.shouldNotReply());
List<MultipleAddresses.Address> addresses3 = info3.getTOAddresses();
assertEquals("Incorrect number of TO addresses", 1, addresses3.size());
String address3 = ((MultipleAddresses.Address) addresses3.get(0)).getJid();
assertEquals("Incorrect TO address", getBareJID(1), address3);
addresses3 = info3.getCCAddresses();
assertEquals("Incorrect number of CC addresses", 1, addresses3.size());
address3 = ((MultipleAddresses.Address) addresses3.get(0)).getJid();
assertEquals("Incorrect CC address", getBareJID(2), address3);
collector1.cancel();
collector2.cancel();
collector3.cancel();
}
/**
* Ensures that replying to packets is ok.
*/
public void testReplying() throws XMPPException {
PacketCollector collector0 =
getConnection(0).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
PacketCollector collector1 =
getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
PacketCollector collector2 =
getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
PacketCollector collector3 =
getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
// Send the intial message with multiple recipients
Message message = new Message();
message.setBody("Hola");
List<String> to = Arrays.asList(new String[]{getBareJID(1)});
List<String> cc = Arrays.asList(new String[]{getBareJID(2)});
List<String> bcc = Arrays.asList(new String[]{getBareJID(3)});
MultipleRecipientManager.send(getConnection(0), message, to, cc, bcc);
// Get the message and ensure it's ok
Message message1 =
(Message) collector1.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection 1 never received the message", message1);
MultipleRecipientInfo info = MultipleRecipientManager.getMultipleRecipientInfo(message1);
assertNotNull("Message 1 does not contain MultipleRecipientInfo", info);
assertFalse("Message 1 should be 'replyable'", info.shouldNotReply());
assertEquals("Incorrect number of TO addresses", 1, info.getTOAddresses().size());
assertEquals("Incorrect number of CC addresses", 1, info.getCCAddresses().size());
// Prepare and send the reply
Message reply1 = new Message();
reply1.setBody("This is my reply");
MultipleRecipientManager.reply(getConnection(1), message1, reply1);
// Get the reply and ensure it's ok
reply1 = (Message) collector0.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection 0 never received the reply", reply1);
info = MultipleRecipientManager.getMultipleRecipientInfo(reply1);
assertNotNull("Replied message does not contain MultipleRecipientInfo", info);
assertFalse("Replied message should be 'replyable'", info.shouldNotReply());
assertEquals("Incorrect number of TO addresses", 1, info.getTOAddresses().size());
assertEquals("Incorrect number of CC addresses", 1, info.getCCAddresses().size());
// Send a reply to the reply
Message reply2 = new Message();
reply2.setBody("This is my reply to your reply");
reply2.setFrom(getBareJID(0));
MultipleRecipientManager.reply(getConnection(0), reply1, reply2);
// Get the reply and ensure it's ok
reply2 = (Message) collector1.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection 1 never received the reply", reply2);
info = MultipleRecipientManager.getMultipleRecipientInfo(reply2);
assertNotNull("Replied message does not contain MultipleRecipientInfo", info);
assertFalse("Replied message should be 'replyable'", info.shouldNotReply());
assertEquals("Incorrect number of TO addresses", 1, info.getTOAddresses().size());
assertEquals("Incorrect number of CC addresses", 1, info.getCCAddresses().size());
// Check that connection2 recevied 3 messages
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection2 didn't receive the 1 message", message1);
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection2 didn't receive the 2 message", message1);
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection2 didn't receive the 3 message", message1);
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNull("XMPPConnection2 received 4 messages", message1);
// Check that connection3 recevied only 1 message (was BCC in the first message)
message1 = (Message) collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection3 didn't receive the 1 message", message1);
message1 = (Message) collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNull("XMPPConnection2 received 2 messages", message1);
collector0.cancel();
collector1.cancel();
collector2.cancel();
collector3.cancel();
}
/**
* Ensures that replying is not allowed when disabled.
*/
public void testNoReply() throws XMPPException {
PacketCollector collector1 =
getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
PacketCollector collector2 =
getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
PacketCollector collector3 =
getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
// Send the intial message with multiple recipients
Message message = new Message();
message.setBody("Hola");
List<String> to = Arrays.asList(new String[]{getBareJID(1)});
List<String> cc = Arrays.asList(new String[]{getBareJID(2)});
List<String> bcc = Arrays.asList(new String[]{getBareJID(3)});
MultipleRecipientManager.send(getConnection(0), message, to, cc, bcc, null, null, true);
// Get the message and ensure it's ok
Message message1 =
(Message) collector1.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection 1 never received the message", message1);
MultipleRecipientInfo info = MultipleRecipientManager.getMultipleRecipientInfo(message1);
assertNotNull("Message 1 does not contain MultipleRecipientInfo", info);
assertTrue("Message 1 should be not 'replyable'", info.shouldNotReply());
assertEquals("Incorrect number of TO addresses", 1, info.getTOAddresses().size());
assertEquals("Incorrect number of CC addresses", 1, info.getCCAddresses().size());
// Prepare and send the reply
Message reply1 = new Message();
reply1.setBody("This is my reply");
try {
MultipleRecipientManager.reply(getConnection(1), message1, reply1);
fail("It was possible to send a reply to a not replyable message");
}
catch (XMPPException e) {
// Exception was expected since replying was not allowed
}
// Check that connection2 recevied 1 messages
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection2 didn't receive the 1 message", message1);
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNull("XMPPConnection2 received 2 messages", message1);
// Check that connection3 recevied only 1 message (was BCC in the first message)
message1 = (Message) collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNotNull("XMPPConnection3 didn't receive the 1 message", message1);
message1 = (Message) collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
assertNull("XMPPConnection2 received 2 messages", message1);
collector1.cancel();
collector2.cancel();
collector3.cancel();
}
protected int getMaxConnections() {
return 4;
}
}

View file

@ -0,0 +1,181 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.packet.OfflineMessageInfo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Tests handling of offline messaging using OfflineMessageManager. This server requires the
* server to support JEP-0013: Flexible Offline Message Retrieval.
*
* @author Gaston Dombiak
*/
public class OfflineMessageManagerTest extends SmackTestCase {
public OfflineMessageManagerTest(String arg0) {
super(arg0);
}
public void testDiscoverFlexibleRetrievalSupport() throws XMPPException {
OfflineMessageManager offlineManager = new OfflineMessageManager(getConnection(1));
assertTrue("Server does not support JEP-13", offlineManager.supportsFlexibleRetrieval());
}
/**
* While user2 is connected but unavailable, user1 sends 2 messages to user1. User2 then
* performs some "Flexible Offline Message Retrieval" checking the number of offline messages,
* retriving the headers, then the real messages of the headers and finally removing the
* loaded messages.
*/
public void testReadAndDelete() {
// Make user2 unavailable
getConnection(1).sendPacket(new Presence(Presence.Type.unavailable));
try {
Thread.sleep(500);
// User1 sends some messages to User2 which is not available at the moment
Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null);
chat.sendMessage("Test 1");
chat.sendMessage("Test 2");
Thread.sleep(500);
// User2 checks the number of offline messages
OfflineMessageManager offlineManager = new OfflineMessageManager(getConnection(1));
assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
// Check the message headers
Iterator<OfflineMessageHeader> headers = offlineManager.getHeaders();
assertTrue("No message header was found", headers.hasNext());
List<String> stamps = new ArrayList<String>();
while (headers.hasNext()) {
OfflineMessageHeader header = headers.next();
assertEquals("Incorrect sender", getFullJID(0), header.getJid());
assertNotNull("No stamp was found in the message header", header.getStamp());
stamps.add(header.getStamp());
}
assertEquals("Wrong number of headers", 2, stamps.size());
// Get the offline messages
Iterator<Message> messages = offlineManager.getMessages(stamps);
assertTrue("No message was found", messages.hasNext());
stamps = new ArrayList<String>();
while (messages.hasNext()) {
Message message = messages.next();
OfflineMessageInfo info = (OfflineMessageInfo) message.getExtension("offline",
"http://jabber.org/protocol/offline");
assertNotNull("No offline information was included in the offline message", info);
assertNotNull("No stamp was found in the message header", info.getNode());
stamps.add(info.getNode());
}
assertEquals("Wrong number of messages", 2, stamps.size());
// Check that the offline messages have not been deleted
assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
// User2 becomes available again
PacketCollector collector = getConnection(1).createPacketCollector(
new MessageTypeFilter(Message.Type.chat));
getConnection(1).sendPacket(new Presence(Presence.Type.available));
// Check that no offline messages was sent to the user
Message message = (Message) collector.nextResult(2500);
assertNull("An offline message was sent from the server", message);
// Delete the retrieved offline messages
offlineManager.deleteMessages(stamps);
// Check that there are no offline message for this user
assertEquals("Wrong number of offline messages", 0, offlineManager.getMessageCount());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* While user2 is connected but unavailable, user1 sends 2 messages to user1. User2 then
* performs some "Flexible Offline Message Retrieval" by fetching all the offline messages
* and then removing all the offline messages.
*/
public void testFetchAndPurge() {
// Make user2 unavailable
getConnection(1).sendPacket(new Presence(Presence.Type.unavailable));
try {
Thread.sleep(500);
// User1 sends some messages to User2 which is not available at the moment
Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null);
chat.sendMessage("Test 1");
chat.sendMessage("Test 2");
Thread.sleep(500);
// User2 checks the number of offline messages
OfflineMessageManager offlineManager = new OfflineMessageManager(getConnection(1));
assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
// Get all offline messages
Iterator<Message> messages = offlineManager.getMessages();
assertTrue("No message was found", messages.hasNext());
List<String> stamps = new ArrayList<String>();
while (messages.hasNext()) {
Message message = messages.next();
OfflineMessageInfo info = (OfflineMessageInfo) message.getExtension("offline",
"http://jabber.org/protocol/offline");
assertNotNull("No offline information was included in the offline message", info);
assertNotNull("No stamp was found in the message header", info.getNode());
stamps.add(info.getNode());
}
assertEquals("Wrong number of messages", 2, stamps.size());
// Check that the offline messages have not been deleted
assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
// User2 becomes available again
PacketCollector collector = getConnection(1).createPacketCollector(
new MessageTypeFilter(Message.Type.chat));
getConnection(1).sendPacket(new Presence(Presence.Type.available));
// Check that no offline messages was sent to the user
Message message = (Message) collector.nextResult(2500);
assertNull("An offline message was sent from the server", message);
// Delete all offline messages
offlineManager.deleteMessages();
// Check that there are no offline message for this user
assertEquals("Wrong number of offline messages", 0, offlineManager.getMessageCount());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,210 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import java.util.Iterator;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.test.SmackTestCase;
/**
*
* Test the Roster Exchange extension using the high level API
*
* @author Gaston Dombiak
*/
public class RosterExchangeManagerTest extends SmackTestCase {
private int entriesSent;
private int entriesReceived;
/**
* Constructor for RosterExchangeManagerTest.
* @param name
*/
public RosterExchangeManagerTest(String name) {
super(name);
}
/**
* High level API test.
* This is a simple test to use with a XMPP client and check if the client receives user1's
* roster
* 1. User_1 will send his/her roster to user_2
*/
public void testSendRoster() {
// Send user1's roster to user2
try {
RosterExchangeManager rosterExchangeManager =
new RosterExchangeManager(getConnection(0));
rosterExchangeManager.send(getConnection(0).getRoster(), getBareJID(1));
}
catch (Exception e) {
e.printStackTrace();
fail("An error occured sending the roster");
}
}
/**
* High level API test.
* This is a simple test to use with a XMPP client and check if the client receives user1's
* roster groups
* 1. User_1 will send his/her RosterGroups to user_2
*/
public void testSendRosterGroup() {
// Send user1's RosterGroups to user2
try {
RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(getConnection(0));
for (RosterGroup rosterGroup : getConnection(0).getRoster().getGroups()) {
rosterExchangeManager.send(rosterGroup, getBareJID(1));
}
}
catch (Exception e) {
e.printStackTrace();
fail("An error occured sending the roster");
}
}
/**
* High level API test.
* 1. User_1 will send his/her roster to user_2
* 2. User_2 will receive the entries and iterate over them 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 testSendAndReceiveRoster() {
RosterExchangeManager rosterExchangeManager1 = new RosterExchangeManager(getConnection(0));
RosterExchangeManager rosterExchangeManager2 = new RosterExchangeManager(getConnection(1));
// Create a RosterExchangeListener that will iterate over the received roster entries
RosterExchangeListener rosterExchangeListener = new RosterExchangeListener() {
public void entriesReceived(String from, Iterator<RemoteRosterEntry> remoteRosterEntries) {
int received = 0;
assertNotNull("From is null", from);
assertNotNull("rosterEntries is null", remoteRosterEntries);
assertTrue("Roster without entries", remoteRosterEntries.hasNext());
while (remoteRosterEntries.hasNext()) {
received++;
RemoteRosterEntry remoteEntry = remoteRosterEntries.next();
System.out.println(remoteEntry);
}
entriesReceived = received;
}
};
rosterExchangeManager2.addRosterListener(rosterExchangeListener);
// Send user1's roster to user2
try {
entriesSent = getConnection(0).getRoster().getEntryCount();
entriesReceived = 0;
rosterExchangeManager1.send(getConnection(0).getRoster(), getBareJID(1));
// Wait up to 2 seconds
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
(entriesSent != entriesReceived)) {
Thread.sleep(100);
}
}
catch (Exception e) {
fail("An error occured sending the message with the roster");
}
assertEquals(
"Number of sent and received entries does not match",
entriesSent,
entriesReceived);
}
/**
* High level API test.
* 1. User_1 will send his/her roster to user_2
* 2. User_2 will automatically add the entries that receives to his/her roster in the
* corresponding group
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
* something is wrong
*/
public void testSendAndAcceptRoster() {
RosterExchangeManager rosterExchangeManager1 = new RosterExchangeManager(getConnection(0));
RosterExchangeManager rosterExchangeManager2 = new RosterExchangeManager(getConnection(1));
// Create a RosterExchangeListener that will accept all the received roster entries
RosterExchangeListener rosterExchangeListener = new RosterExchangeListener() {
public void entriesReceived(String from, Iterator<RemoteRosterEntry> remoteRosterEntries) {
int received = 0;
assertNotNull("From is null", from);
assertNotNull("remoteRosterEntries is null", remoteRosterEntries);
assertTrue("Roster without entries", remoteRosterEntries.hasNext());
while (remoteRosterEntries.hasNext()) {
received++;
try {
RemoteRosterEntry remoteRosterEntry = remoteRosterEntries.next();
getConnection(1).getRoster().createEntry(
remoteRosterEntry.getUser(),
remoteRosterEntry.getName(),
remoteRosterEntry.getGroupArrayNames());
}
catch (Exception e) {
fail(e.toString());
}
}
entriesReceived = received;
}
};
rosterExchangeManager2.addRosterListener(rosterExchangeListener);
// Send user1's roster to user2
try {
entriesSent = getConnection(0).getRoster().getEntryCount();
entriesReceived = 0;
rosterExchangeManager1.send(getConnection(0).getRoster(), getBareJID(1));
// Wait up to 2 seconds
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
(entriesSent != entriesReceived)) {
Thread.sleep(100);
}
}
catch (Exception e) {
fail("An error occured sending the message with the roster");
}
assertEquals(
"Number of sent and received entries does not match",
entriesSent,
entriesReceived);
assertTrue("Roster2 has no entries", getConnection(1).getRoster().getEntryCount() > 0);
}
protected void setUp() throws Exception {
super.setUp();
try {
getConnection(0).getRoster().createEntry(
getBareJID(2),
"gato5",
new String[] { "Friends, Coworker" });
getConnection(0).getRoster().createEntry(getBareJID(3), "gato6", null);
Thread.sleep(100);
}
catch (Exception e) {
fail(e.getMessage());
}
}
protected int getMaxConnections() {
return 4;
}
}

View file

@ -0,0 +1,41 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smackx.packet.RosterExchangeTest;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
*
* Test suite that runs all the Roster Exchange extension tests
*
* @author Gaston Dombiak
*/
public class RosterExchangeTests {
public static Test suite() {
TestSuite suite = new TestSuite("High and low level API tests for roster exchange extension");
//$JUnit-BEGIN$
suite.addTest(new TestSuite(RosterExchangeManagerTest.class));
suite.addTest(new TestSuite(RosterExchangeTest.class));
//$JUnit-END$
return suite;
}
}

View file

@ -0,0 +1,150 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import java.util.Iterator;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.packet.DiscoverInfo.Identity;
/**
* Tests the service discovery functionality.
*
* @author Gaston Dombiak
*/
public class ServiceDiscoveryManagerTest extends SmackTestCase {
public ServiceDiscoveryManagerTest(String arg0) {
super(arg0);
}
/**
* Tests info discovery of a Smack client.
*/
public void testSmackInfo() {
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager
.getInstanceFor(getConnection(0));
try {
// Discover the information of another Smack client
DiscoverInfo info = discoManager.discoverInfo(getFullJID(1));
// Check the identity of the Smack client
Iterator<Identity> identities = info.getIdentities();
assertTrue("No identities were found", identities.hasNext());
Identity identity = identities.next();
assertEquals("Name in identity is wrong", discoManager.getIdentityName(),
identity.getName());
assertEquals("Category in identity is wrong", "client", identity.getCategory());
assertEquals("Type in identity is wrong", discoManager.getIdentityType(),
identity.getType());
assertFalse("More identities were found", identities.hasNext());
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Tests that ensures that Smack answers a 404 error when the disco#info includes a node.
*/
public void testInfoWithNode() {
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager
.getInstanceFor(getConnection(0));
try {
// Discover the information of another Smack client
discoManager.discoverInfo(getFullJID(1), "some node");
// Check the identity of the Smack client
fail("Unexpected identities were returned instead of a 404 error");
}
catch (XMPPException e) {
assertEquals("Incorrect error", 404, e.getXMPPError().getCode());
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Tests service discovery of XHTML support.
*/
public void testXHTMLFeature() {
// Check for local XHTML service support
// By default the XHTML service support is enabled in all the connections
assertTrue(XHTMLManager.isServiceEnabled(getConnection(0)));
assertTrue(XHTMLManager.isServiceEnabled(getConnection(1)));
// Check for XHTML support in connection1 from connection2
// Must specify a full JID and not a bare JID. Ensure that the server is working ok.
assertFalse(XHTMLManager.isServiceEnabled(getConnection(1), getBareJID(0)));
// Using a full JID check that the other client supports XHTML.
assertTrue(XHTMLManager.isServiceEnabled(getConnection(1), getFullJID(0)));
// Disable the XHTML Message support in connection1
XHTMLManager.setServiceEnabled(getConnection(0), false);
// Check for local XHTML service support
assertFalse(XHTMLManager.isServiceEnabled(getConnection(0)));
assertTrue(XHTMLManager.isServiceEnabled(getConnection(1)));
// Check for XHTML support in connection1 from connection2
assertFalse(XHTMLManager.isServiceEnabled(getConnection(1), getFullJID(0)));
}
/**
* Tests support for publishing items to another entity.
*/
public void testDiscoverPublishItemsSupport() {
try {
boolean canPublish = ServiceDiscoveryManager.getInstanceFor(getConnection(0))
.canPublishItems(getServiceName());
assertFalse("Wildfire does not support publishing...so far!!", canPublish);
}
catch (Exception e) {
fail(e.getMessage());
}
}
/**
* Tests publishing items to another entity.
*/
/*public void testPublishItems() {
DiscoverItems itemsToPublish = new DiscoverItems();
DiscoverItems.Item itemToPublish = new DiscoverItems.Item("pubsub.shakespeare.lit");
itemToPublish.setName("Avatar");
itemToPublish.setNode("romeo/avatar");
itemToPublish.setAction(DiscoverItems.Item.UPDATE_ACTION);
itemsToPublish.addItem(itemToPublish);
try {
ServiceDiscoveryManager.getInstanceFor(getConnection(0)).publishItems(getServiceName(),
itemsToPublish);
}
catch (Exception e) {
fail(e.getMessage());
}
}*/
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,47 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.XMPPException;
import java.util.List;
/**
* Test cases for getting the shared groups of a user.<p>
*
* Important note: This functionality is not part of the XMPP spec and it will only work
* with Wildfire.
*
* @author Gaston Dombiak
*/
public class SharedGroupsTest extends SmackTestCase {
public SharedGroupsTest(String arg0) {
super(arg0);
}
public void testGetUserSharedGroups() throws XMPPException {
List<String> groups = SharedGroupManager.getSharedGroups(getConnection(0));
assertNotNull("User groups was null", groups);
}
protected int getMaxConnections() {
return 1;
}
}

View file

@ -0,0 +1,167 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.packet.VCard;
/**
* Created by IntelliJ IDEA.
* User: Gaston
* Date: Jun 18, 2005
* Time: 1:29:30 AM
* To change this template use File | Settings | File Templates.
*/
public class VCardTest extends SmackTestCase {
public VCardTest(String arg0) {
super(arg0);
}
public void testBigFunctional() throws XMPPException {
VCard origVCard = new VCard();
origVCard.setFirstName("kir");
origVCard.setLastName("max");
origVCard.setEmailHome("foo@fee.bar");
origVCard.setEmailWork("foo@fee.www.bar");
origVCard.setJabberId("jabber@id.org");
origVCard.setOrganization("Jetbrains, s.r.o");
origVCard.setNickName("KIR");
origVCard.setField("TITLE", "Mr");
origVCard.setAddressFieldHome("STREET", "Some street & House");
origVCard.setAddressFieldWork("STREET", "Some street work");
origVCard.setPhoneWork("FAX", "3443233");
origVCard.setPhoneHome("VOICE", "3443233");
origVCard.save(getConnection(0));
VCard loaded = new VCard();
try {
loaded.load(getConnection(0));
} catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
assertEquals("Should load own VCard successfully", origVCard, loaded);
loaded = new VCard();
try {
loaded.load(getConnection(1), getBareJID(0));
} catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
assertEquals("Should load another user's VCard successfully", origVCard, loaded);
}
public void testBinaryAvatar() throws Throwable {
VCard card = new VCard();
card.setAvatar(getAvatarBinary());
card.save(getConnection(0));
VCard loaded = new VCard();
try {
loaded.load(getConnection(0));
}
catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
byte[] initialAvatar = card.getAvatar();
byte[] loadedAvatar = loaded.getAvatar();
assertEquals("Should load own Avatar successfully", initialAvatar, loadedAvatar);
loaded = new VCard();
try {
loaded.load(getConnection(1), getBareJID(0));
}
catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
assertEquals("Should load avatar successfully", card.getAvatar(), loaded.getAvatar());
}
public static byte[] getAvatarBinary() {
return StringUtils.decodeBase64(getAvatarEncoded());
}
public static String getAvatarEncoded() {
return "/9j/4AAQSkZJRgABAQEASABIAAD/4QAWRXhpZgAATU0AKgAAAAgAAAAAAAD/2wBDAAUDBAQEAwUE\n" +
"BAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/\n" +
"2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e\n" +
"Hh4eHh4eHh4eHh7/wAARCABQAFADASIAAhEBAxEB/8QAHAAAAgIDAQEAAAAAAAAAAAAABwgFBgID\n" +
"BAkB/8QAORAAAgEDAwIDBwIDBwUAAAAAAQIDBAURAAYSITEHE0EIFBUiMlFxYbEjUqEkQoGR0eHw\n" +
"M0NicsH/xAAZAQADAQEBAAAAAAAAAAAAAAACAwQBAAX/xAAgEQACAgMAAwADAAAAAAAAAAAAAQIR\n" +
"AxIhBBMxMmGR/9oADAMBAAIRAxEAPwDOor6ir6RqwhH0hfX9fx++t1FbGmYRUyEg4A6k5Ot9staw\n" +
"ny4FP8R+RDNkE9s6s1TR2yzW0190QVGOiq/0k/bj21Ko2/0Miv6bKSOKyW1aeAqzjq5B+pvXXKdy\n" +
"BRyYkYOqVd9xw1crSQWiCKnXIXCDl/nj9tUu80016u8dPPdKyC3ypzMMT4ZmGAUz9hkHJz3xqlTa\n" +
"4ilRk/oYJd8WunJjlr6NJT2RplB/fWUO7AwBDhhjIIPTVSsXhltF6FXlslLKGHzNLlmb9e+uC8bC\n" +
"t9muNHJa2qKeJ5eJhErFGABbA69Ppx+M6KUnR3Y/UFa17pilK8I5JSTjIIA/rqJ3TYWeve8UlH5a\n" +
"VKjzgGGCw7N+cd/wNDykNdBKI5KgD5sjI6aJW3qyueDyJI/MjIwSDlW/00vdPjMyRlVFMqoOMhjZ\n" +
"WR/5WGD/AIffUVUUoZ8EaIlDQJXVr0VTGfLlbA/8WJ6ah9zbdms1XGkh5JMnJGx9uhB/UHQShy0T\n" +
"X2iatSxSX96RXTIYRL64Oev761+L7UduTlc3ZII8BEHdjj0GrPZbRTVV5MskKJ5vE5Ax17Hr/wA9\n" +
"NUv2p57BtHbluul4q55qjzpFo7fM4Z6h1CgovqEGQWbOACO5KqdriDxy1fQSVO8DXF4LfZ3SmQdW\n" +
"diCfX0H21Xqu+Ri726oWadY3ZgyDDBBhcgEfc4z+NBi7XGqula9VVPlmJIUdFQfZR6D/AIdc8Ukk\n" +
"MqSxO0ciMGR1OCpHYg+h0aib7h69rCoa2RK7FSVGVHpqq+KNS1NV2aGeOsZ0qTxkhcqEVhxYnH5H\n" +
"X0xoXeDfjlNZsWnejz1dGSiwV0cYaSEDCkSAYLrj5uXV8g/VkYZyJbRfrRDdqCWiudG2QskTpLFK\n" +
"uSGAIJBwQR+Rps6cEGpbWAzdFpv07T8I63hEAIwwPXPc4Hr+dTnh8246CzPdUmm8mneNJ6eo+vkx\n" +
"IIH3HTP40cK+009SvvMYCiTv9gfXX21USUswWWKCcN0yy9QNI1oZJ7dIinSasus7UsL8iiuxxhQD\n" +
"+v37nXd4g2mtjstFVVlQ0s5qWV1KBRllznH7/jVlsdsaTckwY8YXwf0C46n/AC1xeLknvtdQW2PJ\n" +
"bLSOq+nLB/Yf10VtRaJH+RYLrZaSyxz1k9XFT0VPG0ss8zBI4kUFmLMegUKCST0AGvNvxs35W+JH\n" +
"iRdN0VUk3u8r+TQRSEjyaZOka8eTBSR8zBTjm7kd9Nr7fPiDd7LsW0bZs881Ku4pJxWzxS8S1PEq\n" +
"coCMZw5mXJBHRCpyHI0i2iquAXfSV2rYLnuW8xWq1QiSaTqzMcJEg7u59FGf2AySASJv3wVu1ktE\n" +
"V0sM816jBVJ6dIP46HAHNVBPJS2eg6qCPqALC5+DO2327sVLpMh9+uwWpIDdocfwh0JByCWz0Pz4\n" +
"PbRXscVQLYWqj8zDOMems7ZbHxl69m+iOa6fiFf8L+Fe/VPw/wA/3j3XzW8nzePHzOGccuPTljOO\n" +
"mmO8TPDSy7qc1dseC1Xnk7M6wgRVGcn+IB2bkf8AqDJwTkN0wud5oJrVd622VDxvNR1EkEjRklSy\n" +
"MVJGQDjI+w0TVE08cofQneylfrlafF2gt9NXSQ2+5RzR11PnMc4SGR05A+oYDBHUZIzhiC5lPV07\n" +
"SBlmHQ9j/rpV/ZB2tSXw7pu3u6SXS1rS+5yN1KLJ53mADsCQijPfGR2Jywe3qoeeUcYcdMY7aXKT\n" +
"TLfGxp47YSTc/crcayni8xuisxOPxqFo6ee43ISVEhWpq34tIf8Atqx/c6kaFTLZ5CygoHQnp07j\n" +
"UxV0kFPNNIsfFoqlXBX8jQyl0kyJKXBS/boqZrpZtk3CKCY00T1sckvA8UZxAUUnsCQjED14t9jp\n" +
"W9ej1bbrbuKxVtnvlFFWUFbmOaGQfKQT0P3BBAIIwQQCCCAdKn4kezjuayxz3Pacvx+2qSwp8BKy\n" +
"NfmOOPaXACjK4ZmPRNV5MTXUIj8Iza/jfclaODdlL8QiUn+1UyKk3949U6I390dOOAM/MdT27vaF\n" +
"5U4ptq2Tjzw0k9xHUd8qqI3/AKnkW+44+ugPV01RR1c1JVwS09RBI0csUqFXjdTgqwPUEEEEHWrS\n" +
"KH+/JVWXCbxM3nJVvULdhGWYkKtPGVUfYZUnA/Uk6gNxXu5bguJuN2mjnqigRpFgSMsB25cAMnHT\n" +
"J64AHYDVs234Q75vfkyfDIrbTy8szXCdYfLxn6kyZBkjA+X1B7ddWOP2e94StxhvO25TnrwqJiF/\n" +
"J8rWnOOWa7ZXtgeMO/djW2ntW3rnSwW2Kfz3pGoICs7Egt5j8PMbIAXPLkFAAIwMNB4d7xsW/bdS\n" +
"3iyAwVYZYq+hZ8yUrkdc/wAynB4t2IB7EMoTbeG3rjtXctbt+6iL3ujcK5ifmjggMrKfsVIIyAev\n" +
"UA5GurZ28dwbRW5fAK+Sje40vu0siMQyDkDzTrgSABlDd1DtjBIIySs7HkeN9HFvftPeGFjWp2/D\n" +
"T326SU8oV6yhghemkYYzwZpVLAHI5YwcZBIIJLuyN5WDxB2jJubbVX59FUModJFCy08gC8opFyeL\n" +
"rkZGSCCCCVIJ8vdO97EsZtfgZWS148lbjeZZ6Y8gecYSKItgHp88bjBwemexBIuKF3bCZMDTgggg\n" +
"GZSNStuhLRlyAAGP9P8AfOoKW6Udbeqe38i0kANQwHoFHrq0WpG9yp+fdkBb8nrr1GhexDbk2zaN\n" +
"x0vul8tlHcaZG8xI6qBZVVwCOYDAjOCRn9Toe1GwNsWyqBpduWihqkBaKogoo43AIwcMoBHQkaNP\n" +
"lgxYx6ai9xWb4lQfwQBURLyjP3HqupM2NfUPwZNWAi4WmvimKxvLxB6FW1O7XpK1VXzeROe7tqSq\n" +
"/PilaGWNkkU4ZWHUayo5nV8Fv8MakU2uHr+1uIvHtW+Hl5oNy1G+6fFZaK4RLO0a/NRyKixgOP5W\n" +
"4jD9snicHiWBGvTnaFtnnmSeZCsQIKgj6v8AbV5jlDS1AXsqBRqqGJyVs8bM0pcEL9mz2e7pvivi\n" +
"3BvCirLZteMLLDHKjRS3QlQyiPsRCQQTIO4PFDnLI9NBZKKgpaCjtdPDR0YaPhBGgRI1UfKiqOgA\n" +
"CgADtrKoqPLpKaXPVXUdPtnXTNUBLlTQR4xHlj+gHT/7pjw8oTsf/9k=";
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,67 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.packet.Version;
/**
* Test case to ensure that Smack is able to get and parse correctly iq:version packets.
*
* @author Gaston Dombiak
*/
public class VersionTest extends SmackTestCase {
public VersionTest(String arg0) {
super(arg0);
}
/**
* Get the version of the server and make sure that all the required data is present
*
* Note: This test expects the server to answer an iq:version packet.
*/
public void testGetServerVersion() {
Version version = new Version();
version.setType(IQ.Type.GET);
version.setTo(getServiceName());
// Create a packet collector to listen for a response.
PacketCollector collector = getConnection(0).createPacketCollector(new PacketIDFilter(version.getPacketID()));
getConnection(0).sendPacket(version);
// Wait up to 5 seconds for a result.
IQ result = (IQ)collector.nextResult(5000);
// Close the collector
collector.cancel();
assertNotNull("No result from the server", result);
assertEquals("Incorrect result type", IQ.Type.RESULT, result.getType());
assertNotNull("No name specified in the result", ((Version)result).getName());
assertNotNull("No version specified in the result", ((Version)result).getVersion());
}
protected int getMaxConnections() {
return 1;
}
}

View file

@ -0,0 +1,234 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import java.util.Iterator;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.ThreadFilter;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.test.SmackTestCase;
/**
* Test the XHTML extension using the high level API
*
* @author Gaston Dombiak
*/
public class XHTMLManagerTest extends SmackTestCase {
private int bodiesSent;
private int bodiesReceived;
/**
* Constructor for XHTMLManagerTest.
* @param name
*/
public XHTMLManagerTest(String name) {
super(name);
}
/**
* High level API test.
* This is a simple test to use with a XMPP client and check if the client receives the message
* 1. User_1 will send a message with formatted text (XHTML) to user_2
*/
public void testSendSimpleXHTMLMessage() {
// User1 creates a chat with user2
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
// User1 creates a message to send to user2
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("Hey John, this is my new green!!!!");
// Create an XHTMLText to send with the message
XHTMLText xhtmlText = new XHTMLText(null, null);
xhtmlText.appendOpenParagraphTag("font-size:large");
xhtmlText.append("Hey John, this is my new ");
xhtmlText.appendOpenSpanTag("color:green");
xhtmlText.append("green");
xhtmlText.appendCloseSpanTag();
xhtmlText.appendOpenEmTag();
xhtmlText.append("!!!!");
xhtmlText.appendCloseEmTag();
xhtmlText.appendCloseParagraphTag();
// Add the XHTML text to the message
XHTMLManager.addBody(msg, xhtmlText.toString());
// User1 sends the message that contains the XHTML to user2
try {
chat1.sendMessage(msg);
Thread.sleep(200);
} catch (Exception e) {
fail("An error occured sending the message with XHTML");
}
}
/**
* High level API test.
* 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 testSendSimpleXHTMLMessageAndDisplayReceivedXHTMLMessage() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
final PacketCollector chat2 = getConnection(1).createPacketCollector(
new ThreadFilter(chat1.getThreadID()));
// User1 creates a message to send to user2
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("Hey John, this is my new green!!!!");
// Create an XHTMLText to send with the message
XHTMLText xhtmlText = new XHTMLText(null, null);
xhtmlText.appendOpenParagraphTag("font-size:large");
xhtmlText.append("Hey John, this is my new ");
xhtmlText.appendOpenSpanTag("color:green");
xhtmlText.append("green");
xhtmlText.appendCloseSpanTag();
xhtmlText.appendOpenEmTag();
xhtmlText.append("!!!!");
xhtmlText.appendCloseEmTag();
xhtmlText.appendCloseParagraphTag();
// Add the XHTML text to the message
XHTMLManager.addBody(msg, xhtmlText.toString());
// User1 sends the message that contains the XHTML to user2
try {
chat1.sendMessage(msg);
} catch (Exception e) {
fail("An error occured sending the message with XHTML");
}
Packet packet = chat2.nextResult(2000);
Message message = (Message) packet;
assertTrue(
"The received message is not an XHTML Message",
XHTMLManager.isXHTMLMessage(message));
try {
assertTrue(
"Message without XHTML bodies",
XHTMLManager.getBodies(message).hasNext());
for (Iterator<String> it = XHTMLManager.getBodies(message); it.hasNext();) {
String body = it.next();
System.out.println(body);
}
}
catch (ClassCastException e) {
fail("ClassCastException - Most probable cause is that smack providers is misconfigured");
}
assertNotNull("No reply received", msg);
}
/**
* 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 PacketCollector chat2 = getConnection(1).createPacketCollector(
new ThreadFilter(chat1.getThreadID()));
// 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 XHTMLText to send with the message (in Spanish)
XHTMLText xhtmlText = new XHTMLText(null, "es-ES");
xhtmlText.appendOpenHeaderTag(1, null);
xhtmlText.append("impresionante!");
xhtmlText.appendCloseHeaderTag(1);
xhtmlText.appendOpenParagraphTag(null);
xhtmlText.append("Como Emerson dijo una vez:");
xhtmlText.appendCloseParagraphTag();
xhtmlText.appendOpenBlockQuoteTag(null);
xhtmlText.appendOpenParagraphTag(null);
xhtmlText.append("Una consistencia rid&#237;cula es el espantajo de mentes peque&#241;as.");
xhtmlText.appendCloseParagraphTag();
xhtmlText.appendCloseBlockQuoteTag();
// Add the XHTML text to the message
XHTMLManager.addBody(msg, xhtmlText.toString());
// Create an XHTMLText to send with the message (in English)
xhtmlText = new XHTMLText(null, "en-US");
xhtmlText.appendOpenHeaderTag(1, null);
xhtmlText.append("awesome!");
xhtmlText.appendCloseHeaderTag(1);
xhtmlText.appendOpenParagraphTag(null);
xhtmlText.append("As Emerson once said:");
xhtmlText.appendCloseParagraphTag();
xhtmlText.appendOpenBlockQuoteTag(null);
xhtmlText.appendOpenParagraphTag(null);
xhtmlText.append("A foolish consistency is the hobgoblin of little minds.");
xhtmlText.appendCloseParagraphTag();
xhtmlText.appendCloseBlockQuoteTag();
// Add the XHTML text to the message
XHTMLManager.addBody(msg, xhtmlText.toString());
// User1 sends the message that contains the XHTML to user2
try {
bodiesSent = 2;
bodiesReceived = 0;
chat1.sendMessage(msg);
} catch (Exception e) {
fail("An error occured sending the message with XHTML");
}
Packet packet = chat2.nextResult(2000);
int received = 0;
Message message = (Message) packet;
assertTrue(
"The received message is not an XHTML Message",
XHTMLManager.isXHTMLMessage(message));
try {
assertTrue(
"Message without XHTML bodies",
XHTMLManager.getBodies(message).hasNext());
for (Iterator<String> it = XHTMLManager.getBodies(message); it.hasNext();) {
received++;
String body = it.next();
System.out.println(body);
}
bodiesReceived = received;
}
catch (ClassCastException e) {
fail("ClassCastException - Most probable cause is that smack providers" +
"is misconfigured");
}
assertEquals(
"Number of sent and received XHTMP bodies does not match",
bodiesSent,
bodiesReceived);
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,40 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
import org.jivesoftware.smackx.packet.XHTMLExtensionTest;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* Test suite that runs all the XHTML support tests
*
* @author Gaston Dombiak
*/
public class XHTMLSupportTests {
public static Test suite() {
TestSuite suite = new TestSuite("High and low level API tests for XHTML support");
//$JUnit-BEGIN$
suite.addTest(new TestSuite(XHTMLManagerTest.class));
suite.addTest(new TestSuite(XHTMLExtensionTest.class));
//$JUnit-END$
return suite;
}
}

View file

@ -0,0 +1,259 @@
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.bytestreams.ibb;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
import java.util.concurrent.SynchronousQueue;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamListener;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamManager;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamRequest;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamSession;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamManager.StanzaType;
import org.jivesoftware.smackx.bytestreams.ibb.packet.Open;
/**
* Test for In-Band Bytestreams with real XMPP servers.
*
* @author Henning Staib
*/
public class InBandBytestreamTest extends SmackTestCase {
/* the amount of data transmitted in each test */
int dataSize = 1024000;
public InBandBytestreamTest(String arg0) {
super(arg0);
}
/**
* Target should respond with not-acceptable error if no listeners for incoming In-Band
* Bytestream requests are registered.
*
* @throws XMPPException should not happen
*/
public void testRespondWithErrorOnInBandBytestreamRequest() throws XMPPException {
XMPPConnection targetConnection = getConnection(0);
XMPPConnection initiatorConnection = getConnection(1);
Open open = new Open("sessionID", 1024);
open.setFrom(initiatorConnection.getUser());
open.setTo(targetConnection.getUser());
PacketCollector collector = initiatorConnection.createPacketCollector(new PacketIDFilter(
open.getPacketID()));
initiatorConnection.sendPacket(open);
Packet result = collector.nextResult();
assertNotNull(result.getError());
assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition());
}
/**
* An In-Band Bytestream should be successfully established using IQ stanzas.
*
* @throws Exception should not happen
*/
public void testInBandBytestreamWithIQStanzas() throws Exception {
XMPPConnection initiatorConnection = getConnection(0);
XMPPConnection targetConnection = getConnection(1);
// test data
Random rand = new Random();
final byte[] data = new byte[dataSize];
rand.nextBytes(data);
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
InBandBytestreamManager targetByteStreamManager = InBandBytestreamManager.getByteStreamManager(targetConnection);
InBandBytestreamListener incomingByteStreamListener = new InBandBytestreamListener() {
public void incomingBytestreamRequest(InBandBytestreamRequest request) {
InputStream inputStream;
try {
inputStream = request.accept().getInputStream();
byte[] receivedData = new byte[dataSize];
int totalRead = 0;
while (totalRead < dataSize) {
int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
totalRead += read;
}
queue.put(receivedData);
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
InBandBytestreamManager initiatorByteStreamManager = InBandBytestreamManager.getByteStreamManager(initiatorConnection);
OutputStream outputStream = initiatorByteStreamManager.establishSession(
targetConnection.getUser()).getOutputStream();
// verify stream
outputStream.write(data);
outputStream.flush();
outputStream.close();
assertEquals("received data not equal to sent data", data, queue.take());
}
/**
* An In-Band Bytestream should be successfully established using message stanzas.
*
* @throws Exception should not happen
*/
public void testInBandBytestreamWithMessageStanzas() throws Exception {
XMPPConnection initiatorConnection = getConnection(0);
XMPPConnection targetConnection = getConnection(1);
// test data
Random rand = new Random();
final byte[] data = new byte[dataSize];
rand.nextBytes(data);
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
InBandBytestreamManager targetByteStreamManager = InBandBytestreamManager.getByteStreamManager(targetConnection);
InBandBytestreamListener incomingByteStreamListener = new InBandBytestreamListener() {
public void incomingBytestreamRequest(InBandBytestreamRequest request) {
InputStream inputStream;
try {
inputStream = request.accept().getInputStream();
byte[] receivedData = new byte[dataSize];
int totalRead = 0;
while (totalRead < dataSize) {
int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
totalRead += read;
}
queue.put(receivedData);
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
InBandBytestreamManager initiatorByteStreamManager = InBandBytestreamManager.getByteStreamManager(initiatorConnection);
initiatorByteStreamManager.setStanza(StanzaType.MESSAGE);
OutputStream outputStream = initiatorByteStreamManager.establishSession(
targetConnection.getUser()).getOutputStream();
// verify stream
outputStream.write(data);
outputStream.flush();
outputStream.close();
assertEquals("received data not equal to sent data", data, queue.take());
}
/**
* An In-Band Bytestream should be successfully established using IQ stanzas. The established
* session should transfer data bidirectional.
*
* @throws Exception should not happen
*/
public void testBiDirectionalInBandBytestream() throws Exception {
XMPPConnection initiatorConnection = getConnection(0);
XMPPConnection targetConnection = getConnection(1);
// test data
Random rand = new Random();
final byte[] data = new byte[dataSize];
rand.nextBytes(data);
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
InBandBytestreamManager targetByteStreamManager = InBandBytestreamManager.getByteStreamManager(targetConnection);
InBandBytestreamListener incomingByteStreamListener = new InBandBytestreamListener() {
public void incomingBytestreamRequest(InBandBytestreamRequest request) {
try {
InBandBytestreamSession session = request.accept();
OutputStream outputStream = session.getOutputStream();
outputStream.write(data);
outputStream.flush();
InputStream inputStream = session.getInputStream();
byte[] receivedData = new byte[dataSize];
int totalRead = 0;
while (totalRead < dataSize) {
int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
totalRead += read;
}
queue.put(receivedData);
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
InBandBytestreamManager initiatorByteStreamManager = InBandBytestreamManager.getByteStreamManager(initiatorConnection);
InBandBytestreamSession session = initiatorByteStreamManager.establishSession(targetConnection.getUser());
// verify stream
byte[] receivedData = new byte[dataSize];
InputStream inputStream = session.getInputStream();
int totalRead = 0;
while (totalRead < dataSize) {
int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
totalRead += read;
}
assertEquals("sent data not equal to received data", data, receivedData);
OutputStream outputStream = session.getOutputStream();
outputStream.write(data);
outputStream.flush();
outputStream.close();
assertEquals("received data not equal to sent data", data, queue.take());
}
@Override
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,337 @@
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.bytestreams.socks5;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamListener;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamManager;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamRequest;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamSession;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5PacketUtils;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream;
/**
* Test for Socks5 bytestreams with real XMPP servers.
*
* @author Henning Staib
*/
public class Socks5ByteStreamTest extends SmackTestCase {
/**
* Constructor
*
* @param arg0
*/
public Socks5ByteStreamTest(String arg0) {
super(arg0);
}
/**
* Socks5 feature should be added to the service discovery on Smack startup.
*
* @throws XMPPException should not happen
*/
public void testInitializationSocks5FeaturesAndListenerOnStartup() throws XMPPException {
XMPPConnection connection = getConnection(0);
assertTrue(ServiceDiscoveryManager.getInstanceFor(connection).includesFeature(
Socks5BytestreamManager.NAMESPACE));
}
/**
* Target should respond with not-acceptable error if no listeners for incoming Socks5
* bytestream requests are registered.
*
* @throws XMPPException should not happen
*/
public void testRespondWithErrorOnSocks5BytestreamRequest() throws XMPPException {
XMPPConnection targetConnection = getConnection(0);
XMPPConnection initiatorConnection = getConnection(1);
Bytestream bytestreamInitiation = Socks5PacketUtils.createBytestreamInitiation(
initiatorConnection.getUser(), targetConnection.getUser(), "session_id");
bytestreamInitiation.addStreamHost("proxy.localhost", "127.0.0.1", 7777);
PacketCollector collector = initiatorConnection.createPacketCollector(new PacketIDFilter(
bytestreamInitiation.getPacketID()));
initiatorConnection.sendPacket(bytestreamInitiation);
Packet result = collector.nextResult();
assertNotNull(result.getError());
assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition());
}
/**
* Socks5 bytestream should be successfully established using the local Socks5 proxy.
*
* @throws Exception should not happen
*/
public void testSocks5BytestreamWithLocalSocks5Proxy() throws Exception {
// setup port for local socks5 proxy
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
SmackConfiguration.setLocalSocks5ProxyPort(7778);
Socks5Proxy socks5Proxy = Socks5Proxy.getSocks5Proxy();
socks5Proxy.start();
assertTrue(socks5Proxy.isRunning());
XMPPConnection initiatorConnection = getConnection(0);
XMPPConnection targetConnection = getConnection(1);
// test data
final byte[] data = new byte[] { 1, 2, 3 };
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
Socks5BytestreamManager targetByteStreamManager = Socks5BytestreamManager.getBytestreamManager(targetConnection);
Socks5BytestreamListener incomingByteStreamListener = new Socks5BytestreamListener() {
public void incomingBytestreamRequest(Socks5BytestreamRequest request) {
InputStream inputStream;
try {
Socks5BytestreamSession session = request.accept();
inputStream = session.getInputStream();
byte[] receivedData = new byte[3];
inputStream.read(receivedData);
queue.put(receivedData);
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
Socks5BytestreamManager initiatorByteStreamManager = Socks5BytestreamManager.getBytestreamManager(initiatorConnection);
Socks5BytestreamSession session = initiatorByteStreamManager.establishSession(
targetConnection.getUser());
OutputStream outputStream = session.getOutputStream();
assertTrue(session.isDirect());
// verify stream
outputStream.write(data);
outputStream.flush();
outputStream.close();
assertEquals("received data not equal to sent data", data, queue.take());
// reset default configuration
SmackConfiguration.setLocalSocks5ProxyPort(7777);
}
/**
* Socks5 bytestream should be successfully established using a Socks5 proxy provided by the
* XMPP server.
* <p>
* This test will fail if the XMPP server doesn't provide any Socks5 proxies or the Socks5 proxy
* only allows Socks5 bytestreams in the context of a file transfer (like Openfire in default
* configuration, see xmpp.proxy.transfer.required flag).
*
* @throws Exception if no Socks5 proxies found or proxy is unwilling to activate Socks5
* bytestream
*/
public void testSocks5BytestreamWithRemoteSocks5Proxy() throws Exception {
// disable local socks5 proxy
SmackConfiguration.setLocalSocks5ProxyEnabled(false);
Socks5Proxy.getSocks5Proxy().stop();
assertFalse(Socks5Proxy.getSocks5Proxy().isRunning());
XMPPConnection initiatorConnection = getConnection(0);
XMPPConnection targetConnection = getConnection(1);
// test data
final byte[] data = new byte[] { 1, 2, 3 };
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
Socks5BytestreamManager targetByteStreamManager = Socks5BytestreamManager.getBytestreamManager(targetConnection);
Socks5BytestreamListener incomingByteStreamListener = new Socks5BytestreamListener() {
public void incomingBytestreamRequest(Socks5BytestreamRequest request) {
InputStream inputStream;
try {
Socks5BytestreamSession session = request.accept();
inputStream = session.getInputStream();
byte[] receivedData = new byte[3];
inputStream.read(receivedData);
queue.put(receivedData);
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
Socks5BytestreamManager initiatorByteStreamManager = Socks5BytestreamManager.getBytestreamManager(initiatorConnection);
Socks5BytestreamSession session = initiatorByteStreamManager.establishSession(
targetConnection.getUser());
OutputStream outputStream = session.getOutputStream();
assertTrue(session.isMediated());
// verify stream
outputStream.write(data);
outputStream.flush();
outputStream.close();
assertEquals("received data not equal to sent data", data, queue.take());
// reset default configuration
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
Socks5Proxy.getSocks5Proxy().start();
}
/**
* Socks5 bytestream should be successfully established using a Socks5 proxy provided by the
* XMPP server. The established connection should transfer data bidirectional if the Socks5
* proxy supports it.
* <p>
* Support for bidirectional Socks5 bytestream:
* <ul>
* <li>Openfire (3.6.4 and below) - no</li>
* <li>ejabberd (2.0.5 and higher) - yes</li>
* </ul>
* <p>
* This test will fail if the XMPP server doesn't provide any Socks5 proxies or the Socks5 proxy
* only allows Socks5 bytestreams in the context of a file transfer (like Openfire in default
* configuration, see xmpp.proxy.transfer.required flag).
*
* @throws Exception if no Socks5 proxies found or proxy is unwilling to activate Socks5
* bytestream
*/
public void testBiDirectionalSocks5BytestreamWithRemoteSocks5Proxy() throws Exception {
XMPPConnection initiatorConnection = getConnection(0);
// disable local socks5 proxy
SmackConfiguration.setLocalSocks5ProxyEnabled(false);
Socks5Proxy.getSocks5Proxy().stop();
assertFalse(Socks5Proxy.getSocks5Proxy().isRunning());
XMPPConnection targetConnection = getConnection(1);
// test data
final byte[] data = new byte[] { 1, 2, 3 };
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
Socks5BytestreamManager targetByteStreamManager = Socks5BytestreamManager.getBytestreamManager(targetConnection);
Socks5BytestreamListener incomingByteStreamListener = new Socks5BytestreamListener() {
public void incomingBytestreamRequest(Socks5BytestreamRequest request) {
try {
Socks5BytestreamSession session = request.accept();
OutputStream outputStream = session.getOutputStream();
outputStream.write(data);
outputStream.flush();
InputStream inputStream = session.getInputStream();
byte[] receivedData = new byte[3];
inputStream.read(receivedData);
queue.put(receivedData);
session.close();
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
Socks5BytestreamManager initiatorByteStreamManager = Socks5BytestreamManager.getBytestreamManager(initiatorConnection);
Socks5BytestreamSession session = initiatorByteStreamManager.establishSession(targetConnection.getUser());
assertTrue(session.isMediated());
// verify stream
final byte[] receivedData = new byte[3];
final InputStream inputStream = session.getInputStream();
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
public Integer call() throws Exception {
return inputStream.read(receivedData);
}
});
Thread executor = new Thread(futureTask);
executor.start();
try {
futureTask.get(2000, TimeUnit.MILLISECONDS);
}
catch (TimeoutException e) {
// reset default configuration
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
Socks5Proxy.getSocks5Proxy().start();
fail("Couldn't send data from target to inititator");
}
assertEquals("sent data not equal to received data", data, receivedData);
OutputStream outputStream = session.getOutputStream();
outputStream.write(data);
outputStream.flush();
outputStream.close();
assertEquals("received data not equal to sent data", data, queue.take());
session.close();
// reset default configuration
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
Socks5Proxy.getSocks5Proxy().start();
}
@Override
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,111 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.commands;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.packet.DiscoverItems;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
/**
* AdHocCommand tests.
*
* @author Matt Tucker
*/
public class AdHocCommandDiscoTest extends SmackTestCase {
/**
* Constructor for test.
* @param arg0 argument.
*/
public AdHocCommandDiscoTest(String arg0) {
super(arg0);
}
public void testAdHocCommands() {
try {
AdHocCommandManager manager1 = AdHocCommandManager.getAddHocCommandsManager(getConnection(0));
manager1.registerCommand("test", "test node", LocalCommand.class);
manager1.registerCommand("test2", "test node", new LocalCommandFactory() {
public LocalCommand getInstance() throws InstantiationException, IllegalAccessException {
return new LocalCommand() {
public boolean isLastStage() {
return true;
}
public boolean hasPermission(String jid) {
return true;
}
public void execute() throws XMPPException {
Form result = new Form(Form.TYPE_RESULT);
FormField resultField = new FormField("test2");
resultField.setLabel("test node");
resultField.addValue("it worked");
result.addField(resultField);
setForm(result);
}
public void next(Form response) throws XMPPException {
//
}
public void complete(Form response) throws XMPPException {
//
}
public void prev() throws XMPPException {
//
}
public void cancel() throws XMPPException {
//
}
};
}
});
AdHocCommandManager manager2 = AdHocCommandManager.getAddHocCommandsManager(getConnection(1));
DiscoverItems items = manager2.discoverCommands(getFullJID(0));
assertTrue("Disco for command test failed", items.getItems().next().getNode().equals("test"));
RemoteCommand command = manager2.getRemoteCommand(getFullJID(0), "test2");
command.execute();
assertEquals("Disco for command test failed", command.getForm().getField("test2").getValues().next(), "it worked");
}
catch (Exception e) {
fail(e.getMessage());
}
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,147 @@
package org.jivesoftware.smackx.entitycaps;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.TCPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.filter.IQTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.packet.DiscoverInfo;
public class EntityCapsTest extends SmackTestCase {
private static final String DISCOVER_TEST_FEATURE = "entityCapsTest";
XMPPTCPConnection con0;
XMPPTCPConnection con1;
EntityCapsManager ecm0;
EntityCapsManager ecm1;
ServiceDiscoveryManager sdm0;
ServiceDiscoveryManager sdm1;
private boolean discoInfoSend = false;
public EntityCapsTest(String arg0) {
super(arg0);
}
@Override
protected int getMaxConnections() {
return 2;
}
@Override
protected void setUp() throws Exception {
super.setUp();
SmackConfiguration.setAutoEnableEntityCaps(true);
con0 = getConnection(0);
con1 = getConnection(1);
ecm0 = EntityCapsManager.getInstanceFor(getConnection(0));
ecm1 = EntityCapsManager.getInstanceFor(getConnection(1));
sdm0 = ServiceDiscoveryManager.getInstanceFor(con0);
sdm1 = ServiceDiscoveryManager.getInstanceFor(con1);
letsAllBeFriends();
}
public void testLocalEntityCaps() throws InterruptedException {
DiscoverInfo info = EntityCapsManager.getDiscoveryInfoByNodeVer(ecm1.getLocalNodeVer());
assertFalse(info.containsFeature(DISCOVER_TEST_FEATURE));
dropWholeEntityCapsCache();
// This should cause a new presence stanza from con1 with and updated
// 'ver' String
sdm1.addFeature(DISCOVER_TEST_FEATURE);
// Give the server some time to handle the stanza and send it to con0
Thread.sleep(2000);
// The presence stanza should get received by con0 and the data should
// be recorded in the map
// Note that while both connections use the same static Entity Caps
// cache,
// it's assured that *not* con1 added the data to the Entity Caps cache.
// Every time the entities features
// and identities change only a new caps 'ver' is calculated and send
// with the presence stanza
// The other connection has to receive this stanza and record the
// information in order for this test to succeed.
info = EntityCapsManager.getDiscoveryInfoByNodeVer(ecm1.getLocalNodeVer());
assertNotNull(info);
assertTrue(info.containsFeature(DISCOVER_TEST_FEATURE));
}
/**
* Test if entity caps actually prevent a disco info request and reply
*
* @throws XMPPException
*
*/
public void testPreventDiscoInfo() throws XMPPException {
con0.addPacketSendingListener(new PacketListener() {
@Override
public void processPacket(Packet packet) {
discoInfoSend = true;
}
}, new AndFilter(new PacketTypeFilter(DiscoverInfo.class), new IQTypeFilter(IQ.Type.GET)));
// add a bogus feature so that con1 ver won't match con0's
sdm1.addFeature(DISCOVER_TEST_FEATURE);
dropCapsCache();
// discover that
DiscoverInfo info = sdm0.discoverInfo(con1.getUser());
// that discovery should cause a disco#info
assertTrue(discoInfoSend);
assertTrue(info.containsFeature(DISCOVER_TEST_FEATURE));
discoInfoSend = false;
// discover that
info = sdm0.discoverInfo(con1.getUser());
// that discovery shouldn't cause a disco#info
assertFalse(discoInfoSend);
assertTrue(info.containsFeature(DISCOVER_TEST_FEATURE));
}
public void testCapsChanged() {
String nodeVerBefore = EntityCapsManager.getNodeVersionByJid(con1.getUser());
sdm1.addFeature(DISCOVER_TEST_FEATURE);
String nodeVerAfter = EntityCapsManager.getNodeVersionByJid(con1.getUser());
assertFalse(nodeVerBefore.equals(nodeVerAfter));
}
public void testEntityCaps() throws XMPPException, InterruptedException {
dropWholeEntityCapsCache();
sdm1.addFeature(DISCOVER_TEST_FEATURE);
Thread.sleep(3000);
DiscoverInfo info = sdm0.discoverInfo(con1.getUser());
assertTrue(info.containsFeature(DISCOVER_TEST_FEATURE));
String u1ver = EntityCapsManager.getNodeVersionByJid(con1.getUser());
assertNotNull(u1ver);
DiscoverInfo entityInfo = EntityCapsManager.caps.get(u1ver);
assertNotNull(entityInfo);
assertEquals(info.toXML(), entityInfo.toXML());
}
private static void dropWholeEntityCapsCache() {
EntityCapsManager.caps.clear();
EntityCapsManager.jidCaps.clear();
}
private static void dropCapsCache() {
EntityCapsManager.caps.clear();
}
}

View file

@ -0,0 +1,117 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.muc;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Tests creating new MUC rooms.
*
* @author Gaston Dombiak
*/
public class MultiUserChatCreationTest extends SmackTestCase {
private String room;
/**
* Constructor for MultiUserChatCreationTest.
* @param arg0
*/
public MultiUserChatCreationTest(String arg0) {
super(arg0);
}
/**
* Tests creating a new "Reserved Room".
*/
public void testCreateReservedRoom() {
MultiUserChat muc = new MultiUserChat(getConnection(0), room);
try {
// Create the room
muc.create("testbot1");
// Get the the room's configuration form
Form form = muc.getConfigurationForm();
assertNotNull("No room configuration form", form);
// Create a new form to submit based on the original form
Form submitForm = form.createAnswerForm();
// Add default answers to the form to submit
for (Iterator<FormField> fields = form.getFields(); fields.hasNext();) {
FormField field = fields.next();
if (!FormField.TYPE_HIDDEN.equals(field.getType())
&& field.getVariable() != null) {
// Sets the default value as the answer
submitForm.setDefaultAnswer(field.getVariable());
}
}
List<String> owners = new ArrayList<String>();
owners.add(getBareJID(0));
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
// Update the new room's configuration
muc.sendConfigurationForm(submitForm);
// Destroy the new room
muc.destroy("The room has almost no activity...", null);
}
catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Tests creating a new "Instant Room".
*/
public void testCreateInstantRoom() {
MultiUserChat muc = new MultiUserChat(getConnection(0), room);
try {
// Create the room
muc.create("testbot");
// Send an empty room configuration form which indicates that we want
// an instant room
muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
// Destroy the new room
muc.destroy("The room has almost no activity...", null);
}
catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
protected int getMaxConnections() {
return 2;
}
protected void setUp() throws Exception {
super.setUp();
room = "fruta124@" + getMUCDomain();
}
}

View file

@ -0,0 +1,132 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.packet;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.test.SmackTestCase;
/**
*
* Test the MessageEvent extension using the low level API
*
* @author Gaston Dombiak
*/
public class MessageEventTest extends SmackTestCase {
public MessageEventTest(String name) {
super(name);
}
/**
* Low level API test.
* This is a simple test to use with a XMPP client and check if the client receives the
* message
* 1. User_1 will send a message to user_2 requesting to be notified when any of these events
* occurs: offline, composing, displayed or delivered
*/
public void testSendMessageEventRequest() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
// Create the message to send with the roster
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("An interesting body comes here...");
// Create a MessageEvent Package and add it to the message
MessageEvent messageEvent = new MessageEvent();
messageEvent.setComposing(true);
messageEvent.setDelivered(true);
messageEvent.setDisplayed(true);
messageEvent.setOffline(true);
msg.addExtension(messageEvent);
// Send the message that contains the notifications request
try {
chat1.sendMessage(msg);
// Wait half second so that the complete test can run
Thread.sleep(200);
}
catch (Exception e) {
fail("An error occured sending the message");
}
}
/**
* Low level API test.
* This is a simple test to use with a XMPP client, check if the client receives the
* message and display in the console any notification
* 1. User_1 will send a message to user_2 requesting to be notified when any of these events
* occurs: offline, composing, displayed or delivered
* 2. User_2 will use a XMPP client (like Exodus) to display the message and compose a reply
* 3. User_1 will display any notification that receives
*/
public void testSendMessageEventRequestAndDisplayNotifications() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
// Create a Listener that listens for Messages with the extension "jabber:x:roster"
// This listener will listen on the conn2 and answer an ACK if everything is ok
PacketFilter packetFilter = new PacketExtensionFilter("x", "jabber:x:event");
PacketListener packetListener = new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
try {
MessageEvent messageEvent =
(MessageEvent) message.getExtension("x", "jabber:x:event");
assertNotNull("Message without extension \"jabber:x:event\"", messageEvent);
assertTrue(
"Message event is a request not a notification",
!messageEvent.isMessageEventRequest());
System.out.println(messageEvent.toXML());
}
catch (ClassCastException e) {
fail("ClassCastException - Most probable cause is that smack providers is misconfigured");
}
}
};
getConnection(0).addPacketListener(packetListener, packetFilter);
// Create the message to send with the roster
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("An interesting body comes here...");
// Create a MessageEvent Package and add it to the message
MessageEvent messageEvent = new MessageEvent();
messageEvent.setComposing(true);
messageEvent.setDelivered(true);
messageEvent.setDisplayed(true);
messageEvent.setOffline(true);
msg.addExtension(messageEvent);
// Send the message that contains the notifications request
try {
chat1.sendMessage(msg);
// Wait half second so that the complete test can run
Thread.sleep(200);
}
catch (Exception e) {
fail("An error occured sending the message");
}
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,185 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.packet;
import java.util.Iterator;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.*;
/**
*
* Test the Roster Exchange extension using the low level API
*
* @author Gaston Dombiak
*/
public class RosterExchangeTest extends SmackTestCase {
public RosterExchangeTest(String arg0) {
super(arg0);
}
/**
* Low level API test.
* This is a simple test to use with a XMPP client and check if the client receives the message
* 1. User_1 will send his/her roster entries to user_2
*/
public void testSendRosterEntries() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
// Create the message to send with the roster
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("This message contains roster items.");
// Create a RosterExchange Package and add it to the message
assertTrue("Roster has no entries", getConnection(0).getRoster().getEntryCount() > 0);
RosterExchange rosterExchange = new RosterExchange(getConnection(0).getRoster());
msg.addExtension(rosterExchange);
// Send the message that contains the roster
try {
chat1.sendMessage(msg);
} catch (Exception e) {
fail("An error occured sending the message with the roster");
}
}
/**
* Low level API test.
* 1. User_1 will send his/her roster entries to user_2
* 2. User_2 will receive the entries and iterate over them 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 testSendAndReceiveRosterEntries() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
final PacketCollector chat2 = getConnection(1).createPacketCollector(
new ThreadFilter(chat1.getThreadID()));
// Create the message to send with the roster
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("This message contains roster items.");
// Create a RosterExchange Package and add it to the message
assertTrue("Roster has no entries", getConnection(0).getRoster().getEntryCount() > 0);
RosterExchange rosterExchange = new RosterExchange(getConnection(0).getRoster());
msg.addExtension(rosterExchange);
// Send the message that contains the roster
try {
chat1.sendMessage(msg);
} catch (Exception e) {
fail("An error occured sending the message with the roster");
}
// Wait for 2 seconds for a reply
Packet packet = chat2.nextResult(2000);
Message message = (Message) packet;
assertNotNull("Body is null", message.getBody());
try {
rosterExchange =
(RosterExchange) message.getExtension("x", "jabber:x:roster");
assertNotNull("Message without extension \"jabber:x:roster\"", rosterExchange);
assertTrue(
"Roster without entries",
rosterExchange.getRosterEntries().hasNext());
}
catch (ClassCastException e) {
fail("ClassCastException - Most probable cause is that smack providers is misconfigured");
}
}
/**
* Low level API test.
* 1. User_1 will send his/her roster entries to user_2
* 2. User_2 will automatically add the entries that receives to his/her roster in the corresponding group
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then something is wrong
*/
public void testSendAndAcceptRosterEntries() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
final PacketCollector chat2 = getConnection(1).createPacketCollector(
new ThreadFilter(chat1.getThreadID()));
// Create the message to send with the roster
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("This message contains roster items.");
// Create a RosterExchange Package and add it to the message
assertTrue("Roster has no entries", getConnection(0).getRoster().getEntryCount() > 0);
RosterExchange rosterExchange = new RosterExchange(getConnection(0).getRoster());
msg.addExtension(rosterExchange);
// Send the message that contains the roster
try {
chat1.sendMessage(msg);
} catch (Exception e) {
fail("An error occured sending the message with the roster");
}
// Wait for 10 seconds for a reply
Packet packet = chat2.nextResult(5000);
Message message = (Message) packet;
assertNotNull("Body is null", message.getBody());
try {
rosterExchange =
(RosterExchange) message.getExtension("x", "jabber:x:roster");
assertNotNull("Message without extension \"jabber:x:roster\"", rosterExchange);
assertTrue(
"Roster without entries",
rosterExchange.getRosterEntries().hasNext());
// Add the roster entries to user2's roster
for (Iterator<RemoteRosterEntry> it = rosterExchange.getRosterEntries(); it.hasNext();) {
RemoteRosterEntry remoteRosterEntry = it.next();
getConnection(1).getRoster().createEntry(
remoteRosterEntry.getUser(),
remoteRosterEntry.getName(),
remoteRosterEntry.getGroupArrayNames());
}
}
catch (ClassCastException e) {
fail("ClassCastException - Most probable cause is that smack providers is misconfigured");
}
catch (Exception e) {
fail(e.toString());
}
assertTrue("Roster2 has no entries", getConnection(1).getRoster().getEntryCount() > 0);
}
protected void setUp() throws Exception {
super.setUp();
try {
getConnection(0).getRoster().createEntry(
getBareJID(2),
"gato5",
new String[] { "Friends, Coworker" });
getConnection(0).getRoster().createEntry(getBareJID(3), "gato6", null);
Thread.sleep(300);
} catch (Exception e) {
fail(e.getMessage());
}
}
protected int getMaxConnections() {
return 4;
}
}

View file

@ -0,0 +1,212 @@
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.packet;
import java.util.Iterator;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.PacketExtensionFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.ThreadFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.test.SmackTestCase;
/**
* Test the XHTML extension using the low level API
*
* @author Gaston Dombiak
*/
public class XHTMLExtensionTest extends SmackTestCase {
private int bodiesSent;
private int bodiesReceived;
public XHTMLExtensionTest(String name) {
super(name);
}
/**
* Low level API test.
* This is a simple test to use with a XMPP client and check if the client receives the message
* 1. User_1 will send a message with formatted text (XHTML) to user_2
*/
public void testSendSimpleXHTMLMessage() {
// User1 creates a chat with user2
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
// User1 creates a message to send to user2
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("Hey John, this is my new green!!!!");
// Create a XHTMLExtension Package and add it to the message
XHTMLExtension xhtmlExtension = new XHTMLExtension();
xhtmlExtension.addBody(
"<body><p style='font-size:large'>Hey John, this is my new <span style='color:green'>green</span><em>!!!!</em></p></body>");
msg.addExtension(xhtmlExtension);
// User1 sends the message that contains the XHTML to user2
try {
chat1.sendMessage(msg);
Thread.sleep(200);
}
catch (Exception e) {
fail("An error occured sending the message with XHTML");
}
}
/**
* Low level API test.
* 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 testSendSimpleXHTMLMessageAndDisplayReceivedXHTMLMessage() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
final PacketCollector chat2 = getConnection(1).createPacketCollector(
new ThreadFilter(chat1.getThreadID()));
// User1 creates a message to send to user2
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("Hey John, this is my new green!!!!");
// Create a XHTMLExtension Package and add it to the message
XHTMLExtension xhtmlExtension = new XHTMLExtension();
xhtmlExtension.addBody(
"<body><p style='font-size:large'>Hey John, this is my new <span style='color:green'>green</span><em>!!!!</em></p></body>");
msg.addExtension(xhtmlExtension);
// User1 sends the message that contains the XHTML to user2
try {
chat1.sendMessage(msg);
}
catch (Exception e) {
fail("An error occured sending the message with XHTML");
}
Packet packet = chat2.nextResult(2000);
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();) {
String body = it.next();
System.out.println(body);
}
}
catch (ClassCastException e) {
fail("ClassCastException - Most probable cause is that smack providers is misconfigured");
}
}
/**
* 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 PacketCollector chat2 = getConnection(1).createPacketCollector(
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 PacketExtensionFilter("html", "http://jabber.org/protocol/xhtml-im");
PacketListener packetListener = new PacketListener() {
@Override
public void processPacket(Packet packet) {
}
};
getConnection(1).addPacketListener(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 occured 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);
}
@Override
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,63 @@
/**
*
* Copyright 2009 Robin Collier.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub;
import org.jivesoftware.smack.packet.PacketExtension;
/**
*
* @author Robin Collier
*
*/
class CarExtension implements PacketExtension
{
private String color;
private int numTires;
public CarExtension(String col, int num)
{
color = col;
numTires = num;
}
public String getColor()
{
return color;
}
public int getNumTires()
{
return numTires;
}
public String getElementName()
{
return "car";
}
public String getNamespace()
{
return "pubsub:test:vehicle";
}
public String toXML()
{
return "<" + getElementName() + " xmlns='" + getNamespace() + "'><paint color='" +
getColor() + "'/><tires num='" + getNumTires() + "'/></" + getElementName() + ">";
}
}

View file

@ -0,0 +1,53 @@
/**
*
* Copyright 2009 Robin Collier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.provider.PacketExtensionProvider;
import org.xmlpull.v1.XmlPullParser;
/**
*
* @author Robin Collier
*
*/
public class CarExtensionProvider implements PacketExtensionProvider
{
public PacketExtension parseExtension(XmlPullParser parser) throws Exception
{
String color = null;
int numTires = 0;
for (int i=0; i<2; i++)
{
while (parser.next() != XmlPullParser.START_TAG);
if (parser.getName().equals("paint"))
{
color = parser.getAttributeValue(0);
}
else
{
numTires = Integer.parseInt(parser.getAttributeValue(0));
}
}
while (parser.next() != XmlPullParser.END_TAG);
return new CarExtension(color, numTires);
}
}

View file

@ -0,0 +1,89 @@
/**
*
* Copyright 2009 Robin Collier.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub;
import java.util.Iterator;
import java.util.List;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.packet.DiscoverItems;
import org.jivesoftware.smackx.packet.DiscoverInfo.Identity;
import org.jivesoftware.smackx.pubsub.test.SingleUserTestCase;
/**
*
* @author Robin Collier
*
*/
public class EntityUseCases extends SingleUserTestCase
{
public void testDiscoverPubsubInfo() throws Exception
{
DiscoverInfo supportedFeatures = getManager().getSupportedFeatures();
assertNotNull(supportedFeatures);
}
public void testDiscoverNodeInfo() throws Exception
{
LeafNode myNode = getManager().createNode("DiscoNode" + System.currentTimeMillis());
DiscoverInfo info = myNode.discoverInfo();
assertTrue(info.getIdentities().hasNext());
Identity ident = info.getIdentities().next();
assertEquals("leaf", ident.getType());
}
public void testDiscoverNodeItems() throws Exception
{
LeafNode myNode = getRandomPubnode(getManager(), true, false);
myNode.send(new Item());
myNode.send(new Item());
myNode.send(new Item());
myNode.send(new Item());
DiscoverItems items = myNode.discoverItems();
int count = 0;
for(Iterator<DiscoverItems.Item> it = items.getItems(); it.hasNext(); it.next(),count++);
assertEquals(4, count);
}
public void testDiscoverSubscriptions() throws Exception
{
getManager().getSubscriptions();
}
public void testDiscoverNodeSubscriptions() throws Exception
{
LeafNode myNode = getRandomPubnode(getManager(), true, true);
myNode.subscribe(getConnection(0).getUser());
List<Subscription> subscriptions = myNode.getSubscriptions();
assertTrue(subscriptions.size() < 3);
for (Subscription subscription : subscriptions)
{
assertNull(subscription.getNode());
}
}
public void testRetrieveAffiliation() throws Exception
{
getManager().getAffiliations();
}
}

View file

@ -0,0 +1,82 @@
/**
*
* Copyright 2009 Robin Collier.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub;
import java.util.Collection;
import java.util.List;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.pubsub.test.PubSubTestCase;
/**
*
* @author Robin Collier
*
*/
public class MultiUserSubscriptionUseCases extends PubSubTestCase
{
@Override
protected int getMaxConnections()
{
return 2;
}
public void testGetItemsWithSingleSubscription() throws XMPPException
{
LeafNode node = getRandomPubnode(getManager(0), true, false);
node.send((Item)null);
node.send((Item)null);
node.send((Item)null);
node.send((Item)null);
node.send((Item)null);
LeafNode user2Node = (LeafNode) getManager(1).getNode(node.getId());
user2Node.subscribe(getBareJID(1));
Collection<? extends Item> items = user2Node.getItems();
assertTrue(items.size() == 5);
}
public void testGetItemsWithMultiSubscription() throws XMPPException
{
LeafNode node = getRandomPubnode(getManager(0), true, false);
node.send((Item)null);
node.send((Item)null);
node.send((Item)null);
node.send((Item)null);
node.send((Item)null);
LeafNode user2Node = (LeafNode) getManager(1).getNode(node.getId());
Subscription sub1 = user2Node.subscribe(getBareJID(1));
Subscription sub2 = user2Node.subscribe(getBareJID(1));
try
{
user2Node.getItems();
}
catch (XMPPException exc)
{
assertEquals("bad-request", exc.getXMPPError().getCondition());
assertEquals(XMPPError.Type.MODIFY, exc.getXMPPError().getType());
}
List<Item> items = user2Node.getItems(sub1.getId());
assertTrue(items.size() == 5);
}
}

View file

@ -0,0 +1,148 @@
/**
*
* Copyright 2009 Robin Collier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub;
import java.util.Collection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.pubsub.test.SingleUserTestCase;
/**
*
* @author Robin Collier
*
*/
public class OwnerUseCases extends SingleUserTestCase
{
public void testCreateInstantNode() throws Exception
{
LeafNode node = getManager().createNode();
assertNotNull(node);
assertNotNull(node.getId());
}
public void testCreateNamedNode() throws Exception
{
String id = "TestNamedNode" + System.currentTimeMillis();
LeafNode node = getManager().createNode(id);
assertEquals(id, node.getId());
}
public void testCreateConfiguredNode() throws Exception
{
// Generate reasonably unique for multiple tests
String id = "TestConfigNode" + System.currentTimeMillis();
// Create and configure a node
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setAccessModel(AccessModel.open);
form.setDeliverPayloads(false);
form.setNotifyRetract(true);
form.setPersistentItems(true);
form.setPublishModel(PublishModel.open);
LeafNode node = (LeafNode)getManager().createNode(id, form);
ConfigureForm currentForm = node.getNodeConfiguration();
assertEquals(AccessModel.open, currentForm.getAccessModel());
assertFalse(currentForm.isDeliverPayloads());
assertTrue(currentForm.isNotifyRetract());
assertTrue(currentForm.isPersistItems());
assertEquals(PublishModel.open, currentForm.getPublishModel());
}
public void testCreateAndUpdateConfiguredNode() throws Exception
{
// Generate reasonably unique for multiple tests
String id = "TestConfigNode2" + System.currentTimeMillis();
// Create and configure a node
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setAccessModel(AccessModel.open);
form.setDeliverPayloads(false);
form.setNotifyRetract(true);
form.setPersistentItems(true);
form.setPublishModel(PublishModel.open);
LeafNode myNode = (LeafNode)getManager().createNode(id, form);
ConfigureForm config = myNode.getNodeConfiguration();
assertEquals(AccessModel.open, config.getAccessModel());
assertFalse(config.isDeliverPayloads());
assertTrue(config.isNotifyRetract());
assertTrue(config.isPersistItems());
assertEquals(PublishModel.open, config.getPublishModel());
ConfigureForm submitForm = new ConfigureForm(config.createAnswerForm());
submitForm.setAccessModel(AccessModel.whitelist);
submitForm.setDeliverPayloads(true);
submitForm.setNotifyRetract(false);
submitForm.setPersistentItems(false);
submitForm.setPublishModel(PublishModel.publishers);
myNode.sendConfigurationForm(submitForm);
ConfigureForm newConfig = myNode.getNodeConfiguration();
assertEquals(AccessModel.whitelist, newConfig.getAccessModel());
assertTrue(newConfig.isDeliverPayloads());
assertFalse(newConfig.isNotifyRetract());
assertFalse(newConfig.isPersistItems());
assertEquals(PublishModel.publishers, newConfig.getPublishModel());
}
public void testGetDefaultConfig() throws Exception
{
ConfigureForm form = getManager().getDefaultConfiguration();
assertNotNull(form);
}
public void testDeleteNode() throws Exception
{
LeafNode myNode = getManager().createNode();
assertNotNull(getManager().getNode(myNode.getId()));
getManager(0).deleteNode(myNode.getId());
try
{
assertNull(getManager().getNode(myNode.getId()));
fail("Node should not exist");
}
catch (XMPPException e)
{
}
}
public void testPurgeItems() throws XMPPException
{
LeafNode node = getRandomPubnode(getManager(), true, false);
node.send(new Item());
node.send(new Item());
node.send(new Item());
node.send(new Item());
node.send(new Item());
Collection<? extends Item> items = node.getItems();
assertTrue(items.size() == 5);
node.deleteAllItems();
items = node.getItems();
// Pubsub service may keep the last notification (in spec), so 0 or 1 may be returned on get items.
assertTrue(items.size() < 2);
}
}

View file

@ -0,0 +1,166 @@
/**
*
* Copyright 2009 Robin Collier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub;
import java.util.Collection;
import java.util.List;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.packet.XMPPError.Condition;
import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace;
import org.jivesoftware.smackx.pubsub.test.SingleUserTestCase;
/**
*
* @author Robin Collier
*
*/
public class PublisherUseCases extends SingleUserTestCase
{
public void testSendNodeTrNot() throws Exception
{
getPubnode(false, false).send();
}
public void testSendNodeTrPay_WithOutPayload() throws XMPPException
{
LeafNode node = getPubnode(false, true);
try
{
node.send(new Item());
fail("Exception should be thrown when there is no payload");
}
catch (XMPPException e) {
XMPPError err = e.getXMPPError();
assertTrue(err.getType().equals(XMPPError.Type.MODIFY));
assertTrue(err.getCondition().equals(Condition.bad_request.toString()));
assertNotNull(err.getExtension("payload-required", PubSubNamespace.ERROR.getXmlns()));
}
try
{
node.send(new Item("test" + System.currentTimeMillis()));
fail("Exception should be thrown when there is no payload");
}
catch (XMPPException e) {
XMPPError err = e.getXMPPError();
assertTrue(err.getType().equals(XMPPError.Type.MODIFY));
assertTrue(err.getCondition().equals(Condition.bad_request.toString()));
assertNotNull(err.getExtension("payload-required", PubSubNamespace.ERROR.getXmlns()));
}
}
public void testSendNodeTrPay_WithPayload() throws XMPPException
{
LeafNode node = getPubnode(false, true);
node.send(new PayloadItem<SimplePayload>(null,
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Lord of the Rings</title></book>")));
node.send(new PayloadItem<SimplePayload>("test" + System.currentTimeMillis(),
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Two Towers</title></book>")));
}
public void testSendNodePerNot() throws Exception
{
LeafNode node = getPubnode(true, false);
node.send(new Item());
node.send(new Item("test" + System.currentTimeMillis()));
node.send(new PayloadItem<SimplePayload>(null,
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Lord of the Rings</title></book>")));
node.send(new PayloadItem<SimplePayload>("test" + System.currentTimeMillis(),
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Two Towers</title></book>")));
}
public void testSendPerPay_WithPayload() throws Exception
{
LeafNode node = getPubnode(true, true);
node.send(new PayloadItem<SimplePayload>(null,
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Lord of the Rings</title></book>")));
node.send(new PayloadItem<SimplePayload>("test" + System.currentTimeMillis(),
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Two Towers</title></book>")));
}
public void testSendPerPay_NoPayload() throws Exception
{
LeafNode node = getPubnode(true, true);
try
{
node.send(new Item());
fail("Exception should be thrown when there is no payload");
}
catch (XMPPException e) {
XMPPError err = e.getXMPPError();
assertTrue(err.getType().equals(XMPPError.Type.MODIFY));
assertTrue(err.getCondition().equals(Condition.bad_request.toString()));
assertNotNull(err.getExtension("payload-required", PubSubNamespace.ERROR.getXmlns()));
}
try
{
node.send(new Item("test" + System.currentTimeMillis()));
fail("Exception should be thrown when there is no payload");
}
catch (XMPPException e) {
XMPPError err = e.getXMPPError();
assertTrue(err.getType().equals(XMPPError.Type.MODIFY));
assertTrue(err.getCondition().equals(Condition.bad_request.toString()));
assertNotNull(err.getExtension("payload-required", PubSubNamespace.ERROR.getXmlns()));
}
}
public void testDeleteItems() throws XMPPException
{
LeafNode node = getPubnode(true, false);
node.send(new Item("1"));
node.send(new Item("2"));
node.send(new Item("3"));
node.send(new Item("4"));
node.deleteItem("1");
Collection<? extends Item> items = node.getItems();
assertEquals(3, items.size());
}
public void testPersistItems() throws XMPPException
{
LeafNode node = getPubnode(true, false);
node.send(new Item("1"));
node.send(new Item("2"));
node.send(new Item("3"));
node.send(new Item("4"));
Collection<? extends Item> items = node.getItems();
assertTrue(items.size() == 4);
}
public void testItemOverwritten() throws XMPPException
{
LeafNode node = getPubnode(true, false);
node.send(new PayloadItem<SimplePayload>("1", new SimplePayload("test", null, "<test/>")));
node.send(new PayloadItem<SimplePayload>("1", new SimplePayload("test2", null, "<test2/>")));
List<? extends Item> items = node.getItems();
assertEquals(1, items.size());
assertEquals("1", items.get(0).getId());
}
}

View file

@ -0,0 +1,280 @@
/**
*
* Copyright 2009 Robin Collier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.pubsub.test.SingleUserTestCase;
/**
*
* @author Robin Collier
*
*/
public class SubscriberUseCases extends SingleUserTestCase
{
public void testSubscribe() throws Exception
{
LeafNode node = getPubnode(false, false);
Subscription sub = node.subscribe(getJid());
assertEquals(getJid(), sub.getJid());
assertNotNull(sub.getId());
assertEquals(node.getId(), sub.getNode());
assertEquals(Subscription.State.subscribed, sub.getState());
}
public void testSubscribeBadJid() throws Exception
{
LeafNode node = getPubnode(false, false);
try
{
node.subscribe("this@over.here");
fail();
}
catch (XMPPException e)
{
}
}
public void testSubscribeWithOptions() throws Exception
{
SubscribeForm form = new SubscribeForm(FormType.submit);
form.setDeliverOn(true);
Calendar expire = Calendar.getInstance();
expire.set(2020, 1, 1);
form.setExpiry(expire.getTime());
LeafNode node = getPubnode(false, false);
node.subscribe(getJid(), form);
}
public void testSubscribeConfigRequired() throws Exception
{
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setAccessModel(AccessModel.open);
// Openfire specific field - nothing in the spec yet
FormField required = new FormField("pubsub#subscription_required");
required.setType(FormField.TYPE_BOOLEAN);
form.addField(required);
form.setAnswer("pubsub#subscription_required", true);
LeafNode node = (LeafNode)getManager().createNode("Pubnode" + System.currentTimeMillis(), form);
Subscription sub = node.subscribe(getJid());
assertEquals(getJid(), sub.getJid());
assertNotNull(sub.getId());
assertEquals(node.getId(), sub.getNode());
assertEquals(true, sub.isConfigRequired());
}
public void testUnsubscribe() throws Exception
{
LeafNode node = getPubnode(false, false);
node.subscribe(getJid());
Collection<Subscription> subs = node.getSubscriptions();
node.unsubscribe(getJid());
Collection<Subscription> afterSubs = node.getSubscriptions();
assertEquals(subs.size()-1, afterSubs.size());
}
public void testUnsubscribeWithMultipleNoSubId() throws Exception
{
LeafNode node = getPubnode(false, false);
node.subscribe(getBareJID(0));
node.subscribe(getBareJID(0));
node.subscribe(getBareJID(0));
try
{
node.unsubscribe(getBareJID(0));
fail("Unsubscribe with no subid should fail");
}
catch (XMPPException e)
{
}
}
public void testUnsubscribeWithMultipleWithSubId() throws Exception
{
LeafNode node = getPubnode(false, false);
node.subscribe(getJid());
Subscription sub = node.subscribe(getJid());
node.subscribe(getJid());
node.unsubscribe(getJid(), sub.getId());
}
public void testGetOptions() throws Exception
{
LeafNode node = getPubnode(false, false);
Subscription sub = node.subscribe(getJid());
SubscribeForm form = node.getSubscriptionOptions(getJid(), sub.getId());
assertNotNull(form);
}
// public void testSubscribeWithConfig() throws Exception
// {
// LeafNode node = getPubnode(false, false);
//
// Subscription sub = node.subscribe(getBareJID(0));
//
// assertEquals(getBareJID(0), sub.getJid());
// assertNotNull(sub.getId());
// assertEquals(node.getId(), sub.getNode());
// assertEquals(true, sub.isConfigRequired());
// }
//
public void testGetItems() throws Exception
{
LeafNode node = getPubnode(true, false);
runNodeTests(node);
}
private void runNodeTests(LeafNode node) throws Exception
{
node.send((Item)null);
node.send((Item)null);
node.send((Item)null);
node.send((Item)null);
node.send((Item)null);
Collection<? extends Item> items = node.getItems();
assertTrue(items.size() == 5);
long curTime = System.currentTimeMillis();
node.send(new Item("1-" + curTime));
node.send(new Item("2-" + curTime));
node.send(new Item("3-" + curTime));
node.send(new Item("4-" + curTime));
node.send(new Item("5-" + curTime));
items = node.getItems();
assertTrue(items.size() == 10);
LeafNode payloadNode = getPubnode(true, true);
Map<String , String> idPayload = new HashMap<String, String>();
idPayload.put("6-" + curTime, "<a/>");
idPayload.put("7-" + curTime, "<a href=\"/up/here\"/>");
idPayload.put("8-" + curTime, "<entity>text<inner></inner></entity>");
idPayload.put("9-" + curTime, "<entity><inner><text></text></inner></entity>");
for (Map.Entry<String, String> payload : idPayload.entrySet())
{
payloadNode.send(new PayloadItem<SimplePayload>(payload.getKey(), new SimplePayload("a", "pubsub:test", payload.getValue())));
}
payloadNode.send(new PayloadItem<SimplePayload>("6-" + curTime, new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test'/>")));
payloadNode.send(new PayloadItem<SimplePayload>("7-" + curTime, new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href=\'/up/here\'/>")));
payloadNode.send(new PayloadItem<SimplePayload>("8-" + curTime, new SimplePayload("entity", "pubsub:test", "<entity xmlns='pubsub:test'>text<inner>a</inner></entity>")));
payloadNode.send(new PayloadItem<SimplePayload>("9-" + curTime, new SimplePayload("entity", "pubsub:test", "<entity xmlns='pubsub:test'><inner><text>b</text></inner></entity>")));
List<PayloadItem<SimplePayload>> payloadItems = payloadNode.getItems();
Map<String, PayloadItem<SimplePayload>> idMap = new HashMap<String, PayloadItem<SimplePayload>>();
for (PayloadItem<SimplePayload> payloadItem : payloadItems)
{
idMap.put(payloadItem.getId(), payloadItem);
}
assertEquals(4, payloadItems.size());
PayloadItem<SimplePayload> testItem = idMap.get("6-" + curTime);
assertNotNull(testItem);
assertXMLEqual("<a xmlns='pubsub:test'/>", testItem.getPayload().toXML());
testItem = idMap.get("7-" + curTime);
assertNotNull(testItem);
assertXMLEqual("<a xmlns='pubsub:test' href=\'/up/here\'/>", testItem.getPayload().toXML());
testItem = idMap.get("8-" + curTime);
assertNotNull(testItem);
assertXMLEqual("<entity xmlns='pubsub:test'>text<inner>a</inner></entity>", testItem.getPayload().toXML());
testItem = idMap.get("9-" + curTime);
assertNotNull(testItem);
assertXMLEqual("<entity xmlns='pubsub:test'><inner><text>b</text></inner></entity>", testItem.getPayload().toXML());
}
public void testGetSpecifiedItems() throws Exception
{
LeafNode node = getPubnode(true, true);
node.send(new PayloadItem<SimplePayload>("1", new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='1'/>")));
node.send(new PayloadItem<SimplePayload>("2", new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='2'/>")));
node.send(new PayloadItem<SimplePayload>("3", new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='3'/>")));
node.send(new PayloadItem<SimplePayload>("4", new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='4'/>")));
node.send(new PayloadItem<SimplePayload>("5", new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='5'/>")));
Collection<String> ids = new ArrayList<String>(3);
ids.add("1");
ids.add("3");
ids.add("4");
List<PayloadItem<SimplePayload>> items = node.getItems(ids);
assertEquals(3, items.size());
assertEquals("1", items.get(0).getId());
assertXMLEqual("<a xmlns='pubsub:test' href='1'/>", items.get(0).getPayload().toXML());
assertEquals( "3", items.get(1).getId());
assertXMLEqual("<a xmlns='pubsub:test' href='3'/>", items.get(1).getPayload().toXML());
assertEquals("4", items.get(2).getId());
assertXMLEqual("<a xmlns='pubsub:test' href='4'/>", items.get(2).getPayload().toXML());
}
public void testGetLastNItems() throws XMPPException
{
LeafNode node = getPubnode(true, false);
node.send(new Item("1"));
node.send(new Item("2"));
node.send(new Item("3"));
node.send(new Item("4"));
node.send(new Item("5"));
List<Item> items = node.getItems(2);
assertEquals(2, items.size());
assertTrue(listContainsId("4", items));
assertTrue(listContainsId("5", items));
}
private static boolean listContainsId(String id, List<Item> items)
{
for (Item item : items)
{
if (item.getId().equals(id))
return true;
}
return false;
}
private String getJid()
{
return getConnection(0).getUser();
}
}

View file

@ -0,0 +1,40 @@
/**
*
* Copyright 2009 Robin Collier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.pubsub.test.SingleUserTestCase;
/**
*
* @author Robin Collier
*
*/
public class TestAPI extends SingleUserTestCase
{
public void testGetNonexistentNode()
{
try
{
getManager().getNode("" + System.currentTimeMillis());
assertTrue(false);
}
catch (XMPPException e)
{
}
}
}

View file

@ -0,0 +1,598 @@
/**
*
* Copyright 2009 Robin Collier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.XMPPError.Type;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.pubsub.listener.ItemDeleteListener;
import org.jivesoftware.smackx.pubsub.listener.ItemEventListener;
import org.jivesoftware.smackx.pubsub.listener.NodeConfigListener;
/**
*
* @author Robin Collier
*
*/
public class TestEvents extends SmackTestCase
{
public TestEvents(String str)
{
super(str);
}
@Override
protected int getMaxConnections()
{
return 2;
}
private String getService()
{
return "pubsub." + getServiceName();
}
public void testCreateAndGetNode() throws Exception
{
String nodeId = "MyTestNode";
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = null;
try
{
creatorNode = (LeafNode)creatorMgr.getNode(nodeId);
}
catch (XMPPException e)
{
if (e.getXMPPError().getType() == Type.CANCEL && e.getXMPPError().getCondition().equals("item-not-found"))
creatorNode = creatorMgr.createNode(nodeId);
else
throw e;
}
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
assertNotNull(subNode);
}
public void testConfigureAndNotify() throws Exception
{
// Setup event source
String nodeId = "TestNode" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, false, true);
BlockingQueue<NodeConfigCoordinator> queue = new ArrayBlockingQueue<NodeConfigCoordinator>(3);
// Setup event receiver
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
NodeConfigListener sub1Handler = new NodeConfigCoordinator(queue, "sub1");
subNode.subscribe(getConnection(1).getUser());
subNode.addConfigurationListener(sub1Handler);
ConfigureForm currentConfig = creatorNode.getNodeConfiguration();
ConfigureForm form = new ConfigureForm(currentConfig.createAnswerForm());
form.setPersistentItems(true);
form.setDeliverPayloads(false);
form.setNotifyConfig(true);
creatorNode.sendConfigurationForm(form);
ConfigurationEvent event = queue.poll(5, TimeUnit.SECONDS).event;
assertEquals(nodeId, event.getNode());
assertNull(event.getConfiguration());
currentConfig = creatorNode.getNodeConfiguration();
form = new ConfigureForm(currentConfig.createAnswerForm());
form.setDeliverPayloads(true);
creatorNode.sendConfigurationForm(form);
event = queue.poll(5, TimeUnit.SECONDS).event;
assertEquals(nodeId, event.getNode());
assertNotNull(event.getConfiguration());
assertTrue(event.getConfiguration().isPersistItems());
assertTrue(event.getConfiguration().isDeliverPayloads());
}
public void testSendAndReceiveNoPayload() throws Exception
{
// Setup event source
String nodeId = "TestNode" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
BlockingQueue<ItemEventCoordinator<Item>> queue = new ArrayBlockingQueue<ItemEventCoordinator<Item>>(3);
// Setup event receiver
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
ItemEventCoordinator<Item> sub1Handler = new ItemEventCoordinator<Item>(queue, "sub1");
subNode.addItemEventListener(sub1Handler);
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
// Send event
String itemId = String.valueOf(System.currentTimeMillis());
creatorNode.send(new Item(itemId));
ItemEventCoordinator<Item> coord = queue.poll(5, TimeUnit.SECONDS);
assertEquals(1, coord.events.getItems().size());
assertEquals(itemId, coord.events.getItems().iterator().next().getId());
}
public void testPublishAndReceiveNoPayload() throws Exception
{
// Setup event source
String nodeId = "TestNode" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
BlockingQueue<ItemEventCoordinator<Item>> queue = new ArrayBlockingQueue<ItemEventCoordinator<Item>>(3);
// Setup event receiver
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
ItemEventCoordinator<Item> sub1Handler = new ItemEventCoordinator<Item>(queue, "sub1");
subNode.addItemEventListener(sub1Handler);
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
// Send event
String itemId = String.valueOf(System.currentTimeMillis());
creatorNode.publish(new Item(itemId));
ItemEventCoordinator<Item> coord = queue.poll(5, TimeUnit.SECONDS);
assertEquals(1, coord.events.getItems().size());
assertEquals(itemId, coord.events.getItems().get(0).getId());
}
public void testSendAndReceiveSimplePayload() throws Exception
{
// Setup event source
String nodeId = "TestNode" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, true);
BlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>> queue = new ArrayBlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>>(3);
// Setup event receiver
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
ItemEventCoordinator<PayloadItem<SimplePayload>> sub1Handler = new ItemEventCoordinator<PayloadItem<SimplePayload>>(queue, "sub1");
subNode.addItemEventListener(sub1Handler);
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
// Send event
String itemId = String.valueOf(System.currentTimeMillis());
String payloadString = "<book xmlns=\"pubsub:test:book\"><author>Sir Arthur Conan Doyle</author></book>";
creatorNode.send(new PayloadItem<SimplePayload>(itemId, new SimplePayload("book", "pubsub:test:book", payloadString)));
ItemEventCoordinator<PayloadItem<SimplePayload>> coord = queue.poll(5, TimeUnit.SECONDS);
assertEquals(1, coord.events.getItems().size());
PayloadItem<SimplePayload> item = coord.events.getItems().get(0);
assertEquals(itemId, item.getId());
assertTrue(item.getPayload() instanceof SimplePayload);
assertEquals(payloadString, item.getPayload().toXML());
assertEquals("book", item.getPayload().getElementName());
}
/*
* For this test, the following extension needs to be added to the meta-inf/smack.providers file
*
* <extensionProvider>
* <elementName>car</elementName>
* <namespace>pubsub:test:vehicle</namespace>
* <className>org.jivesoftware.smackx.pubsub.CarExtensionProvider</className>
* </extensionProvider>
*/
/*
public void testSendAndReceiveCarPayload() throws Exception
{
// Setup event source
String nodeId = "TestNode" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, true);
BlockingQueue<ItemEventCoordinator<PayloadItem<CarExtension>>> queue = new ArrayBlockingQueue<ItemEventCoordinator<PayloadItem<CarExtension>>>(3);
// Setup event receiver
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
Node subNode = subMgr.getNode(nodeId);
ItemEventCoordinator<PayloadItem<CarExtension>> sub1Handler = new ItemEventCoordinator<PayloadItem<CarExtension>>(queue, "sub1");
subNode.addItemEventListener(sub1Handler);
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
// Send event
String itemId = String.valueOf(System.currentTimeMillis());
String payloadString = "<car xmlns='pubsub:test:vehicle'><paint color='green'/><tires num='4'/></car>";
creatorNode.send(new PayloadItem(itemId, new SimplePayload("car", "pubsub:test:vehicle", payloadString)));
ItemEventCoordinator<PayloadItem<CarExtension>> coord = queue.take();
assertEquals(1, coord.events.getItems().size());
PayloadItem item = coord.events.getItems().get(0);
assertEquals(itemId, item.getId());
assertTrue(item.getPayload() instanceof CarExtension);
CarExtension car = (CarExtension)item.getPayload();
assertEquals("green", car.getColor());
assertEquals(4, car.getNumTires());
}
*/
public void testSendAndReceiveMultipleSubs() throws Exception
{
// Setup event source
String nodeId = "TestNode" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
BlockingQueue<ItemEventCoordinator<Item>> queue = new ArrayBlockingQueue<ItemEventCoordinator<Item>>(3);
// Setup event receiver
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
ItemEventCoordinator<Item> sub1Handler = new ItemEventCoordinator<Item>(queue, "sub1");
subNode.addItemEventListener(sub1Handler);
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
ItemEventCoordinator<Item> sub2Handler = new ItemEventCoordinator<Item>(queue, "sub2");
subNode.addItemEventListener(sub2Handler);
Subscription sub2 = subNode.subscribe(getConnection(1).getUser());
// Send event
String itemId = String.valueOf(System.currentTimeMillis());
creatorNode.send(new Item(itemId));
for(int i=0; i<2; i++)
{
ItemEventCoordinator<Item> coord = queue.poll(10, TimeUnit.SECONDS);
if (coord == null)
fail();
assertEquals(1, coord.events.getItems().size());
assertEquals(itemId, coord.events.getItems().iterator().next().getId());
if (coord.id.equals("sub1") || coord.id.equals("sub2"))
{
assertEquals(2, coord.events.getSubscriptions().size());
}
}
}
public void testSendAndReceiveMultipleItems() throws Exception
{
// Setup event source
String nodeId = "TestNode" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, true);
BlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>> queue = new ArrayBlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>>(3);
ItemEventCoordinator<PayloadItem<SimplePayload>> creatorHandler = new ItemEventCoordinator<PayloadItem<SimplePayload>>(queue, "creator");
creatorNode.addItemEventListener(creatorHandler);
creatorNode.subscribe(getConnection(0).getUser());
// Setup event receiver
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
ItemEventCoordinator<PayloadItem<SimplePayload>> sub1Handler = new ItemEventCoordinator<PayloadItem<SimplePayload>>(queue, "sub1");
subNode.addItemEventListener(sub1Handler);
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
ItemEventCoordinator<PayloadItem<SimplePayload>> sub2Handler = new ItemEventCoordinator<PayloadItem<SimplePayload>>(queue, "sub2");
subNode.addItemEventListener(sub2Handler);
Subscription sub2 = subNode.subscribe(getConnection(1).getUser());
assertEquals(Subscription.State.subscribed, sub1.getState());
assertEquals(Subscription.State.subscribed, sub2.getState());
// Send event
String itemId = String.valueOf(System.currentTimeMillis());
Collection<PayloadItem<SimplePayload>> items = new ArrayList<PayloadItem<SimplePayload>>(3);
String ids[] = {"First-" + itemId, "Second-" + itemId, "Third-" + itemId};
items.add(new PayloadItem<SimplePayload>(ids[0], new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='1'/>")));
items.add(new PayloadItem<SimplePayload>(ids[1], new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='1'/>")));
items.add(new PayloadItem<SimplePayload>(ids[2], new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='1'/>")));
creatorNode.send(items);
for(int i=0; i<3; i++)
{
ItemEventCoordinator<PayloadItem<SimplePayload>> coord = queue.poll(5, TimeUnit.SECONDS);
if (coord == creatorHandler)
assertEquals(1, coord.events.getSubscriptions().size());
else
assertEquals(2, coord.events.getSubscriptions().size());
List<PayloadItem<SimplePayload>> itemResults = coord.events.getItems();
assertEquals(3, itemResults.size());
// assertEquals(ids[0], itemResults.get(0).getId());
// assertEquals("<a xmlns='pubsub:test' href='1'/>", itemResults.get(0).getPayload().toXML().replace('\"', '\''));
// assertEquals(ids[1], itemResults.get(1).getId());
// assertEquals("<a xmlns='pubsub:test' href='2'/>", itemResults.get(1).getPayload().toXML().replace('\"', '\''));
// assertEquals(ids[21], itemResults.get(2).getId());
// assertEquals("<a xmlns='pubsub:test' href='3'/>", itemResults.get(3).getPayload().toXML().replace('\"', '\''));
}
}
public void testSendAndReceiveDelayed() throws Exception
{
// Setup event source
String nodeId = "TestNode" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
// Send event
String itemId = String.valueOf("DelayId-" + System.currentTimeMillis());
String payloadString = "<book xmlns='pubsub:test:book'><author>Sir Arthur Conan Doyle</author></book>";
creatorNode.send(new PayloadItem<SimplePayload>(itemId, new SimplePayload("book", "pubsub:test:book", payloadString)));
Thread.sleep(1000);
BlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>> queue = new ArrayBlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>>(3);
// Setup event receiver
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
ItemEventCoordinator<PayloadItem<SimplePayload>> sub1Handler = new ItemEventCoordinator<PayloadItem<SimplePayload>>(queue, "sub1");
subNode.addItemEventListener(sub1Handler);
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
ItemEventCoordinator<PayloadItem<SimplePayload>> coord = queue.poll(5, TimeUnit.SECONDS);
assertTrue(coord.events.isDelayed());
assertNotNull(coord.events.getPublishedDate());
}
public void testDeleteItemAndNotify() throws Exception
{
// Setup event source
String nodeId = "TestNode" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
BlockingQueue<ItemDeleteCoordinator> queue = new ArrayBlockingQueue<ItemDeleteCoordinator>(3);
// Setup event receiver
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
ItemDeleteCoordinator sub1Handler = new ItemDeleteCoordinator(queue, "sub1");
subNode.addItemDeleteListener(sub1Handler);
subNode.subscribe(getConnection(1).getUser());
// Send event
String itemId = String.valueOf(System.currentTimeMillis());
Collection<Item> items = new ArrayList<Item>(3);
String id1 = "First-" + itemId;
String id2 = "Second-" + itemId;
String id3 = "Third-" + itemId;
items.add(new Item(id1));
items.add(new Item(id2));
items.add(new Item(id3));
creatorNode.send(items);
creatorNode.deleteItem(id1);
ItemDeleteCoordinator coord = queue.poll(5, TimeUnit.SECONDS);
assertEquals(1, coord.event.getItemIds().size());
assertEquals(id1, coord.event.getItemIds().get(0));
creatorNode.deleteItem(Arrays.asList(id2, id3));
coord = queue.poll(5, TimeUnit.SECONDS);
assertEquals(2, coord.event.getItemIds().size());
assertTrue(coord.event.getItemIds().contains(id2));
assertTrue(coord.event.getItemIds().contains(id3));
}
public void testPurgeAndNotify() throws Exception
{
// Setup event source
String nodeId = "TestNode" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
BlockingQueue<ItemDeleteCoordinator> queue = new ArrayBlockingQueue<ItemDeleteCoordinator>(3);
// Setup event receiver
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
ItemDeleteCoordinator sub1Handler = new ItemDeleteCoordinator(queue, "sub1");
subNode.addItemDeleteListener(sub1Handler);
subNode.subscribe(getConnection(1).getUser());
// Send event
String itemId = String.valueOf(System.currentTimeMillis());
Collection<Item> items = new ArrayList<Item>(3);
String id1 = "First-" + itemId;
String id2 = "Second-" + itemId;
String id3 = "Third-" + itemId;
items.add(new Item(id1));
items.add(new Item(id2));
items.add(new Item(id3));
creatorNode.send(items);
creatorNode.deleteAllItems();
ItemDeleteCoordinator coord = queue.poll(5, TimeUnit.SECONDS);
assertNull(nodeId, coord.event);
}
public void testListenerMultipleNodes() throws Exception
{
// Setup event source
String nodeId1 = "Node-1-" + System.currentTimeMillis();
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
String nodeId2 = "Node-2-" + System.currentTimeMillis();
LeafNode creatorNode1 = getPubnode(creatorMgr, nodeId1, true, false);
LeafNode creatorNode2 = getPubnode(creatorMgr, nodeId2, true, false);
BlockingQueue<ItemEventCoordinator<Item>> queue = new ArrayBlockingQueue<ItemEventCoordinator<Item>>(3);
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
LeafNode subNode1 = (LeafNode)subMgr.getNode(nodeId1);
LeafNode subNode2 = (LeafNode)subMgr.getNode(nodeId2);
subNode1.addItemEventListener(new ItemEventCoordinator<Item>(queue, "sub1"));
subNode2.addItemEventListener(new ItemEventCoordinator<Item>(queue, "sub2"));
subNode1.subscribe(getConnection(1).getUser());
subNode2.subscribe(getConnection(1).getUser());
creatorNode1.send(new Item("item1"));
creatorNode2.send(new Item("item2"));
boolean check1 = false;
boolean check2 = false;
for (int i=0; i<2; i++)
{
ItemEventCoordinator<Item> event = queue.poll(5, TimeUnit.SECONDS);
if (event.id.equals("sub1"))
{
assertEquals(event.events.getNodeId(), nodeId1);
check1 = true;
}
else
{
assertEquals(event.events.getNodeId(), nodeId2);
check2 = true;
}
}
assertTrue(check1);
assertTrue(check2);
}
class ItemEventCoordinator <T extends Item> implements ItemEventListener<T>
{
private BlockingQueue<ItemEventCoordinator<T>> theQueue;
private ItemPublishEvent<T> events;
private String id;
ItemEventCoordinator(BlockingQueue<ItemEventCoordinator<T>> queue, String id)
{
theQueue = queue;
this.id = id;
}
public void handlePublishedItems(ItemPublishEvent<T> items)
{
events = items;
theQueue.add(this);
}
@Override
public String toString()
{
return "ItemEventCoordinator: " + id;
}
}
class NodeConfigCoordinator implements NodeConfigListener
{
private BlockingQueue<NodeConfigCoordinator> theQueue;
private String id;
private ConfigurationEvent event;
NodeConfigCoordinator(BlockingQueue<NodeConfigCoordinator> queue, String id)
{
theQueue = queue;
this.id = id;
}
public void handleNodeConfiguration(ConfigurationEvent config)
{
event = config;
theQueue.add(this);
}
@Override
public String toString()
{
return "NodeConfigCoordinator: " + id;
}
}
class ItemDeleteCoordinator implements ItemDeleteListener
{
private BlockingQueue<ItemDeleteCoordinator> theQueue;
private String id;
private ItemDeleteEvent event;
ItemDeleteCoordinator(BlockingQueue<ItemDeleteCoordinator> queue, String id)
{
theQueue = queue;
this.id = id;
}
public void handleDeletedItems(ItemDeleteEvent delEvent)
{
event = delEvent;
theQueue.add(this);
}
public void handlePurge()
{
event = null;
theQueue.add(this);
}
@Override
public String toString()
{
return "ItemDeleteCoordinator: " + id;
}
}
static private LeafNode getPubnode(PubSubManager manager, String id, boolean persistItems, boolean deliverPayload)
throws XMPPException
{
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setPersistentItems(persistItems);
form.setDeliverPayloads(deliverPayload);
form.setAccessModel(AccessModel.open);
return (LeafNode)manager.createNode(id, form);
}
}

View file

@ -0,0 +1,134 @@
/**
*
* Copyright 2009 Robin Collier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub;
import junit.framework.TestCase;
/**
*
* @author Robin Collier
*
*/
public class TestMessageContent extends TestCase
{
String payloadXmlWithNS = "<book xmlns='pubsub:test:book'><author name='Stephen King'/></book>";
public void testItemWithId()
{
Item item = new Item("123");
assertEquals("<item id='123'/>", item.toXML());
assertEquals("item", item.getElementName());
assertNull(item.getNamespace());
}
public void testItemWithNoId()
{
Item item = new Item();
assertEquals("<item/>", item.toXML());
Item itemNull = new Item(null);
assertEquals("<item/>", itemNull.toXML());
}
public void testSimplePayload()
{
SimplePayload payloadNS = new SimplePayload("book", "pubsub:test:book", payloadXmlWithNS);
assertEquals(payloadXmlWithNS, payloadNS.toXML());
String payloadXmlWithNoNS = "<book><author name='Stephen King'/></book>";
SimplePayload payloadNoNS = new SimplePayload("book", null, "<book><author name='Stephen King'/></book>");
assertEquals(payloadXmlWithNoNS, payloadNoNS.toXML());
}
public void testPayloadItemWithId()
{
SimplePayload payload = new SimplePayload("book", "pubsub:test:book", payloadXmlWithNS);
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>("123", payload);
String xml = "<item id='123'>" + payloadXmlWithNS + "</item>";
assertEquals(xml, item.toXML());
assertEquals("item", item.getElementName());
}
public void testPayloadItemWithNoId()
{
SimplePayload payload = new SimplePayload("book", "pubsub:test:book", payloadXmlWithNS);
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>(null, payload);
String xml = "<item>" + payloadXmlWithNS + "</item>";
assertEquals(xml, item.toXML());
}
public void testPayloadItemWithIdNoPayload()
{
try
{
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>("123", null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException e)
{
}
}
public void testPayloadItemWithNoIdNoPayload()
{
try
{
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>(null, null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException e)
{
}
}
public void testRetractItem()
{
RetractItem item = new RetractItem("1234");
assertEquals("<retract id='1234'/>", item.toXML());
assertEquals("retract", item.getElementName());
try
{
new RetractItem(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException e)
{
}
}
public void testGetItemsRequest()
{
GetItemsRequest request = new GetItemsRequest("testId");
assertEquals("<items node='testId'/>", request.toXML());
request = new GetItemsRequest("testId", 5);
assertEquals("<items node='testId' max_items='5'/>", request.toXML());
request = new GetItemsRequest("testId", "qwerty");
assertEquals("<items node='testId' subid='qwerty'/>", request.toXML());
request = new GetItemsRequest("testId", "qwerty", 5);
assertEquals("<items node='testId' subid='qwerty' max_items='5'/>", request.toXML());
}
}

View file

@ -0,0 +1,92 @@
/**
*
* Copyright 2009 Robin Collier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub.test;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.pubsub.AccessModel;
import org.jivesoftware.smackx.pubsub.ConfigureForm;
import org.jivesoftware.smackx.pubsub.FormType;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.PubSubManager;
/**
*
* @author Robin Collier
*
*/
abstract public class PubSubTestCase extends SmackTestCase
{
private PubSubManager[] manager;
public PubSubTestCase(String arg0)
{
super(arg0);
}
public PubSubTestCase()
{
super("PubSub Test Case");
}
protected LeafNode getRandomPubnode(PubSubManager pubMgr, boolean persistItems, boolean deliverPayload) throws XMPPException
{
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setPersistentItems(persistItems);
form.setDeliverPayloads(deliverPayload);
form.setAccessModel(AccessModel.open);
return (LeafNode)pubMgr.createNode("/test/Pubnode" + System.currentTimeMillis(), form);
}
protected LeafNode getPubnode(PubSubManager pubMgr, boolean persistItems, boolean deliverPayload, String nodeId) throws XMPPException
{
LeafNode node = null;
try
{
node = (LeafNode)pubMgr.getNode(nodeId);
}
catch (XMPPException e)
{
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setPersistentItems(persistItems);
form.setDeliverPayloads(deliverPayload);
form.setAccessModel(AccessModel.open);
node = (LeafNode)pubMgr.createNode(nodeId, form);
}
return node;
}
protected PubSubManager getManager(int idx)
{
if (manager == null)
{
manager = new PubSubManager[getMaxConnections()];
for(int i=0; i<manager.length; i++)
{
manager[i] = new PubSubManager(getConnection(i), getService());
}
}
return manager[idx];
}
protected String getService()
{
return "pubsub." + getServiceName();
}
}

View file

@ -0,0 +1,46 @@
/**
*
* Copyright 2009 Robin Collier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.pubsub.test;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.PubSubManager;
/**
*
* @author Robin Collier
*
*/
public class SingleUserTestCase extends PubSubTestCase
{
protected PubSubManager getManager()
{
return getManager(0);
}
protected LeafNode getPubnode(boolean persistItems, boolean deliverPayload) throws XMPPException
{
return getRandomPubnode(getManager(), persistItems, deliverPayload);
}
@Override
protected int getMaxConnections()
{
return 1;
}
}