1
0
Fork 0
mirror of https://codeberg.org/Mercury-IM/Smack synced 2025-09-10 18:59:41 +02:00

Activate the jingle subproject and move integration tests

The jingle subproject builds now. This doesn't change that the code is
outdated with regard to the specification and unmaintained for
years. But hopefully this is the first step to change that. :)

The integration tests have been moved into SourceSets of 'core' and
'extensions'.
This commit is contained in:
Florian Schmaus 2014-02-19 10:38:30 +01:00
parent f7d3f559a2
commit 602a8fc812
177 changed files with 441 additions and 590 deletions

View file

@ -0,0 +1,95 @@
/**
*
* 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.smack;
import java.util.Date;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.filter.ThreadFilter;
/**
* Tests the chat functionality.
*
* @author Gaston Dombiak
*/
public class ChatTest extends SmackTestCase {
public ChatTest(String arg0) {
super(arg0);
}
public void testProperties() {
try {
Chat newChat = getConnection(0).getChatManager().createChat(getFullJID(1), null);
PacketCollector collector = getConnection(1)
.createPacketCollector(new ThreadFilter(newChat.getThreadID()));
Message msg = new Message();
msg.setSubject("Subject of the chat");
msg.setBody("Body of the chat");
msg.setProperty("favoriteColor", "red");
msg.setProperty("age", 30);
msg.setProperty("distance", 30f);
msg.setProperty("weight", 30d);
msg.setProperty("male", true);
msg.setProperty("birthdate", new Date());
newChat.sendMessage(msg);
Message msg2 = (Message) collector.nextResult(2000);
assertNotNull("No message was received", msg2);
assertEquals("Subjects are different", msg.getSubject(), msg2.getSubject());
assertEquals("Bodies are different", msg.getBody(), msg2.getBody());
assertEquals(
"favoriteColors are different",
msg.getProperty("favoriteColor"),
msg2.getProperty("favoriteColor"));
assertEquals(
"ages are different",
msg.getProperty("age"),
msg2.getProperty("age"));
assertEquals(
"distances are different",
msg.getProperty("distance"),
msg2.getProperty("distance"));
assertEquals(
"weights are different",
msg.getProperty("weight"),
msg2.getProperty("weight"));
assertEquals(
"males are different",
msg.getProperty("male"),
msg2.getProperty("male"));
assertEquals(
"birthdates are different",
msg.getProperty("birthdate"),
msg2.getProperty("birthdate"));
}
catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,103 @@
/**
*
* 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.smack;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.filter.ThreadFilter;
/**
* Simple test to measure server performance.
*
* @author Gaston Dombiak
*/
public class FloodTest extends SmackTestCase {
public FloodTest(String arg0) {
super(arg0);
}
public void testMessageFlood() {
try {
Chat chat11 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
PacketCollector chat12 = getConnection(1).createPacketCollector(
new ThreadFilter(chat11.getThreadID()));
Chat chat21 = getConnection(0).getChatManager().createChat(getBareJID(2), null);
PacketCollector chat22 = getConnection(2).createPacketCollector(
new ThreadFilter(chat21.getThreadID()));
Chat chat31 = getConnection(0).getChatManager().createChat(getBareJID(3), null);
PacketCollector chat32 = getConnection(3).createPacketCollector(
new ThreadFilter(chat31.getThreadID()));
for (int i=0; i<500; i++) {
chat11.sendMessage("Hello_1" + i);
chat21.sendMessage("Hello_2" + i);
chat31.sendMessage("Hello_3" + i);
}
for (int i=0; i<500; i++) {
assertNotNull("Some message was lost (" + i + ")", chat12.nextResult(1000));
assertNotNull("Some message was lost (" + i + ")", chat22.nextResult(1000));
assertNotNull("Some message was lost (" + i + ")", chat32.nextResult(1000));
}
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/*public void testMUCFlood() {
try {
int floodNumber = 50000;
MultiUserChat chat = new MultiUserChat(getConnection(0), "myroom@" + getMUCDomain());
chat.create("phatom");
chat.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
MultiUserChat chat2 = new MultiUserChat(getConnection(1), "myroom@" + getMUCDomain());
chat2.join("christine");
for (int i=0; i<floodNumber; i++)
{
chat.sendMessage("hi");
}
Thread.sleep(200);
for (int i=0; i<floodNumber; i++)
{
if (i % 100 == 0) {
System.out.println(i);
}
assertNotNull("Received " + i + " of " + floodNumber + " messages",
chat2.nextMessage(SmackConfiguration.getPacketReplyTimeout()));
}
chat.leave();
//chat2.leave();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}*/
protected int getMaxConnections() {
return 4;
}
}

View file

@ -0,0 +1,102 @@
/**
*
* 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.smack;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.packet.Version;
/**
* Ensure that the server is handling IQ packets correctly.
*
* @author Gaston Dombiak
*/
public class IQTest extends SmackTestCase {
public IQTest(String arg0) {
super(arg0);
}
/**
* Check that the server responds a 503 error code when the client sends an IQ packet with an
* invalid namespace.
*/
public void testInvalidNamespace() {
IQ iq = new IQ() {
public String getChildElementXML() {
StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:anything\">");
buf.append("</query>");
return buf.toString();
}
};
PacketFilter filter = new AndFilter(new PacketIDFilter(iq.getPacketID()),
new PacketTypeFilter(IQ.class));
PacketCollector collector = getConnection(0).createPacketCollector(filter);
// Send the iq packet with an invalid namespace
getConnection(0).sendPacket(iq);
IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
collector.cancel();
if (result == null) {
fail("No response from server");
}
else if (result.getType() != IQ.Type.ERROR) {
fail("The server didn't reply with an error packet");
}
else {
assertEquals("Server answered an incorrect error code", 503, result.getError().getCode());
}
}
/**
* Check that sending an IQ to a full JID that is offline returns an IQ ERROR instead
* of being route to some other resource of the same user.
*/
public void testFullJIDToOfflineUser() {
// Request the version from the server.
Version versionRequest = new Version();
versionRequest.setType(IQ.Type.GET);
versionRequest.setFrom(getFullJID(0));
versionRequest.setTo(getBareJID(0) + "/Something");
// Create a packet collector to listen for a response.
PacketCollector collector = getConnection(0).createPacketCollector(
new PacketIDFilter(versionRequest.getPacketID()));
getConnection(0).sendPacket(versionRequest);
// Wait up to 5 seconds for a result.
IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
collector.cancel();
assertNotNull("No response from server", result);
assertEquals("The server didn't reply with an error packet", IQ.Type.ERROR, result.getType());
assertEquals("Server answered an incorrect error code", 503, result.getError().getCode());
}
protected int getMaxConnections() {
return 1;
}
}

View file

@ -0,0 +1,184 @@
/**
*
* 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.smack;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.util.StringUtils;
/**
* Includes set of login tests.
*
* @author Gaston Dombiak
*/
public class LoginTest extends SmackTestCase {
public LoginTest(String arg0) {
super(arg0);
}
/**
* Check that the server is returning the correct error when trying to login using an invalid
* (i.e. non-existent) user.
*/
public void testInvalidLogin() {
try {
XMPPConnection connection = createConnection();
connection.connect();
try {
// Login with an invalid user
connection.login("invaliduser" , "invalidpass");
connection.disconnect();
fail("Invalid user was able to log into the server");
}
catch (XMPPException e) {
if (e.getXMPPError() != null) {
assertEquals("Incorrect error code while login with an invalid user", 401,
e.getXMPPError().getCode());
}
}
// Wait here while trying tests with exodus
//Thread.sleep(300);
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check that the server handles anonymous users correctly.
*/
public void testSASLAnonymousLogin() {
if (!isTestAnonymousLogin()) return;
try {
XMPPConnection conn1 = createConnection();
XMPPConnection conn2 = createConnection();
conn1.connect();
conn2.connect();
try {
// Try to login anonymously
conn1.loginAnonymously();
conn2.loginAnonymously();
assertNotNull("Resource is null", StringUtils.parseResource(conn1.getUser()));
assertNotNull("Resource is null", StringUtils.parseResource(conn2.getUser()));
assertNotNull("Username is null", StringUtils.parseName(conn1.getUser()));
assertNotNull("Username is null", StringUtils.parseName(conn2.getUser()));
}
catch (XMPPException e) {
fail(e.getMessage());
}
finally {
// Close the connection
conn1.disconnect();
conn2.disconnect();
}
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check that the server handles anonymous users correctly.
*/
public void testNonSASLAnonymousLogin() {
if (!isTestAnonymousLogin()) return;
try {
ConnectionConfiguration config = new ConnectionConfiguration(getHost(), getPort());
config.setSASLAuthenticationEnabled(false);
XMPPConnection conn1 = new XMPPConnection(config);
conn1.connect();
config = new ConnectionConfiguration(getHost(), getPort());
config.setSASLAuthenticationEnabled(false);
XMPPConnection conn2 = new XMPPConnection(config);
conn2.connect();
try {
// Try to login anonymously
conn1.loginAnonymously();
conn2.loginAnonymously();
assertNotNull("Resource is null", StringUtils.parseResource(conn1.getUser()));
assertNotNull("Resource is null", StringUtils.parseResource(conn2.getUser()));
assertNotNull("Username is null", StringUtils.parseName(conn1.getUser()));
assertNotNull("Username is null", StringUtils.parseName(conn2.getUser()));
}
catch (XMPPException e) {
fail(e.getMessage());
}
// Close the connection
conn1.disconnect();
conn2.disconnect();
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check that the server does not allow to log in without specifying a resource.
*/
public void testLoginWithNoResource() {
try {
XMPPConnection conn = createConnection();
conn.connect();
try {
conn.getAccountManager().createAccount("user_1", "user_1", getAccountCreationParameters());
} catch (XMPPException e) {
// Do nothing if the account already exists
if (e.getXMPPError().getCode() != 409) {
throw e;
}
// Else recreate the connection, ins case the server closed it as
// a result of the error, so we can login.
conn = createConnection();
conn.connect();
}
conn.login("user_1", "user_1", (String) null);
if (conn.getSASLAuthentication().isAuthenticated()) {
// Check that the server assigned a resource
assertNotNull("JID assigned by server is missing", conn.getUser());
assertNotNull("JID assigned by server does not have a resource",
StringUtils.parseResource(conn.getUser()));
conn.disconnect();
}
else {
fail("User with no resource was not able to log into the server");
}
} catch (XMPPException e) {
if (e.getXMPPError() != null) {
assertEquals("Wrong error code returned", 406, e.getXMPPError().getCode());
} else {
fail(e.getMessage());
}
}
}
protected int getMaxConnections() {
return 0;
}
}

View file

@ -0,0 +1,408 @@
/**
*
* 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.smack;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.test.SmackTestCase;
/**
* Tests sending messages to other clients.
*
* @author Gaston Dombiak
*/
public class MessageTest extends SmackTestCase {
public MessageTest(String arg0) {
super(arg0);
}
/**
* Will a user recieve a message from another after only sending the user a directed presence,
* or will Wildfire intercept for offline storage?
*
* User1 becomes lines. User0 never sent an available presence to the server but
* instead sent one to User1. User1 sends a message to User0. Should User0 get the
* message?
*/
public void testDirectPresence() {
getConnection(1).sendPacket(new Presence(Presence.Type.available));
Presence presence = new Presence(Presence.Type.available);
presence.setTo(getBareJID(1));
getConnection(0).sendPacket(presence);
PacketCollector collector = getConnection(0)
.createPacketCollector(new MessageTypeFilter(Message.Type.chat));
try {
getConnection(1).getChatManager().createChat(getBareJID(0), null).sendMessage("Test 1");
}
catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
Message message = (Message) collector.nextResult(2500);
assertNotNull("Message not recieved from remote user", message);
}
/**
* Check that when a client becomes unavailable all messages sent to the client are stored offline. So that when
* the client becomes available again the offline messages are received.
*/
public void testOfflineMessage() {
getConnection(0).sendPacket(new Presence(Presence.Type.available));
getConnection(1).sendPacket(new Presence(Presence.Type.available));
// 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);
PacketCollector collector = getConnection(1).createPacketCollector(
new MessageTypeFilter(Message.Type.chat));
chat.sendMessage("Test 1");
chat.sendMessage("Test 2");
Thread.sleep(500);
// User2 becomes available again
getConnection(1).sendPacket(new Presence(Presence.Type.available));
// Check that offline messages are retrieved by user2 which is now available
Message message = (Message) collector.nextResult(2500);
assertNotNull(message);
message = (Message) collector.nextResult(2000);
assertNotNull(message);
message = (Message) collector.nextResult(1000);
assertNull(message);
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Send messages with invalid XML characters to offline users. Check that offline users
* are receiving them from the server.<p>
*
* Test case commented out since some servers may just close the connection while others
* are more tolerant and accept stanzas with invalid XML characters.
*/
/*public void testOfflineMessageInvalidXML() {
// 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);
PacketCollector collector = getConnection(1).createPacketCollector(
new MessageTypeFilter(Message.Type.chat));
chat.sendMessage("Test \f 1");
chat.sendMessage("Test \r 1");
Thread.sleep(500);
// User2 becomes available again
getConnection(1).sendPacket(new Presence(Presence.Type.available));
// Check that offline messages are retrieved by user2 which is now available
Message message = (Message) collector.nextResult(2500);
assertNotNull(message);
message = (Message) collector.nextResult(2000);
assertNotNull(message);
message = (Message) collector.nextResult(1000);
assertNull(message);
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}*/
/**
* Check that two clients are able to send messages with a body of 4K characters and their
* connections are not being closed.
*/
public void testHugeMessage() {
getConnection(0).sendPacket(new Presence(Presence.Type.available));
getConnection(1).sendPacket(new Presence(Presence.Type.available));
// User2 becomes available again
PacketCollector collector = getConnection(1).createPacketCollector(
new MessageTypeFilter(Message.Type.chat));
// Create message with a body of 4K characters
Message msg = new Message(getFullJID(1), Message.Type.chat);
StringBuilder sb = new StringBuilder(5000);
for (int i = 0; i <= 4000; i++) {
sb.append("X");
}
msg.setBody(sb.toString());
// Send the first message
getConnection(0).sendPacket(msg);
// Check that the connection that sent the message is still connected
assertTrue("Connection was closed", getConnection(0).isConnected());
// Check that the message was received
Message rcv = (Message) collector.nextResult(1000);
assertNotNull("No Message was received", rcv);
// Send the second message
getConnection(0).sendPacket(msg);
// Check that the connection that sent the message is still connected
assertTrue("Connection was closed", getConnection(0).isConnected());
// Check that the second message was received
rcv = (Message) collector.nextResult(1000);
assertNotNull("No Message was received", rcv);
}
/**
* User0 is connected from 2 resources. User0 is available in both resources
* but with different priority presence values. User1 sends a message to the
* bare JID of User0. Check that the resource with highest priority will get
* the messages.
*
* @throws Exception if an error occurs.
*/
public void testHighestPriority() throws Exception {
// Create another connection for the same user of connection 1
ConnectionConfiguration connectionConfiguration =
new ConnectionConfiguration(getHost(), getPort(), getServiceName());
XMPPConnection conn3 = new XMPPConnection(connectionConfiguration);
conn3.connect();
conn3.login(getUsername(0), getPassword(0), "Home");
// Set this connection as highest priority
Presence presence = new Presence(Presence.Type.available);
presence.setPriority(10);
conn3.sendPacket(presence);
// Set this connection as highest priority
presence = new Presence(Presence.Type.available);
presence.setPriority(5);
getConnection(0).sendPacket(presence);
// Let the server process the change in presences
Thread.sleep(200);
// User0 listen in both connected clients
PacketCollector collector = getConnection(0).createPacketCollector(new MessageTypeFilter(Message.Type.chat));
PacketCollector coll3 = conn3.createPacketCollector(new MessageTypeFilter(Message.Type.chat));
// User1 sends a message to the bare JID of User0
Chat chat = getConnection(1).getChatManager().createChat(getBareJID(0), null);
chat.sendMessage("Test 1");
chat.sendMessage("Test 2");
// Check that messages were sent to resource with highest priority
Message message = (Message) collector.nextResult(2000);
assertNull("Resource with lowest priority got the message", message);
message = (Message) coll3.nextResult(2000);
assertNotNull(message);
assertEquals("Test 1", message.getBody());
message = (Message) coll3.nextResult(1000);
assertNotNull(message);
assertEquals("Test 2", message.getBody());
conn3.disconnect();
}
/**
* User0 is connected from 2 resources. User0 is available in both resources
* but with different show values. User1 sends a message to the
* bare JID of User0. Check that the resource with highest show value will get
* the messages.
*
* @throws Exception if an error occurs.
*/
public void testHighestShow() throws Exception {
// Create another connection for the same user of connection 1
ConnectionConfiguration connectionConfiguration =
new ConnectionConfiguration(getHost(), getPort(), getServiceName());
XMPPConnection conn3 = new XMPPConnection(connectionConfiguration);
conn3.connect();
conn3.login(getUsername(0), getPassword(0), "Home");
// Set this connection as highest priority
Presence presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.away);
conn3.sendPacket(presence);
// Set this connection as highest priority
presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.available);
getConnection(0).sendPacket(presence);
// Let the server process the change in presences
Thread.sleep(200);
// User0 listen in both connected clients
PacketCollector collector = getConnection(0).createPacketCollector(new MessageTypeFilter(Message.Type.chat));
PacketCollector coll3 = conn3.createPacketCollector(new MessageTypeFilter(Message.Type.chat));
// User1 sends a message to the bare JID of User0
Chat chat = getConnection(1).getChatManager().createChat(getBareJID(0), null);
chat.sendMessage("Test 1");
chat.sendMessage("Test 2");
// Check that messages were sent to resource with highest priority
Message message = (Message) coll3.nextResult(2000);
assertNull("Resource with lowest show value got the message", message);
message = (Message) collector.nextResult(2000);
assertNotNull(message);
assertEquals("Test 1", message.getBody());
message = (Message) collector.nextResult(1000);
assertNotNull(message);
assertEquals("Test 2", message.getBody());
conn3.disconnect();
}
/**
* User0 is connected from 2 resources. User0 is available in both resources
* with same priority presence values and same show values. User1 sends a message to the
* bare JID of User0. Check that the resource with most recent activity will get
* the messages.
*
* @throws Exception if an error occurs.
*/
public void testMostRecentActive() throws Exception {
// Create another connection for the same user of connection 1
ConnectionConfiguration connectionConfiguration =
new ConnectionConfiguration(getHost(), getPort(), getServiceName());
XMPPConnection conn3 = new XMPPConnection(connectionConfiguration);
conn3.connect();
conn3.login(getUsername(0), getPassword(0), "Home");
// Set this connection as highest priority
Presence presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.available);
presence.setPriority(10);
conn3.sendPacket(presence);
// Set this connection as highest priority
presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.available);
presence.setPriority(10);
getConnection(0).sendPacket(presence);
connectionConfiguration =
new ConnectionConfiguration(getHost(), getPort(), getServiceName());
XMPPConnection conn4 = new XMPPConnection(connectionConfiguration);
conn4.connect();
conn4.login(getUsername(0), getPassword(0), "Home2");
presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.available);
presence.setPriority(4);
getConnection(0).sendPacket(presence);
// Let the server process the change in presences
Thread.sleep(200);
// User0 listen in both connected clients
PacketCollector collector = getConnection(0).createPacketCollector(new MessageTypeFilter(Message.Type.chat));
PacketCollector coll3 = conn3.createPacketCollector(new MessageTypeFilter(Message.Type.chat));
PacketCollector coll4 = conn4.createPacketCollector(new MessageTypeFilter(Message.Type.chat));
// Send a message from this resource to indicate most recent activity
conn3.sendPacket(new Message("admin@" + getServiceName()));
// User1 sends a message to the bare JID of User0
Chat chat = getConnection(1).getChatManager().createChat(getBareJID(0), null);
chat.sendMessage("Test 1");
chat.sendMessage("Test 2");
// Check that messages were sent to resource with highest priority
Message message = (Message) collector.nextResult(2000);
assertNull("Resource with oldest activity got the message", message);
message = (Message) coll4.nextResult(2000);
assertNull(message);
message = (Message) coll3.nextResult(2000);
assertNotNull(message);
assertEquals("Test 1", message.getBody());
message = (Message) coll3.nextResult(1000);
assertNotNull(message);
assertEquals("Test 2", message.getBody());
conn3.disconnect();
conn4.disconnect();
}
/**
* User0 is connected from 1 resource with a negative priority presence. User1
* sends a message to the bare JID of User0. Messages should be stored offline.
* User0 then changes the priority presence to a positive value. Check that
* offline messages were delivered to the user.
*
* @throws Exception if an error occurs.
*/
public void testOfflineStorageWithNegativePriority() throws Exception {
// Set this connection with negative priority
Presence presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.available);
presence.setPriority(-1);
getConnection(0).sendPacket(presence);
// Let the server process the change in presences
Thread.sleep(200);
// User0 listen for incoming traffic
PacketCollector collector = getConnection(0).createPacketCollector(new MessageTypeFilter(Message.Type.chat));
// User1 sends a message to the bare JID of User0
Chat chat = getConnection(1).getChatManager().createChat(getBareJID(0), null);
chat.sendMessage("Test 1");
chat.sendMessage("Test 2");
// Check that messages were sent to resource with highest priority
Message message = (Message) collector.nextResult(2000);
assertNull("Messages were not stored offline", message);
// Set this connection with positive priority
presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.available);
presence.setPriority(1);
getConnection(0).sendPacket(presence);
// Let the server process the change in presences
Thread.sleep(200);
message = (Message) collector.nextResult(2000);
assertNotNull("Offline messages were not delivered", message);
assertEquals("Test 1", message.getBody());
message = (Message) collector.nextResult(1000);
assertNotNull(message);
assertEquals("Test 2", message.getBody());
}
protected int getMaxConnections() {
return 2;
}
@Override
protected boolean sendInitialPresence() {
return false;
}
}

View file

@ -0,0 +1,257 @@
/**
*
* 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.smack;
import org.jivesoftware.smack.filter.FromMatchesFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.test.SmackTestCase;
import java.util.Date;
public class PacketReaderTest extends SmackTestCase {
private int counter;
private final Object mutex = new Object();
/**
* Constructor for PacketReaderTest.
*
* @param arg0
*/
public PacketReaderTest(String arg0) {
super(arg0);
resetCounter();
}
// Counter management
private void resetCounter() {
synchronized (mutex) {
counter = 0;
}
}
public void incCounter() {
synchronized (mutex) {
counter++;
}
}
private int valCounter() {
int val;
synchronized (mutex) {
val = counter;
}
return val;
}
/**
* Verify that when Smack receives a "not implemented IQ" answers with an IQ packet
* with error code 501.
*/
public void testIQNotImplemented() {
// Create a new type of IQ to send. The new IQ will include a
// non-existant namespace to cause the "feature-not-implemented" answer
IQ iqPacket = new IQ() {
public String getChildElementXML() {
return "<query xmlns=\"my:ns:test\"/>";
}
};
iqPacket.setTo(getFullJID(1));
iqPacket.setType(IQ.Type.GET);
// Send the IQ and wait for the answer
PacketCollector collector = getConnection(0).createPacketCollector(
new PacketIDFilter(iqPacket.getPacketID()));
getConnection(0).sendPacket(iqPacket);
IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
if (response == null) {
fail("No response from the other user.");
}
assertEquals("The received IQ is not of type ERROR", IQ.Type.ERROR, response.getType());
assertEquals("The error code is not 501", 501, response.getError().getCode());
collector.cancel();
}
/**
* Tests that PacketReader adds new listeners and also removes them correctly.
*/
public void testRemoveListener() {
PacketListener listener = new PacketListener() {
public void processPacket(Packet packet) {
// Do nothing
}
};
// Keep number of current listeners
int listenersSize = getConnection(0).getPacketListeners().size();
// Add a new listener
getConnection(0).addPacketListener(listener, new MockPacketFilter(true));
// Check that the listener was added
assertEquals("Listener was not added", listenersSize + 1,
getConnection(0).getPacketListeners().size());
Message msg = new Message(getConnection(0).getUser(), Message.Type.normal);
getConnection(1).sendPacket(msg);
// Remove the listener
getConnection(0).removePacketListener(listener);
// Check that the number of listeners is correct (i.e. the listener was removed)
assertEquals("Listener was not removed", listenersSize,
getConnection(0).getPacketListeners().size());
}
/**
* Checks that parser still works when receiving an error text with no description.
*/
public void testErrorWithNoText() {
// Send a regular message from user0 to user1
Message packet = new Message();
packet.setFrom(getFullJID(0));
packet.setTo(getFullJID(1));
packet.setBody("aloha");
// User1 will always reply to user0 when a message is received
getConnection(1).addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
System.out.println(new Date() + " " + packet);
Message message = new Message(packet.getFrom());
message.setFrom(getFullJID(1));
message.setBody("HELLO");
getConnection(1).sendPacket(message);
}
}, new PacketTypeFilter(Message.class));
// User0 listen for replies from user1
PacketCollector collector = getConnection(0).createPacketCollector(
new FromMatchesFilter(getFullJID(1)));
// User0 sends the regular message to user1
getConnection(0).sendPacket(packet);
// Check that user0 got a reply from user1
assertNotNull("No message was received", collector.nextResult(1000));
// Send a message with an empty error text
packet = new Message();
packet.setFrom(getFullJID(0));
packet.setTo(getFullJID(1));
packet.setBody("aloha");
packet.setError(new XMPPError(XMPPError.Condition.feature_not_implemented, null));
getConnection(0).sendPacket(packet);
// Check that user0 got a reply from user1
assertNotNull("No message was received", collector.nextResult(1000));
}
/**
* Tests that PacketReader adds new listeners and also removes them correctly.
*/
public void testFiltersRemotion() {
resetCounter();
int repeat = 10;
for (int j = 0; j < repeat; j++) {
PacketListener listener0 = new PacketListener() {
public void processPacket(Packet packet) {
System.out.println("Packet Captured");
incCounter();
}
};
PacketFilter pf0 = new PacketFilter() {
public boolean accept(Packet packet) {
System.out.println("Packet Filtered");
incCounter();
return true;
}
};
PacketListener listener1 = new PacketListener() {
public void processPacket(Packet packet) {
System.out.println("Packet Captured");
incCounter();
}
};
PacketFilter pf1 = new PacketFilter() {
public boolean accept(Packet packet) {
System.out.println("Packet Filtered");
incCounter();
return true;
}
};
getConnection(0).addPacketListener(listener0, pf0);
getConnection(1).addPacketListener(listener1, pf1);
// Check that the listener was added
Message msg0 = new Message(getConnection(0).getUser(), Message.Type.normal);
Message msg1 = new Message(getConnection(1).getUser(), Message.Type.normal);
for (int i = 0; i < 5; i++) {
getConnection(1).sendPacket(msg0);
getConnection(0).sendPacket(msg1);
}
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
// Remove the listener
getConnection(0).removePacketListener(listener0);
getConnection(1).removePacketListener(listener1);
try {
Thread.sleep(300);
}
catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
getConnection(0).sendPacket(msg1);
getConnection(1).sendPacket(msg0);
}
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(valCounter());
assertEquals(valCounter(), repeat * 2 * 10);
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,274 @@
/**
*
* 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.smack;
import java.util.Iterator;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.test.SmackTestCase;
/**
* Ensure that the server is delivering messages to the correct client based on the client's
* presence priority.
*
* @author Gaston Dombiak
*/
public class PresenceTest extends SmackTestCase {
public PresenceTest(String arg0) {
super(arg0);
}
/**
* Connection(0) will send messages to the bareJID of Connection(1) where the user of
* Connection(1) has logged from two different places with different presence priorities.
*/
public void testMessageToHighestPriority() {
XMPPConnection conn = null;
try {
// User_1 will log in again using another resource
conn = createConnection();
conn.connect();
conn.login(getUsername(1), getUsername(1), "OtherPlace");
// Change the presence priorities of User_1
getConnection(1).sendPacket(new Presence(Presence.Type.available, null, 1,
Presence.Mode.available));
conn.sendPacket(new Presence(Presence.Type.available, null, 2,
Presence.Mode.available));
Thread.sleep(150);
// Create the chats between the participants
Chat chat0 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
Chat chat1 = getConnection(1).getChatManager().createChat(getBareJID(0), chat0.getThreadID(), null);
Chat chat2 = conn.getChatManager().createChat(getBareJID(0), chat0.getThreadID(), null);
// Test delivery of message to the presence with highest priority
chat0.sendMessage("Hello");
/*assertNotNull("Resource with highest priority didn't receive the message",
chat2.nextMessage(2000));
assertNull("Resource with lowest priority received the message",
chat1.nextMessage(1000));*/
// Invert the presence priorities of User_1
getConnection(1).sendPacket(new Presence(Presence.Type.available, null, 2,
Presence.Mode.available));
conn.sendPacket(new Presence(Presence.Type.available, null, 1,
Presence.Mode.available));
Thread.sleep(150);
// Test delivery of message to the presence with highest priority
chat0.sendMessage("Hello");
/*assertNotNull("Resource with highest priority didn't receive the message",
chat1.nextMessage(2000));
assertNull("Resource with lowest priority received the message",
chat2.nextMessage(1000));*/
// User_1 closes his connection
conn.disconnect();
Thread.sleep(150);
// Test delivery of message to the unique presence of the user_1
chat0.sendMessage("Hello");
/*assertNotNull("Resource with highest priority didn't receive the message",
chat1.nextMessage(2000));*/
getConnection(1).sendPacket(new Presence(Presence.Type.available, null, 2,
Presence.Mode.available));
// User_1 will log in again using another resource
conn = createConnection();
conn.connect();
conn.login(getUsername(1), getPassword(1), "OtherPlace");
conn.sendPacket(new Presence(Presence.Type.available, null, 1,
Presence.Mode.available));
chat2 = conn.getChatManager().createChat(getBareJID(0), chat0.getThreadID(), null);
Thread.sleep(150);
// Test delivery of message to the presence with highest priority
chat0.sendMessage("Hello");
/*assertNotNull("Resource with highest priority didn't receive the message",
chat1.nextMessage(2000));
assertNull("Resource with lowest priority received the message",
chat2.nextMessage(1000));*/
// Invert the presence priorities of User_1
getConnection(1).sendPacket(new Presence(Presence.Type.available, null, 1,
Presence.Mode.available));
conn.sendPacket(new Presence(Presence.Type.available, null, 2,
Presence.Mode.available));
Thread.sleep(150);
// Test delivery of message to the presence with highest priority
chat0.sendMessage("Hello");
/*assertNotNull("Resource with highest priority didn't receive the message",
chat2.nextMessage(2000));
assertNull("Resource with lowest priority received the message",
chat1.nextMessage(1000));*/
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
finally {
if (conn != null) {
conn.disconnect();
}
}
}
/**
* User1 logs from 2 resources but only one is available. User0 sends a message
* to the full JID of the unavailable resource. User1 in the not available resource
* should receive the message.
* TODO Fix this in Wildfire but before check if XMPP spec requests this feature
*/
public void testNotAvailablePresence() throws XMPPException {
// Change the presence to unavailable of User_1
getConnection(1).sendPacket(new Presence(Presence.Type.unavailable));
// User_1 will log in again using another resource (that is going to be available)
XMPPConnection conn = createConnection();
conn.connect();
conn.login(getUsername(1), getPassword(1), "OtherPlace");
// Create chats between participants
Chat chat0 = getConnection(0).getChatManager().createChat(getFullJID(1), null);
Chat chat1 = getConnection(1).getChatManager().createChat(getBareJID(0), chat0.getThreadID(), null);
// Test delivery of message to the presence with highest priority
chat0.sendMessage("Hello");
/*assertNotNull("Not available connection didn't receive message sent to full JID",
chat1.nextMessage(2000));
assertNull("Not available connection received an unknown message",
chat1.nextMessage(1000));*/
conn.disconnect();
}
/**
* User1 is connected from 2 resources. User1 adds User0 to his roster. Ensure
* that presences are correctly retrieved for User1. User1 logs off from one resource
* and ensure that presences are still correct for User1.
*/
public void testMultipleResources() throws Exception {
// Create another connection for the same user of connection 1
ConnectionConfiguration connectionConfiguration =
new ConnectionConfiguration(getHost(), getPort(), getServiceName());
XMPPConnection conn4 = new XMPPConnection(connectionConfiguration);
conn4.connect();
conn4.login(getUsername(1), getPassword(1), "Home");
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
roster.createEntry(getBareJID(1), "gato1", null);
// Wait up to 2 seconds
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && (
!roster.getPresence(getBareJID(1)).isAvailable()))
{
Thread.sleep(100);
}
// Check that a presence is returned for the new contact
Presence presence = roster.getPresence(getBareJID(1));
assertTrue("Returned an offline Presence for an existing user", presence.isAvailable());
presence = roster.getPresenceResource(getBareJID(1) + "/Home");
assertTrue("Returned an offline Presence for Home resource", presence.isAvailable());
presence = roster.getPresenceResource(getFullJID(1));
assertTrue("Returned an offline Presence for Smack resource", presence.isAvailable());
Iterator<Presence> presences = roster.getPresences(getBareJID(1));
assertTrue("Returned an offline Presence for an existing user", presence.isAvailable());
assertNotNull("No presence was found for user1", presences);
assertTrue("No presence was found for user1", presences.hasNext());
presences.next();
assertTrue("Only one presence was found for user1", presences.hasNext());
// User1 logs out from one resource
conn4.disconnect();
// Wait up to 1 second
Thread.sleep(700);
// Check that a presence is returned for the new contact
presence = roster.getPresence(getBareJID(1));
assertTrue("Returned a null Presence for an existing user", presence.isAvailable());
presence = roster.getPresenceResource(getFullJID(1));
assertTrue("Returned a null Presence for Smack resource", presence.isAvailable());
presence = roster.getPresenceResource(getBareJID(1) + "/Home");
assertTrue("Returned a Presence for no longer connected resource", !presence.isAvailable());
presences = roster.getPresences(getBareJID(1));
assertNotNull("No presence was found for user1", presences);
Presence value = presences.next();
assertTrue("No presence was found for user1", value.isAvailable());
assertFalse("More than one presence was found for user1", presences.hasNext());
}
/**
* User1 logs in, then sets offline presence information (presence with status text). User2
* logs in and checks to see if offline presence is returned.
*
* @throws Exception if an exception occurs.
*/
public void testOfflineStatusPresence() throws Exception {
// Add a new roster entry for other user.
Roster roster = getConnection(0).getRoster();
roster.createEntry(getBareJID(1), "gato1", null);
// Wait up to 2 seconds
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && (
roster.getPresence(getBareJID(1)).getType().equals(Presence.Type.unavailable))) {
Thread.sleep(100);
}
// Sign out of conn1 with status
Presence offlinePresence = new Presence(Presence.Type.unavailable);
offlinePresence.setStatus("Offline test");
getConnection(1).disconnect(offlinePresence);
// Wait 500 ms
Thread.sleep(500);
Presence presence = getConnection(0).getRoster().getPresence(getBareJID(1));
assertEquals("Offline presence status not received.", "Offline test", presence.getStatus());
// Sign out of conn0.
getConnection(0).disconnect();
// See if conneciton 0 can get offline status.
XMPPConnection con0 = getConnection(0);
con0.connect();
con0.login(getUsername(0), getUsername(0));
// Wait 500 ms
Thread.sleep(500);
presence = con0.getRoster().getPresence(getBareJID(1));
assertTrue("Offline presence status not received after logout.",
"Offline test".equals(presence.getStatus()));
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,56 @@
/**
*
* 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.smack;
import java.util.List;
import org.jivesoftware.smack.packet.Privacy;
import org.jivesoftware.smack.packet.PrivacyItem;
/**
* This class supports automated tests about privacy communication from the
* server to the client.
*
* @author Francisco Vives
*/
public class PrivacyClient implements PrivacyListListener {
/**
* holds if the receiver list was modified
*/
private boolean wasModified = false;
/**
* holds a privacy to hold server requests Clients should not use Privacy
* class since it is private for the smack framework.
*/
private Privacy privacy = new Privacy();
public PrivacyClient(PrivacyListManager manager) {
super();
}
public void setPrivacyList(String listName, List<PrivacyItem> listItem) {
privacy.setPrivacyList(listName, listItem);
}
public void updatedPrivacyList(String listName) {
this.wasModified = true;
}
public boolean wasModified() {
return this.wasModified;
}
}

View file

@ -0,0 +1,257 @@
/**
*
* 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.smack;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.ping.PingManager;
/**
* Tests the connection and reconnection mechanism
*
* @author Francisco Vives
*/
public class ReconnectionTest extends SmackTestCase {
private static final long MIN_RECONNECT_WAIT = 17; // Seconds
public ReconnectionTest(String arg0) {
super(arg0);
}
/**
* Tests an automatic reconnection.
* Simulates a connection error and then waits until gets reconnected.
*/
public void testAutomaticReconnection() throws Exception {
XMPPConnection connection = getConnection(0);
CountDownLatch latch = new CountDownLatch(1);
XMPPConnectionTestListener listener = new XMPPConnectionTestListener(latch);
connection.addConnectionListener(listener);
// Simulates an error in the connection
connection.notifyConnectionError(new Exception("Simulated Error"));
latch.await(MIN_RECONNECT_WAIT, TimeUnit.SECONDS);
// After 10 seconds, the reconnection manager must reestablishes the connection
assertEquals("The ConnectionListener.connectionStablished() notification was not fired", true, listener.reconnected);
assertTrue("The ReconnectionManager algorithm has reconnected without waiting at least 5 seconds", listener.attemptsNotifications > 0);
// Executes some server interaction testing the connection
executeSomeServerInteraction(connection);
}
public void testAutomaticReconnectionWithCompression() throws Exception {
// Create the configuration for this new connection
ConnectionConfiguration config = new ConnectionConfiguration(getHost(), getPort());
config.setCompressionEnabled(true);
config.setSASLAuthenticationEnabled(true);
XMPPConnection connection = new XMPPConnection(config);
// Connect to the server
connection.connect();
// Log into the server
connection.login(getUsername(0), getPassword(0), "MyOtherResource");
assertTrue("Failed to use compression", connection.isUsingCompression());
// Executes some server interaction testing the connection
executeSomeServerInteraction(connection);
CountDownLatch latch = new CountDownLatch(1);
XMPPConnectionTestListener listener = new XMPPConnectionTestListener(latch);
connection.addConnectionListener(listener);
// Simulates an error in the connection
connection.notifyConnectionError(new Exception("Simulated Error"));
latch.await(MIN_RECONNECT_WAIT, TimeUnit.SECONDS);
// After 10 seconds, the reconnection manager must reestablishes the connection
assertEquals("The ConnectionListener.connectionEstablished() notification was not fired", true, listener.reconnected);
assertTrue("The ReconnectionManager algorithm has reconnected without waiting at least 5 seconds", listener.attemptsNotifications > 0);
// Executes some server interaction testing the connection
executeSomeServerInteraction(connection);
}
/**
* Tests a manual reconnection.
* Simulates a connection error, disables the reconnection mechanism and then reconnects.
*/
public void testManualReconnectionWithCancelation() throws Exception {
XMPPConnection connection = getConnection(0);
CountDownLatch latch = new CountDownLatch(1);
XMPPConnectionTestListener listener = new XMPPConnectionTestListener(latch);
connection.addConnectionListener(listener);
// Produces a connection error
connection.notifyConnectionError(new Exception("Simulated Error"));
assertEquals(
"An error occurs but the ConnectionListener.connectionClosedOnError(e) was not notified",
true, listener.connectionClosedOnError);
// Thread.sleep(1000);
// Cancels the automatic reconnection
connection.getConfiguration().setReconnectionAllowed(false);
// Waits for a reconnection that must not happened.
Thread.sleep(MIN_RECONNECT_WAIT * 1000);
// Cancels the automatic reconnection
assertEquals(false, listener.reconnected);
// Makes a manual reconnection from an error terminated connection without reconnection
connection.connect();
// Executes some server interaction testing the connection
executeSomeServerInteraction(connection);
}
/**
* Tests a manual reconnection after a login.
* Closes the connection and then reconnects.
*/
public void testCloseAndManualReconnection() throws Exception {
XMPPConnection connection = getConnection(0);
String username = connection.getConfiguration().getUsername();
String password = connection.getConfiguration().getPassword();
XMPPConnectionTestListener listener = new XMPPConnectionTestListener();
connection.addConnectionListener(listener);
// Produces a normal disconnection
connection.disconnect();
assertEquals("ConnectionListener.connectionClosed() was not notified",
true, listener.connectionClosed);
// Waits 10 seconds waiting for a reconnection that must not happened.
Thread.sleep(MIN_RECONNECT_WAIT * 1000);
assertEquals("The connection was stablished but it was not allowed to", false,
listener.reconnected);
// Makes a manual reconnection
connection.connect();
connection.login(username, password);
// Executes some server interaction testing the connection
executeSomeServerInteraction(connection);
}
/**
* Tests a reconnection in a anonymously logged connection.
* Closes the connection and then reconnects.
*/
public void testAnonymousReconnection() throws Exception {
XMPPConnection connection = createConnection();
connection.connect();
XMPPConnectionTestListener listener = new XMPPConnectionTestListener();
connection.addConnectionListener(listener);
// Makes the anounymous login
connection.loginAnonymously();
// Produces a normal disconnection
connection.disconnect();
assertEquals("ConnectionListener.connectionClosed() was not notified",
true, listener.connectionClosed);
// Makes a manual reconnection
connection.connect();
connection.loginAnonymously();
assertEquals("Failed the manual connection", true, connection.isAnonymous());
}
private XMPPConnection createXMPPConnection() throws Exception {
XMPPConnection connection;
// Create the configuration
ConnectionConfiguration config = new ConnectionConfiguration(getHost(), getPort());
config.setCompressionEnabled(Boolean.getBoolean("test.compressionEnabled"));
config.setSASLAuthenticationEnabled(true);
connection = new XMPPConnection(config);
return connection;
}
/**
* Execute some server interaction in order to test that the regenerated connection works fine.
*/
private void executeSomeServerInteraction(XMPPConnection connection) throws XMPPException {
PingManager pingManager = PingManager.getInstanceFor(connection);
pingManager.pingMyServer();
}
protected int getMaxConnections() {
return 1;
}
private class XMPPConnectionTestListener implements ConnectionListener {
// Variables to support listener notifications verification
private volatile boolean connectionClosed = false;
private volatile boolean connectionClosedOnError = false;
private volatile boolean reconnected = false;
private volatile boolean reconnectionFailed = false;
private volatile int remainingSeconds = 0;
private volatile int attemptsNotifications = 0;
private volatile boolean reconnectionCanceled = false;
private CountDownLatch countDownLatch;
private XMPPConnectionTestListener(CountDownLatch latch) {
countDownLatch = latch;
}
private XMPPConnectionTestListener() {
}
/**
* Methods to test the listener.
*/
public void connectionClosed() {
connectionClosed = true;
if (countDownLatch != null)
countDownLatch.countDown();
}
public void connectionClosedOnError(Exception e) {
connectionClosedOnError = true;
}
public void reconnectionCanceled() {
reconnectionCanceled = true;
if (countDownLatch != null)
countDownLatch.countDown();
}
public void reconnectingIn(int seconds) {
attemptsNotifications = attemptsNotifications + 1;
remainingSeconds = seconds;
}
public void reconnectionSuccessful() {
reconnected = true;
if (countDownLatch != null)
countDownLatch.countDown();
}
public void reconnectionFailed(Exception error) {
reconnectionFailed = true;
if (countDownLatch != null)
countDownLatch.countDown();
}
}
}

View file

@ -0,0 +1,48 @@
/**
*
* 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.smack;
/**
* Run all tests defined in RosterTest but initialize the roster before connection is logged in and
* authenticated.
*
* @author Henning Staib
*/
public class RosterInitializedBeforeConnectTest extends RosterSmackTest {
public RosterInitializedBeforeConnectTest(String name) {
super(name);
}
protected boolean createOfflineConnections() {
return true;
}
protected void setUp() throws Exception {
super.setUp();
// initialize all rosters before login
for (int i = 0; i < getMaxConnections(); i++) {
XMPPConnection connection = getConnection(i);
assertFalse(connection.isConnected());
Roster roster = connection.getRoster();
assertNotNull(roster);
connectAndLogin(i);
}
}
}

View file

@ -0,0 +1,206 @@
/**
*
* 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.smack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.test.SmackTestCase;
/**
* Test cases for adding the {@link RosterListener} in different connection states.
*
* @author Henning Staib
*/
public class RosterListenerTest extends SmackTestCase {
public RosterListenerTest(String arg0) {
super(arg0);
}
public void testAddingRosterListenerBeforeConnect() throws Exception {
int inviterIndex = 0;
int inviteeIndex = 1;
XMPPConnection inviterConnection = getConnection(inviterIndex);
connectAndLogin(inviterIndex);
assertTrue("Inviter is not online", inviterConnection.isConnected());
Roster inviterRoster = inviterConnection.getRoster();
// add user1 to roster to create roster events stored at XMPP server
inviterRoster.createEntry(getBareJID(inviteeIndex), getUsername(inviteeIndex), null);
XMPPConnection inviteeConnection = getConnection(inviteeIndex);
assertFalse("Invitee is already online", inviteeConnection.isConnected());
// collector for added entries
final List<String> addedEntries = new ArrayList<String>();
// register roster listener before login
Roster inviteeRoster = inviteeConnection.getRoster();
inviteeRoster.addRosterListener(new RosterListener() {
public void presenceChanged(Presence presence) {
// ignore
}
public void entriesUpdated(Collection<String> addresses) {
// ignore
}
public void entriesDeleted(Collection<String> addresses) {
// ignore
}
public void entriesAdded(Collection<String> addresses) {
addedEntries.addAll(addresses);
}
});
// connect after adding the listener
connectAndLogin(inviteeIndex);
Thread.sleep(5000); // wait for packets to be processed
assertNotNull("inviter is not in roster", inviteeRoster.getEntry(getBareJID(inviterIndex)));
assertTrue("got no event for adding inviter",
addedEntries.contains(getBareJID(inviterIndex)));
}
public void testAddingRosterListenerAfterConnect() throws Exception {
int inviterIndex = 0;
int inviteeIndex = 1;
XMPPConnection inviterConnection = getConnection(inviterIndex);
connectAndLogin(inviterIndex);
assertTrue("Inviter is not online", inviterConnection.isConnected());
Roster inviterRoster = inviterConnection.getRoster();
// add user1 to roster to create roster events stored at XMPP server
inviterRoster.createEntry(getBareJID(inviteeIndex), getUsername(inviteeIndex), null);
Thread.sleep(500); // wait for XMPP server
XMPPConnection inviteeConnection = getConnection(inviteeIndex);
connectAndLogin(inviteeIndex);
assertTrue("Invitee is not online", inviteeConnection.isConnected());
// collector for added entries
final List<String> addedEntries = new ArrayList<String>();
// wait to simulate concurrency before adding listener
Thread.sleep(200);
// register roster listener after login
Roster inviteeRoster = inviteeConnection.getRoster();
inviteeRoster.addRosterListener(new RosterListener() {
public void presenceChanged(Presence presence) {
// ignore
}
public void entriesUpdated(Collection<String> addresses) {
// ignore
}
public void entriesDeleted(Collection<String> addresses) {
// ignore
}
public void entriesAdded(Collection<String> addresses) {
addedEntries.addAll(addresses);
}
});
Thread.sleep(500); // wait for packets to be processed
assertNotNull("Inviter is not in roster", inviteeRoster.getEntry(getBareJID(inviterIndex)));
assertFalse("got event for adding inviter", addedEntries.contains(getBareJID(inviterIndex)));
}
@Override
protected void tearDown() throws Exception {
cleanUpRoster();
super.tearDown();
}
protected int getMaxConnections() {
return 2;
}
protected boolean createOfflineConnections() {
return true;
}
/**
* Clean up all the entries in the roster
*/
private void cleanUpRoster() {
for (int i = 0; i < getMaxConnections(); i++) {
// Delete all the entries from the roster
Roster roster = getConnection(i).getRoster();
for (RosterEntry entry : roster.getEntries()) {
try {
roster.removeEntry(entry);
Thread.sleep(100);
}
catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
catch (InterruptedException e) {
// ignore
}
}
try {
Thread.sleep(700);
}
catch (InterruptedException e) {
fail(e.getMessage());
}
}
// Wait up to 6 seconds to receive roster removal notifications
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 6000
&& (getConnection(0).getRoster().getEntryCount() != 0 || getConnection(1).getRoster().getEntryCount() != 0)) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
}
}
assertEquals("Wrong number of entries in connection 0", 0,
getConnection(0).getRoster().getEntryCount());
assertEquals("Wrong number of groups in connection 0", 0,
getConnection(0).getRoster().getGroupCount());
assertEquals("Wrong number of entries in connection 1", 0,
getConnection(1).getRoster().getEntryCount());
assertEquals("Wrong number of groups in connection 1", 0,
getConnection(1).getRoster().getGroupCount());
}
}

View file

@ -0,0 +1,710 @@
/**
*
* Copyright 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.smack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.util.StringUtils;
import org.mockito.internal.util.RemoveFirstLine;
/**
* Tests the Roster functionality by creating and removing roster entries.
*
* @author Gaston Dombiak
*/
public class RosterSmackTest extends SmackTestCase {
/**
* Constructor for RosterSmackTest.
* @param name
*/
public RosterSmackTest(String name) {
super(name);
}
/**
* 1. Create entries in roster groups
* 2. Iterate on the groups and remove the entry from each group
* 3. Check that the entries are kept as unfiled entries
*/
public void testDeleteAllRosterGroupEntries() {
try {
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
CountDownLatch latch = new CountDownLatch(2);
setupCountdown(latch, roster);
roster.createEntry(getBareJID(1), "gato11", new String[] { "Friends", "Family" });
roster.createEntry(getBareJID(2), "gato12", new String[] { "Family" });
waitForCountdown(latch, roster, 2);
final CountDownLatch removeLatch = new CountDownLatch(3);
RosterListener latchCounter = new RosterListener() {
@Override
public void presenceChanged(Presence presence) {}
@Override
public void entriesUpdated(Collection<String> addresses) {
removeLatch.countDown();
}
@Override
public void entriesDeleted(Collection<String> addresses) {}
@Override
public void entriesAdded(Collection<String> addresses) {}
};
roster.addRosterListener(latchCounter);
for (RosterEntry entry : roster.getEntries()) {
for (RosterGroup rosterGroup : entry.getGroups()) {
rosterGroup.removeEntry(entry);
}
}
removeLatch.await(5, TimeUnit.SECONDS);
roster.removeRosterListener(latchCounter);
assertEquals("The number of entries in connection 1 should be 1", 1, getConnection(1).getRoster().getEntryCount());
assertEquals("The number of groups in connection 1 should be 0", 0, getConnection(1).getRoster().getGroupCount());
assertEquals("The number of entries in connection 2 should be 1", 1, getConnection(2).getRoster().getEntryCount());
assertEquals("The number of groups in connection 2 should be 0", 0, getConnection(2).getRoster().getGroupCount());
assertEquals("The number of entries in connection 0 should be 2", 2, roster.getEntryCount());
assertEquals("The number of groups in connection 0 should be 0", 0, roster.getGroupCount());
}
catch (Exception e) {
fail(e.getMessage());
}
}
private void setupCountdown(final CountDownLatch latch, Roster roster) {
roster.addRosterListener(new RosterListener() {
@Override
public void presenceChanged(Presence presence) {}
@Override
public void entriesUpdated(Collection<String> addresses) {
latch.countDown();
}
@Override
public void entriesDeleted(Collection<String> addresses) {}
@Override
public void entriesAdded(Collection<String> addresses) {}
});
}
private void waitForCountdown(CountDownLatch latch, Roster roster, int entryCount) throws InterruptedException {
latch.await(5, TimeUnit.SECONDS);
assertEquals(entryCount, roster.getEntryCount());
}
/**
* 1. Create entries in roster groups
* 2. Iterate on all the entries and remove them from the roster
* 3. Check that the number of entries and groups is zero
*/
public void testDeleteAllRosterEntries() throws Exception {
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
CountDownLatch latch = new CountDownLatch(2);
setupCountdown(latch, roster);
roster.createEntry(getBareJID(1), "gato11", new String[] { "Friends" });
roster.createEntry(getBareJID(2), "gato12", new String[] { "Family" });
waitForCountdown(latch, roster, 2);
CountDownLatch removeLatch = new CountDownLatch(2);
RosterListener latchCounter = new RemovalListener(removeLatch);
roster.addRosterListener(latchCounter);
for (RosterEntry entry : roster.getEntries()) {
roster.removeEntry(entry);
}
removeLatch.await(5, TimeUnit.SECONDS);
roster.removeRosterListener(latchCounter);
assertEquals("Wrong number of entries in connection 0", 0, roster.getEntryCount());
assertEquals("Wrong number of groups in connection 0", 0, roster.getGroupCount());
assertEquals("Wrong number of entries in connection 1", 0, getConnection(1).getRoster().getEntryCount());
assertEquals("Wrong number of groups in connection 1", 0, getConnection(1).getRoster().getGroupCount());
}
/**
* 1. Create unfiled entries
* 2. Iterate on all the entries and remove them from the roster
* 3. Check that the number of entries and groups is zero
*/
public void testDeleteAllUnfiledRosterEntries() {
try {
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
CountDownLatch latch = new CountDownLatch(2);
setupCountdown(latch, roster);
roster.createEntry(getBareJID(1), "gato11", null);
roster.createEntry(getBareJID(2), "gato12", null);
waitForCountdown(latch, roster, 2);
CountDownLatch removeLatch = new CountDownLatch(2);
RosterListener latchCounter = new RemovalListener(removeLatch);
roster.addRosterListener(latchCounter);
for (RosterEntry entry : roster.getEntries()) {
roster.removeEntry(entry);
}
removeLatch.await(5, TimeUnit.SECONDS);
roster.removeRosterListener(latchCounter);
assertEquals("Wrong number of entries in connection 0", 0, roster.getEntryCount());
assertEquals("Wrong number of groups in connection 0", 0, roster.getGroupCount());
assertEquals("Wrong number of entries in connection 1", 0, getConnection(1).getRoster().getEntryCount());
assertEquals("Wrong number of groups in connection 1", 0, getConnection(1).getRoster().getGroupCount());
}
catch (Exception e) {
fail(e.getMessage());
}
}
/**
* 1. Create an unfiled entry
* 2. Change its name
* 3. Check that the name has been modified
* 4. Reload the whole roster
* 5. Check that the name has been modified
*/
public void testChangeNameToUnfiledEntry() {
try {
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
CountDownLatch latch = new CountDownLatch(1);
setupCountdown(latch, roster);
roster.createEntry(getBareJID(1), null, null);
waitForCountdown(latch, roster, 1);
final CountDownLatch updateLatch = new CountDownLatch(2);
RosterListener latchCounter = new RosterListener() {
@Override
public void entriesAdded(Collection<String> addresses) {}
@Override
public void entriesUpdated(Collection<String> addresses) {
updateLatch.countDown();
}
@Override
public void entriesDeleted(Collection<String> addresses) {}
@Override
public void presenceChanged(Presence presence) {}
};
roster.addRosterListener(latchCounter);
// Change the roster entry name and check if the change was made
for (RosterEntry entry : roster.getEntries()) {
entry.setName("gato11");
assertEquals("gato11", entry.getName());
}
// Reload the roster and check the name again
roster.reload();
updateLatch.await(5, TimeUnit.SECONDS);
for (RosterEntry entry : roster.getEntries()) {
assertEquals("gato11", entry.getName());
}
}
catch (Exception e) {
fail(e.getMessage());
}
}
/**
* 1. Create an unfiled entry with no name
* 2. Check that the the entry does not belong to any group
* 3. Change its name and add it to a group
* 4. Check that the name has been modified and that the entry belongs to a group
*/
public void testChangeGroupAndNameToUnfiledEntry() {
try {
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
roster.createEntry(getBareJID(1), null, null);
Thread.sleep(500);
getConnection(1).getRoster().createEntry(getBareJID(0), null, null);
// Wait up to 5 seconds to receive presences of the new roster contacts
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 5000 &&
!roster.getPresence(getBareJID(0)).isAvailable()) {
Thread.sleep(100);
}
//assertNotNull("Presence not received", roster.getPresence(getBareJID(0)));
for (RosterEntry entry : roster.getEntries()) {
assertFalse("The roster entry belongs to a group", !entry.getGroups().isEmpty());
}
// Change the roster entry name and check if the change was made
roster.createEntry(getBareJID(1), "NewName", new String[] { "Friends" });
// Reload the roster and check the name again
Thread.sleep(200);
for (RosterEntry entry : roster.getEntries()) {
assertEquals("Name of roster entry is wrong", "NewName", entry.getName());
assertTrue("The roster entry does not belong to any group", !entry.getGroups().isEmpty());
}
// Wait up to 5 seconds to receive presences of the new roster contacts
initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 5000 &&
!roster.getPresence(getBareJID(1)).isAvailable()) {
Thread.sleep(100);
}
assertTrue("Presence not received", roster.getPresence(getBareJID(1)).isAvailable());
} catch (Exception e) {
fail(e.getMessage());
}
}
/**
* Tests that adding an existing roster entry that belongs to a group to another group
* works fine.
*/
public void testAddEntryToNewGroup() {
try {
Thread.sleep(500);
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
roster.createEntry(getBareJID(1), "gato11", new String[] { "Friends" });
roster.createEntry(getBareJID(2), "gato12", new String[] { "Family" });
// Wait up to 2 seconds to receive new roster contacts
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && roster.getEntryCount() != 2) {
Thread.sleep(100);
}
assertEquals("Wrong number of entries in connection 0", 2, roster.getEntryCount());
// Add "gato11" to a new group called NewGroup
roster.createGroup("NewGroup").addEntry(roster.getEntry(getBareJID(1)));
// Log in from another resource so we can test the roster
XMPPConnection con2 = createConnection();
con2.connect();
con2.login(getUsername(0), getUsername(0), "MyNewResource");
Roster roster2 = con2.getRoster();
assertEquals("Wrong number of entries in new connection", 2, roster2.getEntryCount());
assertEquals("Wrong number of groups in new connection", 3, roster2.getGroupCount());
RosterEntry entry = roster2.getEntry(getBareJID(1));
assertNotNull("No entry for user 1 was found", entry);
List<String> groupNames = new ArrayList<String>();
for (RosterGroup rosterGroup : entry.getGroups()) {
groupNames.add(rosterGroup.getName());
}
assertTrue("Friends group was not found", groupNames.contains("Friends"));
assertTrue("NewGroup group was not found", groupNames.contains("NewGroup"));
// Close the new connection
con2.disconnect();
Thread.sleep(500);
}
catch (Exception e) {
fail(e.getMessage());
}
}
/**
* Test if renaming a roster group works fine.
*
*/
public void testRenameRosterGroup() {
try {
Thread.sleep(200);
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
roster.createEntry(getBareJID(1), "gato11", new String[] { "Friends" });
roster.createEntry(getBareJID(2), "gato12", new String[] { "Friends" });
// Wait up to 2 seconds to let the server process presence subscriptions
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && (
!roster.getPresence(getBareJID(1)).isAvailable() ||
!roster.getPresence(getBareJID(2)).isAvailable())) {
Thread.sleep(100);
}
roster.getGroup("Friends").setName("Amigos");
// Wait up to 2 seconds
initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
(roster.getGroup("Friends") != null)) {
Thread.sleep(100);
}
assertNull("The group Friends still exists", roster.getGroup("Friends"));
assertNotNull("The group Amigos does not exist", roster.getGroup("Amigos"));
assertEquals(
"Wrong number of entries in the group Amigos",
2,
roster.getGroup("Amigos").getEntryCount());
// Setting the name to empty is like removing this group
roster.getGroup("Amigos").setName("");
// Wait up to 2 seconds for the group to change its name
initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
(roster.getGroup("Amigos") != null)) {
Thread.sleep(100);
}
assertNull("The group Amigos still exists", roster.getGroup("Amigos"));
assertNull("The group with no name does exist", roster.getGroup(""));
assertEquals("There are still groups in the roster", 0, roster.getGroupCount());
assertEquals(
"Wrong number of unfiled entries",
2,
roster.getUnfiledEntryCount());
Thread.sleep(200);
}
catch (Exception e) {
fail(e.getMessage());
}
}
/**
* Test presence management.<p>
*
* 1. Log in user0 from a client and user1 from 2 clients
* 2. Create presence subscription of type BOTH between 2 users
* 3. Check that presence is correctly delivered to both users
* 4. User1 logs out from a client
* 5. Check that presence for each connected resource is correct
*/
public void testRosterPresences() throws Exception {
Presence presence;
// Create another connection for the same user of connection 1
ConnectionConfiguration connectionConfiguration =
new ConnectionConfiguration(getHost(), getPort(), getServiceName());
XMPPConnection conn4 = new XMPPConnection(connectionConfiguration);
conn4.connect();
conn4.login(getUsername(1), getPassword(1), "Home");
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
roster.createEntry(getBareJID(1), "gato11", null);
// Wait up to 2 seconds
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
(roster.getPresence(getBareJID(1)).getType() == Presence.Type.unavailable)) {
Thread.sleep(100);
}
// Check that a presence is returned for a user
presence = roster.getPresence(getBareJID(1));
assertTrue("Returned a null Presence for an existing user", presence.isAvailable());
// Check that the right presence is returned for a user+resource
presence = roster.getPresenceResource(getUsername(1) + "@" + conn4.getServiceName() + "/Home");
assertEquals("Returned the wrong Presence", "Home",
StringUtils.parseResource(presence.getFrom()));
// Check that the right presence is returned for a user+resource
presence = roster.getPresenceResource(getFullJID(1));
assertTrue("Presence not found for user " + getFullJID(1), presence.isAvailable());
assertEquals("Returned the wrong Presence", "Smack",
StringUtils.parseResource(presence.getFrom()));
// Check the returned presence for a non-existent user+resource
presence = roster.getPresenceResource("noname@" + getServiceName() + "/Smack");
assertFalse("Available presence was returned for a non-existing user", presence.isAvailable());
assertEquals("Returned Presence for a non-existing user has the incorrect type",
Presence.Type.unavailable, presence.getType());
// Check that the returned presences are correct
Iterator<Presence> presences = roster.getPresences(getBareJID(1));
int count = 0;
while (presences.hasNext()) {
count++;
presences.next();
}
assertEquals("Wrong number of returned presences", count, 2);
// Close the connection so one presence must go
conn4.disconnect();
// Check that the returned presences are correct
presences = roster.getPresences(getBareJID(1));
count = 0;
while (presences.hasNext()) {
count++;
presences.next();
}
assertEquals("Wrong number of returned presences", count, 1);
}
/**
* User1 is connected from 2 resources. User1 adds User0 to his roster. Ensure
* that both resources of user1 get the available presence of User0. Remove User0
* from User1's roster and check presences again.
*/
public void testMultipleResources() throws Exception {
// Create another connection for the same user of connection 1
ConnectionConfiguration connectionConfiguration =
new ConnectionConfiguration(getHost(), getPort(), getServiceName());
XMPPConnection conn4 = new XMPPConnection(connectionConfiguration);
conn4.connect();
conn4.login(getUsername(1), getPassword(1), "Home");
// Add a new roster entry
Roster roster = conn4.getRoster();
roster.createEntry(getBareJID(0), "gato11", null);
// Wait up to 2 seconds
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && (
!roster.getPresence(getBareJID(0)).isAvailable() ||
!getConnection(1).getRoster().getPresence(getBareJID(0)).isAvailable())) {
Thread.sleep(100);
}
// Check that a presence is returned for the new contact
Presence presence = roster.getPresence(getBareJID(0));
assertTrue("Returned a null Presence for an existing user", presence.isAvailable());
// Check that a presence is returned for the new contact
presence = getConnection(1).getRoster().getPresence(getBareJID(0));
assertTrue("Returned a null Presence for an existing user", presence.isAvailable());
// Delete user from roster
roster.removeEntry(roster.getEntry(getBareJID(0)));
// Wait up to 2 seconds
initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && (
roster.getPresence(getBareJID(0)).getType() != Presence.Type.unavailable ||
getConnection(1).getRoster().getPresence(getBareJID(0)).getType() !=
Presence.Type.unavailable)) {
Thread.sleep(100);
}
// Check that no presence is returned for the removed contact
presence = roster.getPresence(getBareJID(0));
assertFalse("Available presence was returned for removed contact", presence.isAvailable());
assertEquals("Returned Presence for removed contact has incorrect type",
Presence.Type.unavailable, presence.getType());
// Check that no presence is returned for the removed contact
presence = getConnection(1).getRoster().getPresence(getBareJID(0));
assertFalse("Available presence was returned for removed contact", presence.isAvailable());
assertEquals("Returned Presence for removed contact has incorrect type",
Presence.Type.unavailable, presence.getType());
}
/**
* Tests that the server and Smack are able to handle nicknames that include
* < > characters.
*/
public void testNotCommonNickname() throws Exception {
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
roster.createEntry(getBareJID(1), "Thiago <12001200>", null);
Thread.sleep(500);
assertEquals("Created entry was never received", 1, roster.getEntryCount());
// Create another connection for the same user of connection 0
ConnectionConfiguration connectionConfiguration =
new ConnectionConfiguration(getHost(), getPort(), getServiceName());
XMPPConnection conn2 = new XMPPConnection(connectionConfiguration);
conn2.connect();
conn2.login(getUsername(0), getPassword(0), "Home");
// Retrieve roster and verify that new contact is there and nickname is correct
Roster roster2 = conn2.getRoster();
assertEquals("Created entry was never received", 1, roster2.getEntryCount());
RosterEntry entry = roster2.getEntry(getBareJID(1));
assertNotNull("New entry was not returned from the server", entry);
assertEquals("Roster item name is incorrect", "Thiago <12001200>", entry.getName());
}
/**
* Clean up all the entries in the roster
*/
private void cleanUpRoster() {
for (int i=0; i<getMaxConnections(); i++) {
// Delete all the entries from the roster
Roster roster = getConnection(i).getRoster();
final CountDownLatch removalLatch = new CountDownLatch(roster.getEntryCount());
roster.addRosterListener(new RosterListener() {
@Override
public void presenceChanged(Presence presence) {}
@Override
public void entriesUpdated(Collection<String> addresses) {}
@Override
public void entriesDeleted(Collection<String> addresses) {
removalLatch.countDown();
}
@Override
public void entriesAdded(Collection<String> addresses) {}
});
for (RosterEntry entry : roster.getEntries()) {
try {
roster.removeEntry(entry);
}
catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
try {
removalLatch.await(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
fail(e.getMessage());
}
}
assertEquals("Wrong number of entries in connection 0", 0, getConnection(0).getRoster().getEntryCount());
assertEquals("Wrong number of entries in connection 1", 0, getConnection(1).getRoster().getEntryCount());
assertEquals("Wrong number of entries in connection 2", 0, getConnection(2).getRoster().getEntryCount());
}
/**
* Tests the creation of a roster and then simulates abrupt termination. Cached presences
* must go offline. At reconnection, presences must go back to online.
* <ol>
* <li> Create some entries
* <li> Breack the connection
* <li> Check offline presences
* <li> Whait for automatic reconnection
* <li> Check online presences
* </ol>
*/
public void testOfflinePresencesAfterDisconnection() throws Exception {
// Add a new roster entry
Roster roster = getConnection(0).getRoster();
roster.createEntry(getBareJID(1), "gato11", null);
roster.createEntry(getBareJID(2), "gato12", null);
// Wait up to 2 seconds to let the server process presence subscriptions
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && (
!roster.getPresence(getBareJID(1)).isAvailable() ||
!roster.getPresence(getBareJID(2)).isAvailable())) {
Thread.sleep(100);
}
Thread.sleep(200);
// Break the connection
getConnection(0).notifyConnectionError(new Exception("Simulated Error"));
Presence presence = roster.getPresence(getBareJID(1));
assertFalse("Unavailable presence not found for offline user", presence.isAvailable());
assertEquals("Unavailable presence not found for offline user", Presence.Type.unavailable,
presence.getType());
// Reconnection should occur in 10 seconds
Thread.sleep(12200);
presence = roster.getPresence(getBareJID(1));
assertTrue("Presence not found for user", presence.isAvailable());
assertEquals("Presence should be online after a connection reconnection",
Presence.Type.available, presence.getType());
}
protected int getMaxConnections() {
return 3;
}
protected void setUp() throws Exception {
super.setUp();
cleanUpRoster();
}
@Override
protected void tearDown() throws Exception {
cleanUpRoster();
super.tearDown();
}
private class RemovalListener implements RosterListener {
private CountDownLatch latch;
private RemovalListener(CountDownLatch removalLatch) {
latch = removalLatch;
}
@Override
public void presenceChanged(Presence presence) {}
@Override
public void entriesUpdated(Collection<String> addresses) {}
@Override
public void entriesDeleted(Collection<String> addresses) {
latch.countDown();
}
@Override
public void entriesAdded(Collection<String> addresses) {}
};
}

View file

@ -0,0 +1,64 @@
/**
*
* Copyright 2003 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.smack.filter;
import junit.framework.TestCase;
import org.jivesoftware.smack.packet.*;
/**
* A test case for the AndFilter class.
*/
public class AndFilterTest extends TestCase {
public void testNullArgs() {
PacketFilter filter = null;
try {
new AndFilter(filter, filter);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException e) {
assertTrue(true);
}
}
public void testAccept() {
MockPacketFilter trueFilter = new MockPacketFilter(true);
MockPacketFilter falseFilter = new MockPacketFilter(false);
MockPacket packet = new MockPacket();
AndFilter andFilter = new AndFilter(trueFilter, trueFilter);
assertTrue(andFilter.accept(packet));
andFilter = new AndFilter(trueFilter, falseFilter);
assertFalse(andFilter.accept(packet));
andFilter = new AndFilter(falseFilter, trueFilter);
assertFalse(andFilter.accept(packet));
andFilter = new AndFilter(falseFilter, falseFilter);
assertFalse(andFilter.accept(packet));
andFilter = new AndFilter();
andFilter.addFilter(trueFilter);
andFilter.addFilter(trueFilter);
andFilter.addFilter(falseFilter);
andFilter.addFilter(trueFilter);
assertFalse(andFilter.accept(packet));
}
}

View file

@ -0,0 +1,69 @@
/**
*
* Copyright 2003 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.smack.filter;
import junit.framework.TestCase;
import org.jivesoftware.smack.packet.*;
/**
* A test case for the FromContainsFilter class.
*/
public class FromContainsFilterTest extends TestCase {
public void testNullArgs() {
try {
new FromContainsFilter(null);
fail("Parameter can not be null");
}
catch (IllegalArgumentException e) {
assertTrue(true);
}
}
public void testAccept() {
MockFromPacket packet = new MockFromPacket("foo@bar.com");
FromContainsFilter fromContainsFilter = new FromContainsFilter("");
assertTrue(fromContainsFilter.accept(packet));
fromContainsFilter = new FromContainsFilter("foo");
assertTrue(fromContainsFilter.accept(packet));
fromContainsFilter = new FromContainsFilter("foo@bar.com");
assertTrue(fromContainsFilter.accept(packet));
fromContainsFilter = new FromContainsFilter("bar@foo.com");
assertFalse(fromContainsFilter.accept(packet));
fromContainsFilter = new FromContainsFilter("blah-stuff,net");
assertFalse(fromContainsFilter.accept(packet));
}
/**
* Wraps the MockPacket class to always give an expected From field.
*/
private class MockFromPacket extends MockPacket {
private String from;
public MockFromPacket(String from) {
this.from = from;
}
public String getFrom() {
return from;
}
}
}

View file

@ -0,0 +1,51 @@
/**
*
* Copyright 2003 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.smack.filter;
import junit.framework.TestCase;
import org.jivesoftware.smack.packet.*;
/**
* A test case for the NotFilter class.
*/
public class NotFilterTest extends TestCase {
public void testNullArgs() {
PacketFilter filter = null;
try {
NotFilter or = new NotFilter(filter);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException e) {
assertTrue(true);
}
}
public void testAccept() {
MockPacketFilter trueFilter = new MockPacketFilter(true);
MockPacketFilter falseFilter = new MockPacketFilter(false);
MockPacket packet = new MockPacket();
NotFilter NotFilter = new NotFilter(trueFilter);
assertFalse(NotFilter.accept(packet));
NotFilter = new NotFilter(falseFilter);
assertTrue(NotFilter.accept(packet));
}
}

View file

@ -0,0 +1,98 @@
/**
*
* Copyright 2003 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.smack.filter;
import junit.framework.TestCase;
import org.jivesoftware.smack.packet.*;
/**
* A test case for the OrFilter class.
*/
public class OrFilterTest extends TestCase {
public void testNullArgs() {
PacketFilter filter = null;
try {
OrFilter or = new OrFilter(filter, filter);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException e) {
assertTrue(true);
}
}
public void testAccept() {
MockPacketFilter trueFilter = new MockPacketFilter(true);
MockPacketFilter falseFilter = new MockPacketFilter(false);
MockPacket packet = new MockPacket();
// Testing TT == T
OrFilter orFilter = new OrFilter(trueFilter, trueFilter);
assertTrue(orFilter.accept(packet));
// Testing TF = F
orFilter = new OrFilter(trueFilter, falseFilter);
assertTrue(orFilter.accept(packet));
// Testing FT = F
orFilter = new OrFilter(falseFilter, trueFilter);
assertTrue(orFilter.accept(packet));
// Testing FF = F
orFilter = new OrFilter(falseFilter, falseFilter);
assertFalse(orFilter.accept(packet));
// Testing TTTT = T
orFilter = new OrFilter(
new OrFilter(trueFilter, trueFilter), new OrFilter(trueFilter, trueFilter)
);
assertTrue(orFilter.accept(packet));
// Testing TFTT = F
orFilter = new OrFilter(
new OrFilter(trueFilter, falseFilter), new OrFilter(trueFilter, trueFilter)
);
assertTrue(orFilter.accept(packet));
// Testing TTFT = F
orFilter = new OrFilter(
new OrFilter(trueFilter, trueFilter), new OrFilter(falseFilter, trueFilter)
);
assertTrue(orFilter.accept(packet));
// Testing TTTF = F
orFilter = new OrFilter(
new OrFilter(trueFilter, trueFilter), new OrFilter(trueFilter, falseFilter)
);
assertTrue(orFilter.accept(packet));
// Testing FFFF = F
orFilter = new OrFilter(
new OrFilter(falseFilter, falseFilter), new OrFilter(falseFilter, falseFilter)
);
assertFalse(orFilter.accept(packet));
orFilter = new OrFilter();
orFilter.addFilter(trueFilter);
orFilter.addFilter(trueFilter);
orFilter.addFilter(falseFilter);
orFilter.addFilter(trueFilter);
assertTrue(orFilter.accept(packet));
}
}

View file

@ -0,0 +1,63 @@
/**
*
* Copyright 2003 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.smack.filter;
import junit.framework.TestCase;
import org.jivesoftware.smack.packet.*;
/**
* A test case for the PacketIDFilter class.
*/
public class PacketIDFilterTest extends TestCase {
public void testNullArgs() {
try {
new PacketIDFilter(null);
fail("Parameter can not be null");
}
catch (IllegalArgumentException e) {
assertTrue(true);
}
}
public void testAccept() {
MockIDPacket packet = new MockIDPacket("foo");
PacketIDFilter packetIDFilter = new PacketIDFilter("");
assertFalse(packetIDFilter.accept(packet));
packetIDFilter = new PacketIDFilter("foo");
assertTrue(packetIDFilter.accept(packet));
packetIDFilter = new PacketIDFilter("fOO");
assertFalse(packetIDFilter.accept(packet));
}
/**
* Wraps the MockPacket class to always give an expected packet ID field.
*/
private class MockIDPacket extends MockPacket {
private String id;
public MockIDPacket(String id) {
this.id = id;
}
public String getPacketID() {
return id;
}
}
}

View file

@ -0,0 +1,111 @@
/**
*
* Copyright 2003 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.smack.filter;
import junit.framework.TestCase;
import org.jivesoftware.smack.packet.*;
/**
* Test cases for the PacketTypeFilter class.
*/
public class PacketTypeFilterTest extends TestCase {
private class InnerClassDummy {
public class DummyPacket extends Packet {
public String toXML() {
return null;
}
}
public DummyPacket getInnerInstance() {
return new DummyPacket();
}
}
private static class StaticInnerClassDummy {
public static class StaticDummyPacket extends Packet {
public String toXML() {
return null;
}
}
public static StaticDummyPacket getInnerInstance() {
return new StaticDummyPacket();
}
}
/**
* Test case for the constructor of PacketTypeFilter objects.
*/
public void testConstructor() {
// We dont need to test this since PacketTypeFilter(Class<? extends Packet> packetType) only excepts Packets
// Test a class that is not a subclass of Packet
// try {
// new PacketTypeFilter(Dummy.class);
// fail("Parameter must be a subclass of Packet.");
// }
// catch (IllegalArgumentException e) {}
// Test a class that is a subclass of Packet
try {
new PacketTypeFilter(MockPacket.class);
}
catch (IllegalArgumentException e) {
fail();
}
// Test another class which is a subclass of Packet
try {
new PacketTypeFilter(IQ.class);
}
catch (IllegalArgumentException e) {
fail();
}
// Test an internal class which is a subclass of Packet
try {
new PacketTypeFilter(InnerClassDummy.DummyPacket.class);
}
catch (IllegalArgumentException e) {
fail();
}
// Test an internal static class which is a static subclass of Packet
try {
new PacketTypeFilter(StaticInnerClassDummy.StaticDummyPacket.class);
}
catch (IllegalArgumentException e) {
fail();
}
}
/**
* Test case to test the accept() method of PacketTypeFilter objects.
*/
public void testAccept() {
Packet packet = new MockPacket();
PacketTypeFilter filter = new PacketTypeFilter(MockPacket.class);
assertTrue(filter.accept(packet));
packet = (new InnerClassDummy()).getInnerInstance();
filter = new PacketTypeFilter(InnerClassDummy.DummyPacket.class);
assertTrue(filter.accept(packet));
packet = StaticInnerClassDummy.getInnerInstance();
filter = new PacketTypeFilter(StaticInnerClassDummy.StaticDummyPacket.class);
assertTrue(filter.accept(packet));
}
}

View file

@ -0,0 +1,69 @@
/**
*
* Copyright 2003 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.smack.filter;
import junit.framework.TestCase;
import org.jivesoftware.smack.packet.*;
/**
* A test case for the ToContainsFilter class.
*/
public class ToContainsFilterTest extends TestCase {
public void testNullArgs() {
try {
new ToContainsFilter(null);
fail("Parameter can not be null");
}
catch (IllegalArgumentException e) {
assertTrue(true);
}
}
public void testAccept() {
MockToPacket packet = new MockToPacket("foo@bar.com");
ToContainsFilter toContainsFilter = new ToContainsFilter("");
assertTrue(toContainsFilter.accept(packet));
toContainsFilter = new ToContainsFilter("foo");
assertTrue(toContainsFilter.accept(packet));
toContainsFilter = new ToContainsFilter("foo@bar.com");
assertTrue(toContainsFilter.accept(packet));
toContainsFilter = new ToContainsFilter("bar@foo.com");
assertFalse(toContainsFilter.accept(packet));
toContainsFilter = new ToContainsFilter("blah-stuff,net");
assertFalse(toContainsFilter.accept(packet));
}
/**
* Wraps the MockPacket class to always give an expected To field.
*/
private class MockToPacket extends MockPacket {
private String to;
public MockToPacket(String to) {
this.to = to;
}
public String getTo() {
return to;
}
}
}

View file

@ -0,0 +1,32 @@
/**
*
* Copyright 2003 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.smack.packet;
/**
* A mock implementation of the Packet abstract class. Implements toXML() by returning null.
*/
public class MockPacket extends Packet {
/**
* Returns null always.
* @return null
*/
public String toXML() {
return null;
}
}

View file

@ -0,0 +1,38 @@
/**
*
* 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.smack.packet;
import org.jivesoftware.smack.filter.PacketFilter;
/**
* A mock implementation of the PacketFilter class. Pass in the value you want the
* accept(..) method to return.
*/
public class MockPacketFilter implements PacketFilter {
private boolean acceptValue;
public MockPacketFilter(boolean acceptValue) {
this.acceptValue = acceptValue;
}
public boolean accept(Packet packet) {
return acceptValue;
}
}

View file

@ -0,0 +1,384 @@
/**
*
* 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.smack.packet;
import org.jivesoftware.smack.provider.PrivacyProvider;
import org.jivesoftware.smack.test.SmackTestCase;
import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.StringReader;
/**
* Test the PrivacyProvider class with valids privacy xmls
*
* @author Francisco Vives
*/
public class PrivacyProviderTest extends SmackTestCase {
/**
* Constructor for PrivacyTest.
* @param arg0
*/
public PrivacyProviderTest(String arg0) {
super(arg0);
}
public static void main(String args[]) {
try {
new PrivacyProviderTest(null).testFull();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* Check the parser with an xml with all kind of stanzas.
* To create the xml string based from an xml file, replace:\n with: "\n + "
*/
public void testFull() {
// Make the XML to test
String xml = ""
+ " <iq type='result' id='getlist2' to='romeo@example.net/orchard'> "
+ " <query xmlns='jabber:iq:privacy'> "
+ " <active name='testFilter'/> "
+ " <default name='testSubscription'/> "
+ " <list name='testFilter'> "
+ " <item type='jid' "
+ " value='tybalt@example.com' "
+ " action='deny' "
+ " order='1'/> "
+ " <item action='allow' order='2'> "
+ " <message/> "
+ " <presence-in/> "
+ " <presence-out/> "
+ " <iq/> "
+ " </item> "
+ " </list> "
+ " <list name='testSubscription'> "
+ " <item type='subscription' "
+ " value='both' "
+ " action='allow' "
+ " order='10'/> "
+ " <item type='subscription' "
+ " value='to' "
+ " action='allow' "
+ " order='11'/> "
+ " <item type='subscription' "
+ " value='from' "
+ " action='allow' "
+ " order='12'/> "
+ " <item type='subscription' "
+ " value='none' "
+ " action='deny' "
+ " order='5'> "
+ " <message/> "
+ " </item> "
+ " <item action='deny' order='15'/> "
+ " </list> "
+ " <list name='testJID'> "
+ " <item type='jid' "
+ " value='juliet@example.com' "
+ " action='allow' "
+ " order='6'/> "
+ " <item type='jid' "
+ " value='benvolio@example.org/palm' "
+ " action='deny' "
+ " order='7'/> "
+ " <item type='jid' "
+ " action='allow' "
+ " order='42'/> "
+ " <item action='deny' order='666'/> "
+ " </list> "
+ " <list name='testGroup'> "
+ " <item type='group' "
+ " value='Enemies' "
+ " action='deny' "
+ " order='4'> "
+ " <message/> "
+ " </item> "
+ " <item action='deny' order='666'/> "
+ " </list> "
+ " <list name='testEmpty'/> "
+ " </query> "
+ " <error type='cancel'> "
+ " <item-not-found "
+ " xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/> "
+ " </error> "
+ "</iq> ";
try {
// Create the xml parser
XmlPullParser parser = getParserFromXML(xml);
// Create a packet from the xml
Privacy packet = (Privacy) (new PrivacyProvider()).parseIQ(parser);
// check if it exist
assertNotNull(packet);
// assertEquals(xml, packet.getChildElementXML());
// check the default and active names
assertEquals("testFilter", packet.getActiveName());
assertEquals("testSubscription", packet.getDefaultName());
// check the list
assertEquals(2, packet.getPrivacyList("testFilter").size());
assertEquals(5, packet.getPrivacyList("testSubscription").size());
assertEquals(4, packet.getPrivacyList("testJID").size());
assertEquals(2, packet.getPrivacyList("testGroup").size());
assertEquals(0, packet.getPrivacyList("testEmpty").size());
// check each privacy item
PrivacyItem item = packet.getItem("testGroup", 4);
assertEquals("Enemies", item.getValue());
assertEquals(PrivacyItem.Type.group, item.getType());
assertEquals(false, item.isAllow());
assertEquals(true, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(false, item.isFilterEverything());
item = packet.getItem("testFilter", 1);
assertEquals("tybalt@example.com", item.getValue());
assertEquals(PrivacyItem.Type.jid, item.getType());
assertEquals(false, item.isAllow());
assertEquals(false, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(true, item.isFilterEverything());
item = packet.getItem("testFilter", 2);
assertEquals(null, item.getValue());
assertEquals(null, item.getType());
assertEquals(true, item.isAllow());
assertEquals(true, item.isFilterMessage());
assertEquals(true, item.isFilterIQ());
assertEquals(true, item.isFilterPresence_in());
assertEquals(true, item.isFilterPresence_out());
assertEquals(false, item.isFilterEverything());
// TEST THE testSubscription LIST
item = packet.getItem("testSubscription", 10);
assertEquals("both", item.getValue());
assertEquals(PrivacyItem.Type.subscription, item.getType());
assertEquals(true, item.isAllow());
assertEquals(false, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(true, item.isFilterEverything());
item = packet.getItem("testSubscription", 11);
assertEquals("to", item.getValue());
assertEquals(PrivacyItem.Type.subscription, item.getType());
assertEquals(true, item.isAllow());
assertEquals(false, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(true, item.isFilterEverything());
item = packet.getItem("testSubscription", 12);
assertEquals("from", item.getValue());
assertEquals(PrivacyItem.Type.subscription, item.getType());
assertEquals(true, item.isAllow());
assertEquals(false, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(true, item.isFilterEverything());
item = packet.getItem("testSubscription", 5);
assertEquals("none", item.getValue());
assertEquals(PrivacyItem.Type.subscription, item.getType());
assertEquals(false, item.isAllow());
assertEquals(true, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(false, item.isFilterEverything());
item = packet.getItem("testSubscription", 15);
assertEquals(null, item.getValue());
assertEquals(null, item.getType());
assertEquals(false, item.isAllow());
assertEquals(false, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(true, item.isFilterEverything());
// TEST THE testJID LIST
item = packet.getItem("testJID", 6);
assertEquals("juliet@example.com", item.getValue());
assertEquals(PrivacyItem.Type.jid, item.getType());
assertEquals(true, item.isAllow());
assertEquals(false, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(true, item.isFilterEverything());
item = packet.getItem("testJID", 7);
assertEquals("benvolio@example.org/palm", item.getValue());
assertEquals(PrivacyItem.Type.jid, item.getType());
assertEquals(false, item.isAllow());
assertEquals(false, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(true, item.isFilterEverything());
item = packet.getItem("testJID", 42);
assertEquals(null, item.getValue());
assertEquals(PrivacyItem.Type.jid, item.getType());
assertEquals(true, item.isAllow());
assertEquals(false, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(true, item.isFilterEverything());
item = packet.getItem("testJID", 666);
assertEquals(null, item.getValue());
assertEquals(null, item.getType());
assertEquals(false, item.isAllow());
assertEquals(false, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(true, item.isFilterEverything());
// TEST THE testGroup LIST
item = packet.getItem("testGroup", 4);
assertEquals("Enemies", item.getValue());
assertEquals(PrivacyItem.Type.group, item.getType());
assertEquals(false, item.isAllow());
assertEquals(true, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(false, item.isFilterEverything());
item = packet.getItem("testGroup", 666);
assertEquals(null, item.getValue());
assertEquals(null, item.getType());
assertEquals(false, item.isAllow());
assertEquals(false, item.isFilterMessage());
assertEquals(false, item.isFilterIQ());
assertEquals(false, item.isFilterPresence_in());
assertEquals(false, item.isFilterPresence_out());
assertEquals(true, item.isFilterEverything());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check the parser with an xml with empty lists. It includes the active,
* default and special list.
* To create the xml string based from an xml file, replace:\n with: "\n + "
*/
public void testEmptyLists() {
// Make the XML to test
String xml = ""
+ " <iq type='result' id='getlist1' to='romeo@example.net/orchard'> "
+ " <query xmlns='jabber:iq:privacy'> "
+ " <active/> "
+ " <default name='public'/> "
+ " <list name='public'/> "
+ " <list name='private'/> "
+ " <list name='special'/> "
+ " </query> "
+ " </iq> ";
try {
// Create the xml parser
XmlPullParser parser = getParserFromXML(xml);
// Create a packet from the xml
Privacy packet = (Privacy) (new PrivacyProvider()).parseIQ(parser);
assertNotNull(packet);
assertNotNull(packet.getChildElementXML());
assertEquals("public", packet.getDefaultName());
assertEquals(null, packet.getActiveName());
assertEquals(0, packet.getPrivacyList("public").size());
assertEquals(0, packet.getPrivacyList("private").size());
assertEquals(0, packet.getPrivacyList("special").size());
assertEquals(true, packet.isDeclineActiveList());
assertEquals(false, packet.isDeclineDefaultList());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check the parser with an xml with empty lists. It includes the active,
* default and special list.
* To create the xml string based from an xml file, replace:\n with: "\n + "
*/
public void testDeclineLists() {
// Make the XML to test
String xml = ""
+ " <iq type='result' id='getlist1' to='romeo@example.net/orchard'> "
+ " <query xmlns='jabber:iq:privacy'> "
+ " <active/> "
+ " <default/> "
+ " </query> "
+ " </iq> ";
try {
// Create the xml parser
XmlPullParser parser = getParserFromXML(xml);
// Create a packet from the xml
Privacy packet = (Privacy) (new PrivacyProvider()).parseIQ(parser);
assertNotNull(packet);
assertEquals(null, packet.getDefaultName());
assertEquals(null, packet.getActiveName());
assertEquals(true, packet.isDeclineActiveList());
assertEquals(true, packet.isDeclineDefaultList());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private XmlPullParser getParserFromXML(String xml) throws XmlPullParserException {
MXParser parser = new MXParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
parser.setInput(new StringReader(xml));
return parser;
}
protected int getMaxConnections() {
return 0;
}
}

View file

@ -0,0 +1,521 @@
/**
*
* 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.smack.packet;
import org.jivesoftware.smack.PrivacyList;
import org.jivesoftware.smack.PrivacyListListener;
import org.jivesoftware.smack.PrivacyListManager;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.PrivacyItem.PrivacyRule;
import org.jivesoftware.smack.test.SmackTestCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PrivacyTest extends SmackTestCase {
public PrivacyTest(String arg0) {
super(arg0);
}
/**
* Check when a client set a new active list.
*/
public void testCreateActiveList() {
try {
String listName = "testCreateActiveList";
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(getConnection(0));
PrivacyClient client = new PrivacyClient(privacyManager);
privacyManager.addListener(client);
// Add the list that will be set as the active
ArrayList<PrivacyItem> items = new ArrayList<PrivacyItem>();
PrivacyItem item = new PrivacyItem(PrivacyItem.Type.jid.name(), true, 1);
item.setValue(getConnection(0).getUser());
items.add(item);
privacyManager.createPrivacyList(listName, items);
Thread.sleep(500);
// Set the active list
privacyManager.setActiveListName(listName);
Thread.sleep(500);
// Assert the list composition.
assertEquals(listName, privacyManager.getActiveList().toString());
List<PrivacyItem> privacyItems = privacyManager.getPrivacyList(listName).getItems();
assertEquals(1, privacyItems.size());
// Assert the privacy item composition
PrivacyItem receivedItem = privacyItems.get(0);
assertEquals(1, receivedItem.getOrder());
assertEquals(PrivacyItem.Type.jid, receivedItem.getType());
assertEquals(true, receivedItem.isAllow());
privacyManager.deletePrivacyList(listName);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check when a client set more than one list.
*/
public void testCreateTwoLists() {
try {
String listName1 = "1testCreateTwoLists";
String listName2 = "2testCreateTwoLists";
String groupName = "testCreateTwoListsGroup";
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(getConnection(0));
PrivacyClient client = new PrivacyClient(privacyManager);
privacyManager.addListener(client);
// Add a list
ArrayList<PrivacyItem> items = new ArrayList<PrivacyItem>();
PrivacyItem item = new PrivacyItem(PrivacyItem.Type.jid.name(), true, 1);
item.setValue(getConnection(0).getUser());
items.add(item);
privacyManager.createPrivacyList(listName1, items);
Thread.sleep(500);
// Add the another list
ArrayList<PrivacyItem> itemsList2 = new ArrayList<PrivacyItem>();
item = new PrivacyItem(PrivacyItem.Type.group.name(), false, 2);
item.setValue(groupName);
item.setFilterMessage(true);
itemsList2.add(item);
privacyManager.createPrivacyList(listName2, itemsList2);
Thread.sleep(500);
// Assert the list composition.
PrivacyList[] privacyLists = privacyManager.getPrivacyLists();
PrivacyList receivedList1 = null;
PrivacyList receivedList2 = null;
for (PrivacyList privacyList : privacyLists) {
if (listName1.equals(privacyList.toString())) {
receivedList1 = privacyList;
}
if (listName2.equals(privacyList.toString())) {
receivedList2 = privacyList;
}
}
PrivacyItem receivedItem;
// Assert on the list 1
assertNotNull(receivedList1);
assertEquals(1, receivedList1.getItems().size());
receivedItem = receivedList1.getItems().get(0);
assertEquals(1, receivedItem.getOrder());
assertEquals(PrivacyItem.Type.jid, receivedItem.getType());
assertEquals(true, receivedItem.isAllow());
assertEquals(getConnection(0).getUser(), receivedItem.getValue());
// Assert on the list 2
assertNotNull(receivedList2);
assertEquals(1, receivedList2.getItems().size());
receivedItem = receivedList2.getItems().get(0);
assertEquals(2, receivedItem.getOrder());
assertEquals(PrivacyItem.Type.group, receivedItem.getType());
assertEquals(groupName, receivedItem.getValue());
assertEquals(false, receivedItem.isAllow());
assertEquals(groupName, receivedItem.getValue());
assertEquals(false, receivedItem.isFilterEverything());
assertEquals(true, receivedItem.isFilterMessage());
assertEquals(false, receivedItem.isFilterPresence_in());
assertEquals(false, receivedItem.isFilterPresence_out());
privacyManager.deletePrivacyList(listName1);
privacyManager.deletePrivacyList(listName2);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check when a client set a new list and then update its content.
*/
public void testCreateAndUpdateList() {
try {
String listName = "testCreateAndUpdateList";
String user = "tybalt@example.com";
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(getConnection(0));
PrivacyClient client = new PrivacyClient(privacyManager);
privacyManager.addListener(client);
// Add the list that will be set as the active
ArrayList<PrivacyItem> items = new ArrayList<PrivacyItem>();
PrivacyItem item = new PrivacyItem(PrivacyItem.Type.jid.name(), true, 1);
item.setValue(getConnection(0).getUser());
items.add(item);
privacyManager.createPrivacyList(listName, items);
Thread.sleep(500);
// Remove the existing item and add a new one.
items.remove(item);
item = new PrivacyItem(PrivacyItem.Type.jid.name(), false, 2);
item.setValue(user);
item.setFilterPresence_out(true);
item.setFilterPresence_in(true);
item.setFilterMessage(true);
items.add(item);
// Update the list on server
privacyManager.updatePrivacyList(listName, items);
Thread.sleep(500);
// Assert the list composition.
PrivacyList list = privacyManager.getPrivacyList(listName);
assertEquals(1, list.getItems().size());
// Assert the privacy item composition
PrivacyItem receivedItem = list.getItems().get(0);
assertEquals(2, receivedItem.getOrder());
assertEquals(PrivacyItem.Type.jid, receivedItem.getType());
assertEquals(false, receivedItem.isAllow());
assertEquals(user, receivedItem.getValue());
assertEquals(false, receivedItem.isFilterEverything());
assertEquals(true, receivedItem.isFilterMessage());
assertEquals(true, receivedItem.isFilterPresence_in());
assertEquals(true, receivedItem.isFilterPresence_out());
assertEquals(true, client.wasModified());
privacyManager.deletePrivacyList(listName);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check when a client denies the use of a default list.
*/
public void testDenyDefaultList() {
try {
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(getConnection(0));
PrivacyClient client = new PrivacyClient(privacyManager);
privacyManager.addListener(client);
privacyManager.declineDefaultList();
Thread.sleep(500);
try {
// The list should not exist and an error will be raised
privacyManager.getDefaultList();
} catch (XMPPException xmppException) {
assertEquals(404, xmppException.getXMPPError().getCode());
}
assertEquals(null, null);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check when a client denies the use of the active list.
*/
public void testDenyActiveList() {
try {
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(getConnection(0));
PrivacyClient client = new PrivacyClient(privacyManager);
privacyManager.addListener(client);
privacyManager.declineActiveList();
Thread.sleep(500);
try {
// The list should not exist and an error will be raised
privacyManager.getActiveList();
} catch (XMPPException xmppException) {
assertEquals(404, xmppException.getXMPPError().getCode());
}
assertEquals(null, null);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check when a client set a new default list.
*/
public void testCreateDefaultList() {
try {
String listName = "testCreateDefaultList";
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(getConnection(0));
PrivacyClient client = new PrivacyClient(privacyManager);
privacyManager.addListener(client);
// Add the list that will be set as the Default
ArrayList<PrivacyItem> items = new ArrayList<PrivacyItem>();
PrivacyItem item = new PrivacyItem(PrivacyItem.Type.jid.name(), true, 1);
item.setValue(getConnection(0).getUser());
items.add(item);
privacyManager.createPrivacyList(listName, items);
Thread.sleep(500);
// Set the Default list
privacyManager.setDefaultListName(listName);
Thread.sleep(500);
// Assert the list composition.
assertEquals(listName, privacyManager.getDefaultList().toString());
List<PrivacyItem> privacyItems = privacyManager.getPrivacyList(listName).getItems();
assertEquals(1, privacyItems.size());
// Assert the privacy item composition
PrivacyItem receivedItem = privacyItems.get(0);
assertEquals(1, receivedItem.getOrder());
assertEquals(PrivacyItem.Type.jid, receivedItem.getType());
assertEquals(true, receivedItem.isAllow());
privacyManager.deletePrivacyList(listName);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check when a client add a new list and then remove it.
*/
public void testRemoveList() {
try {
String listName = "testRemoveList";
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(getConnection(0));
PrivacyClient client = new PrivacyClient(privacyManager);
privacyManager.addListener(client);
// Add the list that will be set as the Default
ArrayList<PrivacyItem> items = new ArrayList<PrivacyItem>();
PrivacyItem item = new PrivacyItem(PrivacyItem.Type.jid.name(), true, 1);
item.setValue(getConnection(0).getUser());
items.add(item);
privacyManager.createPrivacyList(listName, items);
Thread.sleep(500);
// Set the Default list
privacyManager.setDefaultListName(listName);
Thread.sleep(500);
privacyManager.deletePrivacyList(listName);
Thread.sleep(500);
try {
// The list should not exist and an error will be raised
privacyManager.getPrivacyList(listName);
} catch (XMPPException xmppException) {
assertEquals(404, xmppException.getXMPPError().getCode());
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check different types of privacy items.
*/
public void testPrivacyItems() {
try {
String listName = "testPrivacyItems";
String user = "tybalt@example.com";
String groupName = "enemies";
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(getConnection(0));
PrivacyClient client = new PrivacyClient(privacyManager);
privacyManager.addListener(client);
PrivacyItem[] originalPrivacyItems = new PrivacyItem[12];
int i=0;
// Items to test JID
PrivacyItem item = new PrivacyItem(PrivacyItem.Type.jid.name(), true, i);
item.setValue(i + "_" + user);
originalPrivacyItems[i] = item;
i = i + 1;
item = new PrivacyItem(PrivacyItem.Type.jid.name(), false, i);
item.setValue(i + "_" + user);
originalPrivacyItems[i] = item;
i = i + 1;
// Items to test suscription
item = new PrivacyItem(PrivacyItem.Type.subscription.name(), true, i);
item.setValue(PrivacyRule.SUBSCRIPTION_BOTH);
originalPrivacyItems[i] = item;
i = i + 1;
item = new PrivacyItem(PrivacyItem.Type.subscription.name(), false, i);
item.setValue(PrivacyRule.SUBSCRIPTION_FROM);
originalPrivacyItems[i] = item;
i = i + 1;
item = new PrivacyItem(PrivacyItem.Type.subscription.name(), true, i);
item.setValue(PrivacyRule.SUBSCRIPTION_TO);
originalPrivacyItems[i] = item;
i = i + 1;
item = new PrivacyItem(PrivacyItem.Type.subscription.name(), false, i);
item.setValue(PrivacyRule.SUBSCRIPTION_NONE);
originalPrivacyItems[i] = item;
i = i + 1;
// Items to test Group
item = new PrivacyItem(PrivacyItem.Type.group.name(), false, i);
item.setValue(groupName);
originalPrivacyItems[i] = item;
i = i + 1;
// Items to test messages
item = new PrivacyItem(PrivacyItem.Type.group.name(), false, i);
item.setValue(groupName);
item.setFilterMessage(true);
originalPrivacyItems[i] = item;
i = i + 1;
// Items to test presence notifications
item = new PrivacyItem(PrivacyItem.Type.group.name(), false, i);
item.setValue(groupName);
item.setFilterMessage(true);
originalPrivacyItems[i] = item;
i = i + 1;
item = new PrivacyItem(null, false, i);
item.setFilterPresence_in(true);
originalPrivacyItems[i] = item;
i = i + 1;
item = new PrivacyItem(PrivacyItem.Type.subscription.name(), false, i);
item.setValue(PrivacyRule.SUBSCRIPTION_TO);
item.setFilterPresence_out(true);
originalPrivacyItems[i] = item;
i = i + 1;
item = new PrivacyItem(PrivacyItem.Type.jid.name(), false, i);
item.setValue(i + "_" + user);
item.setFilterPresence_out(true);
item.setFilterPresence_in(true);
item.setFilterMessage(true);
originalPrivacyItems[i] = item;
// Set the new privacy list
privacyManager.createPrivacyList(listName, Arrays.asList(originalPrivacyItems));
Thread.sleep(500);
// Assert the server list composition.
List<PrivacyItem> privacyItems = privacyManager.getPrivacyList(listName).getItems();
assertEquals(originalPrivacyItems.length, privacyItems.size());
// Assert the local and server privacy item composition
PrivacyItem originalItem;
PrivacyItem receivedItem;
int index;
for (int j = 0; j < originalPrivacyItems.length; j++) {
// Look for the same server and original items
receivedItem = privacyItems.get(j);
index = 0;
while ((index < originalPrivacyItems.length)
&& (originalPrivacyItems[index].getOrder() != receivedItem.getOrder())) {
index++;
}
originalItem = originalPrivacyItems[index];
// Assert the items
assertEquals(originalItem.getOrder(), receivedItem.getOrder());
assertEquals(originalItem.getType(), receivedItem.getType());
assertEquals(originalItem.isAllow(), receivedItem.isAllow());
assertEquals(originalItem.getValue(), receivedItem.getValue());
assertEquals(originalItem.isFilterEverything(), receivedItem.isFilterEverything());
assertEquals(originalItem.isFilterIQ(), receivedItem.isFilterIQ());
assertEquals(originalItem.isFilterMessage(), receivedItem.isFilterMessage());
assertEquals(originalItem.isFilterPresence_in(), receivedItem.isFilterPresence_in());
assertEquals(originalItem.isFilterPresence_out(), receivedItem.isFilterPresence_out());
}
privacyManager.deletePrivacyList(listName);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
protected int getMaxConnections() {
return 1;
}
/**
* This class supports automated tests about privacy communication from the
* server to the client.
*
* @author Francisco Vives
*/
public class PrivacyClient implements PrivacyListListener {
/**
* holds if the receiver list was modified
*/
private boolean wasModified = false;
/**
* holds a privacy to hold server requests Clients should not use Privacy
* class since it is private for the smack framework.
*/
private Privacy privacy = new Privacy();
public PrivacyClient(PrivacyListManager manager) {
super();
}
public void setPrivacyList(String listName, List<PrivacyItem> listItem) {
privacy.setPrivacyList(listName, listItem);
}
public void updatedPrivacyList(String listName) {
this.wasModified = true;
}
public boolean wasModified() {
return this.wasModified;
}
}
}

View file

@ -0,0 +1,535 @@
/**
*
* 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.smack.test;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.SocketFactory;
import junit.framework.TestCase;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.util.ConnectionUtils;
import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;
/**
* Base class for all the test cases which provides a pre-configured execution context. This
* means that any test case that subclassifies this base class will have access to a pool of
* connections and to the user of each connection. The maximum number of connections in the pool
* can be controlled by the message {@link #getMaxConnections()} which every subclass must
* implement.<p>
*
* This base class defines a default execution context (i.e. host, port, chat domain and muc
* domain) which can be found in the file "config/test-case.xml". However, each subclass could
* redefine the default configuration by providing its own configuration file (if desired). The
* name of the configuration file must be of the form <test class name>.xml (e.g. RosterTest.xml).
* The file must be placed in the folder "config". This folder is where the default configuration
* file is being held.
*
* @author Gaston Dombiak
*/
public abstract class SmackTestCase extends TestCase {
private String host = "localhost";
private String serviceName = "localhost";
private int port = 5222;
private String usernamePrefix = "user";
private String passwordPrefix;
private boolean testAnonymousLogin = false;
private Map<String, String> accountCreationParameters = new HashMap<String, String>();
private boolean samePassword;
private List<Integer> createdUserIdx = new ArrayList<Integer>();
private boolean compressionEnabled = false;
private String[] usernames;
private String[] passwords;
private String chatDomain = "chat";
private String mucDomain = "conference";
private XMPPConnection[] connections = null;
/**
* Constructor for SmackTestCase.
* @param arg0 arg for SmackTestCase
*/
public SmackTestCase(String arg0) {
super(arg0);
}
/**
* Returns the maximum number of connections to initialize for this test case. All the
* initialized connections will be connected to the server using a new test account for
* each conection.
*
* @return the maximum number of connections to initialize for this test case.
*/
protected abstract int getMaxConnections();
/**
* Returns a SocketFactory that will be used to create the socket to the XMPP server. By
* default no SocketFactory is used but subclasses my want to redefine this method.<p>
*
* A custom SocketFactory allows fine-grained control of the actual connection to the XMPP
* server. A typical use for a custom SocketFactory is when connecting through a SOCKS proxy.
*
* @return a SocketFactory that will be used to create the socket to the XMPP server.
*/
protected SocketFactory getSocketFactory() {
return null;
}
/**
* Returns <code>false</code> if the connections initialized by the test case will be
* automatically connected to the XMPP server.
* Returns <code>true</code> if the connections initialized by the test case will
* NOT be connected to the XMPP server. To connect the connections invoke
* {@link #connectAndLogin(int)}.
* <p>
* Connections are connected by default.
* Overwrite this method if the test case needs unconnected connections.
*
* @return <code>true</code> if connections should NOT be connected automatically,
* <code>false</code> if connections should be connected automatically.
*/
protected boolean createOfflineConnections() {
return false;
}
/**
* Returns the XMPPConnection located at the requested position. Each test case holds a
* pool of connections which is initialized while setting up the test case. The maximum
* number of connections is controlled by the message {@link #getMaxConnections()} which
* every subclass must implement.<p>
*
* If the requested position is greater than the connections size then an
* IllegalArgumentException will be thrown.
*
* @param index the position in the pool of the connection to look for.
* @return the XMPPConnection located at the requested position.
*/
protected XMPPConnection getConnection(int index) {
if (index > getMaxConnections()) {
throw new IllegalArgumentException("Index out of bounds");
}
return connections[index];
}
/**
* Creates a new XMPPConnection using the connection preferences. This is useful when
* not using a connection from the connection pool in a test case.
*
* @return a new XMPP connection.
*/
protected XMPPConnection createConnection() {
// Create the configuration for this new connection
ConnectionConfiguration config = new ConnectionConfiguration(host, port);
config.setCompressionEnabled(compressionEnabled);
config.setSendPresence(sendInitialPresence());
if (getSocketFactory() == null) {
config.setSocketFactory(getSocketFactory());
}
return new XMPPConnection(config);
}
/**
* Returns the name of the user (e.g. johndoe) that is using the connection
* located at the requested position.
*
* @param index the position in the pool of the connection to look for.
* @return the user of the user (e.g. johndoe).
*/
protected String getUsername(int index) {
return usernames[index];
}
/**
* Returns the password of the user (e.g. johndoe) that is using the connection
* located at the requested position.
*
* @param index the position in the pool of the connection to look for.
* @return the password of the user (e.g. johndoe).
*/
protected String getPassword(int index) {
return passwords[index];
}
/**
* Returns the bare XMPP address of the user (e.g. johndoe@jabber.org) that is
* using the connection located at the requested position.
*
* @param index the position in the pool of the connection to look for.
* @return the bare XMPP address of the user (e.g. johndoe@jabber.org).
*/
protected String getBareJID(int index) {
return getUsername(index) + "@" + getConnection(index).getServiceName();
}
/**
* Returns the full XMPP address of the user (e.g. johndoe@jabber.org/Smack) that is
* using the connection located at the requested position.
*
* @param index the position in the pool of the connection to look for.
* @return the full XMPP address of the user (e.g. johndoe@jabber.org/Smack).
*/
protected String getFullJID(int index) {
return getBareJID(index) + "/Smack";
}
protected String getHost() {
return host;
}
protected int getPort() {
return port;
}
protected String getServiceName() {
return serviceName;
}
/**
* Returns the default groupchat service domain.
*
* @return the default groupchat service domain.
*/
protected String getChatDomain() {
return chatDomain;
}
/**
* Returns the default MUC service domain.
*
* @return the default MUC service domain.
*/
protected String getMUCDomain() {
return mucDomain + "." + serviceName;
}
protected void setUp() throws Exception {
super.setUp();
init();
if (getMaxConnections() < 1) {
return;
}
connections = new XMPPConnection[getMaxConnections()];
usernames = new String[getMaxConnections()];
passwords = new String[getMaxConnections()];
try {
// Connect to the server
for (int i = 0; i < getMaxConnections(); i++) {
connections[i] = createConnection();
if (!createOfflineConnections())
connections[i].connect();
String currentPassword = usernamePrefix + (i+1);
String currentUser = currentPassword;
if (passwordPrefix != null)
currentPassword = (samePassword ? passwordPrefix : passwordPrefix + (i+1));
usernames[i] = currentUser;
passwords[i] = currentPassword;
}
// Use the host name that the server reports. This is a good idea in most
// cases, but could fail if the user set a hostname in their XMPP server
// that will not resolve as a network connection.
host = connections[0].getHost();
serviceName = connections[0].getServiceName();
if (!createOfflineConnections()) {
for (int i = 0; i < getMaxConnections(); i++) {
String currentUser = usernames[i];
String currentPassword = passwords[i];
try {
getConnection(i).login(currentUser, currentPassword, "Smack");
} catch (XMPPException e) {
// Create the test accounts
if (!getConnection(0).getAccountManager().supportsAccountCreation())
fail("Server does not support account creation");
// Create the account and try logging in again as the
// same user.
try {
createAccount(i, currentUser, currentPassword);
} catch (Exception e1) {
e1.printStackTrace();
fail("Could not create user: " + currentUser);
}
i--;
}
}
// Let the server process the available presences
Thread.sleep(150);
}
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
protected void connectAndLogin(int connectionIndex) throws XMPPException
{
String password = usernamePrefix + (connectionIndex + 1);
if (passwordPrefix != null)
password = (samePassword ? passwordPrefix : passwordPrefix + (connectionIndex + 1));
XMPPConnection con = getConnection(connectionIndex);
if (!con.isConnected())
con.connect();
try {
con.login(usernamePrefix + (connectionIndex + 1), password, "Smack");
} catch (XMPPException e) {
createAccount(connectionIndex, usernamePrefix + (connectionIndex + 1), password);
con.login(usernamePrefix + (connectionIndex + 1), password, "Smack");
}
}
protected void disconnect(int connectionIndex) throws XMPPException
{
getConnection(connectionIndex).disconnect();
}
private void createAccount(int connectionIdx, String username, String password)
{
// Create the test account
try {
getConnection(connectionIdx).getAccountManager().createAccount(username, password);
createdUserIdx.add(connectionIdx);
} catch (XMPPException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
protected void tearDown() throws Exception {
super.tearDown();
for (int i = 0; i < getMaxConnections(); i++)
{
if (createdUserIdx.contains(i))
{
try {
// If not connected, connect so that we can delete the account.
if (!getConnection(i).isConnected()) {
XMPPConnection con = getConnection(i);
con.connect();
con.login(getUsername(i), getUsername(i));
}
else if (!getConnection(i).isAuthenticated()) {
getConnection(i).login(getUsername(i), getUsername(i));
}
// Delete the created account for the test
getConnection(i).getAccountManager().deleteAccount();
}
catch (Exception e) {
e.printStackTrace();
}
}
if (getConnection(i).isConnected()) {
// Close the connection
getConnection(i).disconnect();
}
}
}
protected boolean sendInitialPresence() {
return true;
}
/**
* Initializes the context of the test case. We will first try to load the configuration from
* a file whose name is conformed by the test case class name plus an .xml extension
* (e.g RosterTest.xml). If no file was found under that name then we will try to load the
* default configuration for all the test cases from the file "config/test-case.xml".
*
*/
private void init() {
try {
boolean found = false;
// Try to load the configutation from an XML file specific for this test case
Enumeration<URL> resources =
ClassLoader.getSystemClassLoader().getResources(getConfigurationFilename());
while (resources.hasMoreElements()) {
found = parseURL(resources.nextElement());
}
// If none was found then try to load the configuration from the default configuration
// file (i.e. "config/test-case.xml")
if (!found) {
resources = ClassLoader.getSystemClassLoader().getResources("config/test-case.xml");
while (resources.hasMoreElements()) {
found = parseURL(resources.nextElement());
}
}
if (!found) {
System.err.println("File config/test-case.xml not found. Using default config.");
}
}
catch (Exception e) {
/* Do Nothing */
}
}
/**
* Returns true if the given URL was found and parsed without problems. The file provided
* by the URL must contain information useful for the test case configuration, such us,
* host and port of the server.
*
* @param url the url of the file to parse.
* @return true if the given URL was found and parsed without problems.
*/
private boolean parseURL(URL url) {
boolean parsedOK = false;
InputStream systemStream = null;
try {
systemStream = url.openStream();
XmlPullParser parser = new MXParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
parser.setInput(systemStream, "UTF-8");
int eventType = parser.getEventType();
do {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("host")) {
host = parser.nextText();
}
else if (parser.getName().equals("port")) {
port = parseIntProperty(parser, port);
}
else if (parser.getName().equals("serviceName")) {
serviceName = parser.nextText();
}
else if (parser.getName().equals("chat")) {
chatDomain = parser.nextText();
}
else if (parser.getName().equals("muc")) {
mucDomain = parser.nextText();
}
else if (parser.getName().equals("username")) {
usernamePrefix = parser.nextText();
}
else if (parser.getName().equals("password")) {
samePassword = "true".equals(parser.getAttributeValue(0));
passwordPrefix = parser.nextText();
}
else if (parser.getName().equals("testAnonymousLogin")) {
testAnonymousLogin = "true".equals(parser.nextText());
}
else if (parser.getName().equals("accountCreationParameters")) {
int numAttributes = parser.getAttributeCount();
String key = null;
String value = null;
for (int i = 0; i < numAttributes; i++) {
key = parser.getAttributeName(i);
value = parser.getAttributeValue(i);
accountCreationParameters.put(key, value);
}
}
else if (parser.getName().equals("compressionEnabled")) {
compressionEnabled = "true".equals(parser.nextText());
}
}
eventType = parser.next();
}
while (eventType != XmlPullParser.END_DOCUMENT);
parsedOK = true;
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
systemStream.close();
}
catch (Exception e) {
/* Do Nothing */
}
}
return parsedOK;
}
private static int parseIntProperty(XmlPullParser parser, int defaultValue) throws Exception {
try {
return Integer.parseInt(parser.nextText());
}
catch (NumberFormatException nfe) {
nfe.printStackTrace();
return defaultValue;
}
}
/**
* Returns the name of the configuration file related to <b>this</b> test case. By default all
* the test cases will use the same configuration file. However, it's possible to override the
* default configuration by providing a file of the form <test case class name>.xml
* (e.g. RosterTest.xml).
*
* @return the name of the configuration file related to this test case.
*/
private String getConfigurationFilename() {
String fullClassName = this.getClass().getName();
int firstChar = fullClassName.lastIndexOf('.') + 1;
return "config/" + fullClassName.substring(firstChar) + ".xml";
}
/**
* Subscribes all connections with each other: They all become friends
*
* @throws XMPPException
*/
protected void letsAllBeFriends() throws XMPPException {
ConnectionUtils.letsAllBeFriends(connections);
}
/**
* Compares two contents of two byte arrays to make sure that they are equal
*
* @param message The message to show in the case of failure
* @param byteArray1 The first byte array.
* @param byteArray2 The second byte array.
*/
public static void assertEquals(String message, byte [] byteArray1, byte [] byteArray2) {
if(byteArray1.length != byteArray2.length) {
fail(message);
}
for(int i = 0; i < byteArray1.length; i++) {
assertEquals(message, byteArray1[i], byteArray2[i]);
}
}
public boolean isTestAnonymousLogin() {
return testAnonymousLogin;
}
public Map<String, String> getAccountCreationParameters() {
return accountCreationParameters;
}
}

View file

@ -0,0 +1,43 @@
/**
*
* Copyright 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.smack.util;
import junit.framework.TestCase;
/**
* A test case for the Cache class.
*/
public class CacheTest extends TestCase {
public void testMaxSize() {
Cache<Integer, String> cache = new Cache<Integer, String>(100, -1);
for (int i=0; i < 1000; i++) {
cache.put(i, "value");
assertTrue("Cache size must never be larger than 100.", cache.size() <= 100);
}
}
public void testLRU() {
Cache<Integer, String> cache = new Cache<Integer, String>(100, -1);
for (int i=0; i < 1000; i++) {
cache.put(i, "value");
assertTrue("LRU algorithm for cache key of '0' failed.",
cache.get(new Integer(0)) != null);
}
}
}

View file

@ -0,0 +1,29 @@
package org.jivesoftware.smack.util;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPException;
public class ConnectionUtils {
private ConnectionUtils() {}
public static void becomeFriends(Connection con0, Connection con1) throws XMPPException {
Roster r0 = con0.getRoster();
Roster r1 = con1.getRoster();
r0.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
r1.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
r0.createEntry(con1.getUser(), "u2", null);
r1.createEntry(con0.getUser(), "u1", null);
}
public static void letsAllBeFriends(Connection[] connections) throws XMPPException {
for (Connection c1 : connections) {
for (Connection c2 : connections) {
if (c1 == c2)
continue;
becomeFriends(c1, c2);
}
}
}
}

View file

@ -0,0 +1,147 @@
package org.jivesoftware.smack.util;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import org.jivesoftware.smack.util.dns.DNSJavaResolver;
import org.jivesoftware.smack.util.dns.DNSResolver;
import org.jivesoftware.smack.util.dns.HostAddress;
import org.jivesoftware.smack.util.dns.JavaxResolver;
import org.jivesoftware.smack.util.dns.SRVRecord;
import org.junit.Test;
public class DNSUtilTest {
private static final String igniterealtimeDomain = "igniterealtime.org";
private static final String igniterealtimeXMPPServer = "xmpp." + igniterealtimeDomain;
private static final int igniterealtimeClientPort = 5222;
private static final int igniterealtimeServerPort = 5269;
@Test
public void xmppClientDomainJavaXTest() {
DNSResolver resolver = JavaxResolver.getInstance();
assertNotNull(resolver);
DNSUtil.setDNSResolver(resolver);
xmppClientDomainTest();
}
@Test
public void xmppServerDomainJavaXTest() {
DNSResolver resolver = JavaxResolver.getInstance();
assertNotNull(resolver);
DNSUtil.setDNSResolver(resolver);
xmppServerDomainTest();
}
@Test
public void xmppClientDomainDNSJavaTest() {
DNSResolver resolver = DNSJavaResolver.getInstance();
assertNotNull(resolver);
DNSUtil.setDNSResolver(resolver);
xmppClientDomainTest();
}
@Test
public void xmppServerDomainDNSJavaTest() {
DNSResolver resolver = DNSJavaResolver.getInstance();
assertNotNull(resolver);
DNSUtil.setDNSResolver(resolver);
xmppServerDomainTest();
}
@Test
public void sortSRVlowestPrioFirstTest() {
List<HostAddress> sortedRecords = DNSUtil.sortSRVRecords(createSRVRecords());
assertTrue(sortedRecords.get(0).getFQDN().equals("0.20.foo.bar"));
}
@Test
public void sortSRVdistributeOverWeights() {
int weight50 = 0;
int weight20one = 0;
int weight20two = 0;
int weight10 = 0;
for (int i = 0; i < 1000; i++) {
List<HostAddress> sortedRecords = DNSUtil.sortSRVRecords(createSRVRecords());
String host = sortedRecords.get(1).getFQDN();
if (host.equals("5.20.one.foo.bar")) {
weight20one++;
} else if (host.equals("5.20.two.foo.bar")) {
weight20two++;
} else if (host.equals("5.10.foo.bar")) {
weight10++;
} else if (host.equals("5.50.foo.bar")) {
weight50++;
} else {
fail("Wrong host after SRVRecord sorting");
}
}
assertTrue(weight50 > 400 && weight50 < 600);
assertTrue(weight20one > 100 && weight20one < 300);
assertTrue(weight20two > 100 && weight20two < 300);
assertTrue(weight10 > 0&& weight10 < 200);
}
@Test
public void sortSRVdistributeZeroWeights() {
int weightZeroOne = 0;
int weightZeroTwo = 0;
for (int i = 0; i < 1000; i++) {
List<HostAddress> sortedRecords = DNSUtil.sortSRVRecords(createSRVRecords());
// Remove the first 5 records with a lower priority
for (int j = 0; j < 5; j++) {
sortedRecords.remove(0);
}
String host = sortedRecords.remove(0).getFQDN();
if (host.equals("10.0.one.foo.bar")) {
weightZeroOne++;
} else if (host.endsWith("10.0.two.foo.bar")) {
weightZeroTwo++;
} else {
fail("Wrong host after SRVRecord sorting");
}
}
assertTrue(weightZeroOne > 400 && weightZeroOne < 600);
assertTrue(weightZeroTwo > 400 && weightZeroTwo < 600);
}
private void xmppClientDomainTest() {
List<HostAddress> hostAddresses = DNSUtil.resolveXMPPDomain(igniterealtimeDomain);
HostAddress ha = hostAddresses.get(0);
assertEquals(ha.getFQDN(), igniterealtimeXMPPServer);
assertEquals(ha.getPort(), igniterealtimeClientPort);
}
private void xmppServerDomainTest() {
List<HostAddress> hostAddresses = DNSUtil.resolveXMPPServerDomain(igniterealtimeDomain);
HostAddress ha = hostAddresses.get(0);
assertEquals(ha.getFQDN(), igniterealtimeXMPPServer);
assertEquals(ha.getPort(), igniterealtimeServerPort);
}
private static List<SRVRecord> createSRVRecords() {
List<SRVRecord> records = new ArrayList<SRVRecord>();
// We create one record with priority 0 that should also be tried first
// Then 4 records with priority 5 and different weights (50, 20, 20, 10)
// Then 2 records with priority 10 and weight 0 which should be treaded equal
// These records are added in a 'random' way to the list
try {
records.add(new SRVRecord("5.20.one.foo.bar", 42, 5, 20)); // Priority 5, Weight 20
records.add(new SRVRecord("10.0.one.foo.bar", 42, 10, 0)); // Priority 10, Weight 0
records.add(new SRVRecord("5.10.foo.bar", 42, 5, 10)); // Priority 5, Weight 10
records.add(new SRVRecord("10.0.two.foo.bar", 42, 10, 0)); // Priority 10, Weight 0
records.add(new SRVRecord("5.20.two.foo.bar", 42, 5, 20)); // Priority 5, Weight 20
records.add(new SRVRecord("0.20.foo.bar", 42, 0, 20)); // Priority 0, Weight 20
records.add(new SRVRecord("5.50.foo.bar", 42, 5, 50)); // Priority 5, Weight 50
} catch (IllegalArgumentException e) {
// Ignore
}
assertTrue(records.size() > 0);
return records;
}
}

View file

@ -0,0 +1,203 @@
/**
*
* 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.smack.util;
import java.io.StringReader;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.test.SmackTestCase;
import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
public class XMPPErrorTest extends SmackTestCase {
public XMPPErrorTest(String arg0) {
super(arg0);
}
/**
* Check the creation of a new xmppError locally.
*/
public void testLocalErrorCreation() {
XMPPError error = new XMPPError(XMPPError.Condition.item_not_found);
error.toXML();
assertEquals(error.getCondition(), "item-not-found");
assertEquals(error.getCode(), 404);
assertEquals(error.getType(), XMPPError.Type.CANCEL);
assertNull(error.getMessage());
}
/**
* Check the creation of a new xmppError locally.
*/
public void testLocalErrorWithCommentCreation() {
String message = "Error Message";
XMPPError error = new XMPPError(XMPPError.Condition.item_not_found, message);
error.toXML();
assertEquals(error.getCondition(), "item-not-found");
assertEquals(error.getCode(), 404);
assertEquals(error.getType(), XMPPError.Type.CANCEL);
assertEquals(error.getMessage(), message);
}
/**
* Check the creation of a new xmppError locally where there is not a default defined.
*/
public void testUserDefinedErrorWithCommentCreation() {
String message = "Error Message";
XMPPError error = new XMPPError(new XMPPError.Condition("my_own_error"), message);
error.toXML();
assertEquals(error.getCondition(), "my_own_error");
assertEquals(error.getCode(), 0);
assertNull(error.getType());
assertEquals(error.getMessage(), message);
}
/**
* Check the parser with an xml with the 404 error.
*/
public void test404() {
// Make the XML to test
String xml = "<error code='404' type='cancel'>" +
"<item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" +
"</error></iq>";
try {
// Create the xml parser
XmlPullParser parser = getParserFromXML(xml);
// Create a packet from the xml
XMPPError packet = parseError(parser);
assertNotNull(packet);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check the parser with an xml with the 404 error.
*/
public void testCancel() {
// Make the XML to test
String xml = "<error type='cancel'>" +
"<conflict xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" +
"</error>";
try {
// Create the xml parser
XmlPullParser parser = getParserFromXML(xml);
// Create a packet from the xml
XMPPError error = parseError(parser);
assertNotNull(error);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testMessageAndApplicationDefinedError() {
String xml = "<error type='modify' code='404'>" +
"<undefined-condition xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" +
"<text xml:lang='en' xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'>" +
"Some special application diagnostic information..." +
"</text>" +
"<special-application-condition xmlns='application-ns'/>" +
"</error>";
try {
// Create the xml parser
XmlPullParser parser = getParserFromXML(xml);
// Create a packet from the xml
XMPPError error = parseError(parser);
String sendingXML = error.toXML();
assertNotNull(error);
assertNotNull(sendingXML);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check the parser with an xml with the 404 error.
*/
public void testCancelWithMessage() {
// Make the XML to test
String xml = "<error type='cancel'>" +
"<conflict xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" +
"<text xmlns='urn:ietf:params:xml:ns:xmpp-stanzas' xml:lang='langcode'>" +
"Some special application diagnostic information!" +
"</text>" +
"</error>";
try {
// Create the xml parser
XmlPullParser parser = getParserFromXML(xml);
// Create a packet from the xml
XMPPError error = parseError(parser);
assertNotNull(error);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Check the parser with an xml with the 404 error.
*/
public void testCancelWithMessageAndApplicationError() {
// Make the XML to test
String xml = "<error type='cancel' code='10'>" +
"<conflict xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" +
"<text xml:lang='en' xmlns='urn:ietf:params:xml:ns:xmpp-streams'>" +
"Some special application diagnostic information!" +
"</text>" +
"<application-defined-error xmlns='application-ns'/>" +
"</error>";
try {
// Create the xml parser
XmlPullParser parser = getParserFromXML(xml);
// Create a packet from the xml
XMPPError error = parseError(parser);
assertNotNull(error);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private XMPPError parseError(XmlPullParser parser) throws Exception {
parser.next();
return PacketParserUtils.parseError(parser);
}
private XmlPullParser getParserFromXML(String xml) throws XmlPullParserException {
MXParser parser = new MXParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
parser.setInput(new StringReader(xml));
return parser;
}
protected int getMaxConnections() {
return 0;
}
}

View file

@ -0,0 +1,31 @@
<?xml version="1.0"?>
<!-- Rename this file to test-case.xml to overwrite the default values of the Smack testcases -->
<testcase>
<!-- Host and port of the XMPP server to use -->
<host>localhost</host>
<port>5222</port>
<!-- Username prefix to use for creating accounts. -->
<username>user</username>
<!-- Password prefix to use for creating connections -->
<!-- If same password is true, then the same password will be used for all accounts -->
<!-- If password is not set, the username will be used as password -->
<!--
<password same='true'>passw0rd</password>
-->
<!-- Chat and MUC domain names to use -->
<chat>chat</chat>
<muc>conference</muc>
<!-- LoginTest parameters -->
<testAnonymousLogin>false</testAnonymousLogin>
<!-- Account creation parameters -->
<!--
<accountCreationParameters email="test@xcp.localhost" name="test"/>
-->
<compressionEnabled>false</compressionEnabled>
</testcase>