mirror of
https://github.com/vanitasvitae/Smack.git
synced 2025-12-07 19:41:11 +01:00
Migrate from Ant to Gradle (SMACK-265)
This commit is contained in:
parent
235eca3a3d
commit
201152ef42
767 changed files with 1088 additions and 4296 deletions
31
integration-test/config/test-case.example.xml
Normal file
31
integration-test/config/test-case.example.xml
Normal 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>
|
||||
95
integration-test/org/jivesoftware/smack/ChatTest.java
Normal file
95
integration-test/org/jivesoftware/smack/ChatTest.java
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2004 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
103
integration-test/org/jivesoftware/smack/FloodTest.java
Normal file
103
integration-test/org/jivesoftware/smack/FloodTest.java
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
102
integration-test/org/jivesoftware/smack/IQTest.java
Normal file
102
integration-test/org/jivesoftware/smack/IQTest.java
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
184
integration-test/org/jivesoftware/smack/LoginTest.java
Normal file
184
integration-test/org/jivesoftware/smack/LoginTest.java
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
408
integration-test/org/jivesoftware/smack/MessageTest.java
Normal file
408
integration-test/org/jivesoftware/smack/MessageTest.java
Normal file
|
|
@ -0,0 +1,408 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
257
integration-test/org/jivesoftware/smack/PacketReaderTest.java
Normal file
257
integration-test/org/jivesoftware/smack/PacketReaderTest.java
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2004 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
274
integration-test/org/jivesoftware/smack/PresenceTest.java
Normal file
274
integration-test/org/jivesoftware/smack/PresenceTest.java
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
56
integration-test/org/jivesoftware/smack/PrivacyClient.java
Normal file
56
integration-test/org/jivesoftware/smack/PrivacyClient.java
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/**
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
257
integration-test/org/jivesoftware/smack/ReconnectionTest.java
Normal file
257
integration-test/org/jivesoftware/smack/ReconnectionTest.java
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
/**
|
||||
*
|
||||
* All rights reserved. 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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
/**
|
||||
*
|
||||
* All rights reserved. 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
206
integration-test/org/jivesoftware/smack/RosterListenerTest.java
Normal file
206
integration-test/org/jivesoftware/smack/RosterListenerTest.java
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
/**
|
||||
*
|
||||
* All rights reserved. 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());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
710
integration-test/org/jivesoftware/smack/RosterSmackTest.java
Normal file
710
integration-test/org/jivesoftware/smack/RosterSmackTest.java
Normal file
|
|
@ -0,0 +1,710 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2005 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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) {}
|
||||
};
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,384 @@
|
|||
/**
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
521
integration-test/org/jivesoftware/smack/packet/PrivacyTest.java
Normal file
521
integration-test/org/jivesoftware/smack/packet/PrivacyTest.java
Normal file
|
|
@ -0,0 +1,521 @@
|
|||
/**
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
535
integration-test/org/jivesoftware/smack/test/SmackTestCase.java
Normal file
535
integration-test/org/jivesoftware/smack/test/SmackTestCase.java
Normal file
|
|
@ -0,0 +1,535 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2005 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
43
integration-test/org/jivesoftware/smack/util/CacheTest.java
Normal file
43
integration-test/org/jivesoftware/smack/util/CacheTest.java
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2005 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
147
integration-test/org/jivesoftware/smack/util/DNSUtilTest.java
Normal file
147
integration-test/org/jivesoftware/smack/util/DNSUtilTest.java
Normal 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;
|
||||
}
|
||||
}
|
||||
203
integration-test/org/jivesoftware/smack/util/XMPPErrorTest.java
Normal file
203
integration-test/org/jivesoftware/smack/util/XMPPErrorTest.java
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2006 Jive Software.
|
||||
*
|
||||
* All rights reserved. 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;
|
||||
}
|
||||
}
|
||||
116
integration-test/org/jivesoftware/smackx/CompressionTest.java
Normal file
116
integration-test/org/jivesoftware/smackx/CompressionTest.java
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2005 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smack.*;
|
||||
import org.jivesoftware.smack.filter.PacketIDFilter;
|
||||
import org.jivesoftware.smack.packet.IQ;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.packet.Version;
|
||||
|
||||
/**
|
||||
* Ensure that stream compression (JEP-138) is correctly supported by Smack.
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class CompressionTest extends SmackTestCase {
|
||||
|
||||
public CompressionTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that stream compression works fine. It is assumed that the server supports and has
|
||||
* stream compression enabled.
|
||||
*/
|
||||
public void testSuccessCompression() throws XMPPException {
|
||||
|
||||
// Create the configuration for this new connection
|
||||
ConnectionConfiguration config = new ConnectionConfiguration(getHost(), getPort());
|
||||
config.setCompressionEnabled(true);
|
||||
config.setSASLAuthenticationEnabled(true);
|
||||
|
||||
XMPPConnection connection = new XMPPConnection(config);
|
||||
connection.connect();
|
||||
|
||||
// Login with the test account
|
||||
connection.login("user0", "user0");
|
||||
|
||||
assertTrue("Connection is not using stream compression", connection.isUsingCompression());
|
||||
|
||||
// Request the version of the server
|
||||
Version version = new Version();
|
||||
version.setType(IQ.Type.GET);
|
||||
version.setTo(getServiceName());
|
||||
|
||||
// Create a packet collector to listen for a response.
|
||||
PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(version.getPacketID()));
|
||||
|
||||
connection.sendPacket(version);
|
||||
|
||||
// Wait up to 5 seconds for a result.
|
||||
IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
// Close the collector
|
||||
collector.cancel();
|
||||
|
||||
assertNotNull("No reply was received from the server", result);
|
||||
assertEquals("Incorrect IQ type from server", IQ.Type.RESULT, result.getType());
|
||||
|
||||
// Close connection
|
||||
connection.disconnect();
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Just create an account.
|
||||
*/
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
XMPPConnection setupConnection = new XMPPConnection(getServiceName());
|
||||
setupConnection.connect();
|
||||
if (!setupConnection.getAccountManager().supportsAccountCreation())
|
||||
fail("Server does not support account creation");
|
||||
|
||||
// Create the test account
|
||||
try {
|
||||
setupConnection.getAccountManager().createAccount("user0", "user0");
|
||||
} catch (XMPPException e) {
|
||||
// Do nothing if the accout already exists
|
||||
if (e.getXMPPError().getCode() != 409) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the created account for the test.
|
||||
*/
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
XMPPConnection setupConnection = createConnection();
|
||||
setupConnection.connect();
|
||||
setupConnection.login("user0", "user0");
|
||||
// Delete the created account for the test
|
||||
setupConnection.getAccountManager().deleteAccount();
|
||||
// Close the setupConnection
|
||||
setupConnection.disconnect();
|
||||
}
|
||||
}
|
||||
119
integration-test/org/jivesoftware/smackx/FileTransferTest.java
Normal file
119
integration-test/org/jivesoftware/smackx/FileTransferTest.java
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2006 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smackx.filetransfer.*;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.SynchronousQueue;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class FileTransferTest extends SmackTestCase {
|
||||
|
||||
int receiveCount = -1;
|
||||
|
||||
Exception exception;
|
||||
|
||||
public FileTransferTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
public void testInbandFileTransfer() throws Exception {
|
||||
FileTransferNegotiator.IBB_ONLY = true;
|
||||
try {
|
||||
testFileTransfer();
|
||||
}
|
||||
finally {
|
||||
FileTransferNegotiator.IBB_ONLY = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void testFileTransfer() throws Exception {
|
||||
final byte [] testTransfer = "This is a test transfer".getBytes();
|
||||
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
|
||||
FileTransferManager manager1 = new FileTransferManager(getConnection(0));
|
||||
manager1.addFileTransferListener(new FileTransferListener() {
|
||||
public void fileTransferRequest(final FileTransferRequest request) {
|
||||
new Thread(new Runnable() {
|
||||
public void run() {
|
||||
IncomingFileTransfer transfer = request.accept();
|
||||
InputStream stream;
|
||||
try {
|
||||
stream = transfer.recieveFile();
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
exception = e;
|
||||
return;
|
||||
}
|
||||
byte [] testRecieve = new byte[testTransfer.length];
|
||||
int receiveCount = 0;
|
||||
try {
|
||||
while (receiveCount != -1) {
|
||||
receiveCount = stream.read(testRecieve);
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
exception = e;
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
stream.close();
|
||||
}
|
||||
catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
try {
|
||||
queue.put(testRecieve);
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
exception = e;
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
});
|
||||
|
||||
// Send the file from user1 to user0
|
||||
FileTransferManager manager2 = new FileTransferManager(getConnection(1));
|
||||
OutgoingFileTransfer outgoing = manager2.createOutgoingFileTransfer(getFullJID(0));
|
||||
|
||||
OutputStream stream =
|
||||
outgoing.sendFile("test.txt", testTransfer.length, "The great work of robin hood");
|
||||
stream.write(testTransfer);
|
||||
stream.flush();
|
||||
stream.close();
|
||||
|
||||
if(exception != null) {
|
||||
exception.printStackTrace();
|
||||
fail();
|
||||
}
|
||||
byte [] array = queue.take();
|
||||
assertEquals("Recieved file not equal to sent file.", testTransfer, array);
|
||||
}
|
||||
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
157
integration-test/org/jivesoftware/smackx/FormTest.java
Normal file
157
integration-test/org/jivesoftware/smackx/FormTest.java
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2004 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smack.Chat;
|
||||
import org.jivesoftware.smack.PacketCollector;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.filter.ThreadFilter;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
|
||||
/**
|
||||
* Tests the DataForms extensions.
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class FormTest extends SmackTestCase {
|
||||
|
||||
public FormTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. Create a form to fill out and send it to the other user
|
||||
* 2. Retrieve the form to fill out, complete it and return it to the requestor
|
||||
* 3. Retrieve the completed form and check that everything is OK
|
||||
*/
|
||||
public void testFilloutForm() {
|
||||
Form formToSend = new Form(Form.TYPE_FORM);
|
||||
formToSend.setInstructions(
|
||||
"Fill out this form to report your case.\nThe case will be created automatically.");
|
||||
formToSend.setTitle("Case configurations");
|
||||
// Add a hidden variable
|
||||
FormField field = new FormField("hidden_var");
|
||||
field.setType(FormField.TYPE_HIDDEN);
|
||||
field.addValue("Some value for the hidden variable");
|
||||
formToSend.addField(field);
|
||||
// Add a fixed variable
|
||||
field = new FormField();
|
||||
field.addValue("Section 1: Case description");
|
||||
formToSend.addField(field);
|
||||
// Add a text-single variable
|
||||
field = new FormField("name");
|
||||
field.setLabel("Enter a name for the case");
|
||||
field.setType(FormField.TYPE_TEXT_SINGLE);
|
||||
formToSend.addField(field);
|
||||
// Add a text-multi variable
|
||||
field = new FormField("description");
|
||||
field.setLabel("Enter a description");
|
||||
field.setType(FormField.TYPE_TEXT_MULTI);
|
||||
formToSend.addField(field);
|
||||
// Add a boolean variable
|
||||
field = new FormField("time");
|
||||
field.setLabel("Is this your first case?");
|
||||
field.setType(FormField.TYPE_BOOLEAN);
|
||||
formToSend.addField(field);
|
||||
// Add a text variable where an int value is expected
|
||||
field = new FormField("age");
|
||||
field.setLabel("How old are you?");
|
||||
field.setType(FormField.TYPE_TEXT_SINGLE);
|
||||
formToSend.addField(field);
|
||||
|
||||
// Create the chats between the two participants
|
||||
Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
PacketCollector collector = getConnection(0).createPacketCollector(
|
||||
new ThreadFilter(chat.getThreadID()));
|
||||
PacketCollector collector2 = getConnection(1).createPacketCollector(
|
||||
new ThreadFilter(chat.getThreadID()));
|
||||
|
||||
Message msg = new Message();
|
||||
msg.setBody("To enter a case please fill out this form and send it back to me");
|
||||
msg.addExtension(formToSend.getDataFormToSend());
|
||||
|
||||
try {
|
||||
// Send the message with the form to fill out
|
||||
chat.sendMessage(msg);
|
||||
|
||||
// Get the message with the form to fill out
|
||||
Message msg2 = (Message)collector2.nextResult(2000);
|
||||
assertNotNull("Messge not found", msg2);
|
||||
// Retrieve the form to fill out
|
||||
Form formToRespond = Form.getFormFrom(msg2);
|
||||
assertNotNull(formToRespond);
|
||||
assertNotNull(formToRespond.getField("name"));
|
||||
assertNotNull(formToRespond.getField("description"));
|
||||
// Obtain the form to send with the replies
|
||||
Form completedForm = formToRespond.createAnswerForm();
|
||||
assertNotNull(completedForm.getField("hidden_var"));
|
||||
// Check that a field of type String does not accept booleans
|
||||
try {
|
||||
completedForm.setAnswer("name", true);
|
||||
fail("A boolean value was set to a field of type String");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
}
|
||||
completedForm.setAnswer("name", "Credit card number invalid");
|
||||
completedForm.setAnswer(
|
||||
"description",
|
||||
"The ATM says that my credit card number is invalid. What's going on?");
|
||||
completedForm.setAnswer("time", true);
|
||||
completedForm.setAnswer("age", 20);
|
||||
// Create a new message to send with the completed form
|
||||
msg2 = new Message();
|
||||
msg2.setTo(msg.getFrom());
|
||||
msg2.setThread(msg.getThread());
|
||||
msg2.setType(Message.Type.chat);
|
||||
msg2.setBody("To enter a case please fill out this form and send it back to me");
|
||||
// Add the completed form to the message
|
||||
msg2.addExtension(completedForm.getDataFormToSend());
|
||||
// Send the message with the completed form
|
||||
getConnection(1).sendPacket(msg2);
|
||||
|
||||
// Get the message with the completed form
|
||||
Message msg3 = (Message) collector.nextResult(2000);
|
||||
assertNotNull("Messge not found", msg3);
|
||||
// Retrieve the completed form
|
||||
completedForm = Form.getFormFrom(msg3);
|
||||
assertNotNull(completedForm);
|
||||
assertNotNull(completedForm.getField("name"));
|
||||
assertNotNull(completedForm.getField("description"));
|
||||
assertEquals(
|
||||
completedForm.getField("name").getValues().next(),
|
||||
"Credit card number invalid");
|
||||
assertNotNull(completedForm.getField("time"));
|
||||
assertNotNull(completedForm.getField("age"));
|
||||
assertEquals("The age is bad", "20", completedForm.getField("age").getValues().next());
|
||||
|
||||
}
|
||||
catch (XMPPException ex) {
|
||||
fail(ex.getMessage());
|
||||
}
|
||||
finally {
|
||||
collector.cancel();
|
||||
collector2.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smack.*;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smack.filter.PacketFilter;
|
||||
import org.jivesoftware.smack.filter.PacketExtensionFilter;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author Matt Tucker
|
||||
*/
|
||||
public class GroupChatInvitationTest extends SmackTestCase {
|
||||
|
||||
private PacketCollector collector = null;
|
||||
|
||||
/**
|
||||
* Constructor for GroupChatInvitationTest.
|
||||
* @param arg0
|
||||
*/
|
||||
public GroupChatInvitationTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
public void testInvitation() {
|
||||
try {
|
||||
GroupChatInvitation invitation = new GroupChatInvitation("test@" + getChatDomain());
|
||||
Message message = new Message(getBareJID(1));
|
||||
message.setBody("Group chat invitation!");
|
||||
message.addExtension(invitation);
|
||||
getConnection(0).sendPacket(message);
|
||||
|
||||
Thread.sleep(250);
|
||||
|
||||
Message result = (Message)collector.pollResult();
|
||||
assertNotNull("Message not delivered correctly.", result);
|
||||
|
||||
GroupChatInvitation resultInvite = (GroupChatInvitation)result.getExtension("x",
|
||||
"jabber:x:conference");
|
||||
|
||||
assertEquals("Invitation not to correct room", "test@" + getChatDomain(),
|
||||
resultInvite.getRoomAddress());
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
// Register listener for groupchat invitations.
|
||||
PacketFilter filter = new PacketExtensionFilter("x", "jabber:x:conference");
|
||||
collector = getConnection(1).createPacketCollector(filter);
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
// Cancel the packet collector so that no more results are queued up
|
||||
collector.cancel();
|
||||
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2006 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smack.XMPPConnection;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.packet.LastActivity;
|
||||
|
||||
public class LastActivityManagerTest extends SmackTestCase {
|
||||
|
||||
/**
|
||||
* This is a test to check if a LastActivity request for idle time is
|
||||
* answered and correct.
|
||||
*/
|
||||
public void testOnline() {
|
||||
XMPPConnection conn0 = getConnection(0);
|
||||
XMPPConnection conn1 = getConnection(1);
|
||||
|
||||
// Send a message as the last activity action from connection 1 to
|
||||
// connection 0
|
||||
conn1.sendPacket(new Message(getBareJID(0)));
|
||||
|
||||
// Wait 1 seconds to have some idle time
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
fail("Thread sleep interrupted");
|
||||
}
|
||||
|
||||
LastActivity lastActivity = null;
|
||||
try {
|
||||
lastActivity = LastActivityManager.getLastActivity(conn0, getFullJID(1));
|
||||
} catch (XMPPException e) {
|
||||
e.printStackTrace();
|
||||
fail("An error occurred requesting the Last Activity");
|
||||
}
|
||||
|
||||
// Asserts that the last activity packet was received
|
||||
assertNotNull("No last activity packet", lastActivity);
|
||||
// Asserts that there is at least a 1 second of idle time
|
||||
assertTrue(
|
||||
"The last activity idle time is less than expected: " + lastActivity.getIdleTime(),
|
||||
lastActivity.getIdleTime() >= 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a test to check if a denied LastActivity response is handled correctly.
|
||||
*/
|
||||
public void testOnlinePermisionDenied() {
|
||||
XMPPConnection conn0 = getConnection(0);
|
||||
XMPPConnection conn2 = getConnection(2);
|
||||
|
||||
// Send a message as the last activity action from connection 2 to
|
||||
// connection 0
|
||||
conn2.sendPacket(new Message(getBareJID(0)));
|
||||
|
||||
// Wait 1 seconds to have some idle time
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
fail("Thread sleep interrupted");
|
||||
}
|
||||
|
||||
try {
|
||||
LastActivityManager.getLastActivity(conn0, getFullJID(2));
|
||||
fail("No error was received from the server. User was able to get info of other user not in his roster.");
|
||||
} catch (XMPPException e) {
|
||||
assertNotNull("No error was returned from the server", e.getXMPPError());
|
||||
assertEquals("Forbidden error was not returned from the server", 403,
|
||||
e.getXMPPError().getCode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a test to check if a LastActivity request for last logged out
|
||||
* lapsed time is answered and correct
|
||||
*/
|
||||
public void testLastLoggedOut() {
|
||||
XMPPConnection conn0 = getConnection(0);
|
||||
|
||||
LastActivity lastActivity = null;
|
||||
try {
|
||||
lastActivity = LastActivityManager.getLastActivity(conn0, getBareJID(1));
|
||||
} catch (XMPPException e) {
|
||||
e.printStackTrace();
|
||||
fail("An error occurred requesting the Last Activity");
|
||||
}
|
||||
|
||||
assertNotNull("No last activity packet", lastActivity);
|
||||
assertTrue("The last activity idle time should be 0 since the user is logged in: " +
|
||||
lastActivity.getIdleTime(), lastActivity.getIdleTime() == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a test to check if a LastActivity request for server uptime
|
||||
* is answered and correct
|
||||
*/
|
||||
public void testServerUptime() {
|
||||
XMPPConnection conn0 = getConnection(0);
|
||||
|
||||
LastActivity lastActivity = null;
|
||||
try {
|
||||
lastActivity = LastActivityManager.getLastActivity(conn0, getHost());
|
||||
} catch (XMPPException e) {
|
||||
if (e.getXMPPError().getCode() == 403) {
|
||||
//The test can not be done since the host do not allow this kind of request
|
||||
return;
|
||||
}
|
||||
e.printStackTrace();
|
||||
fail("An error occurred requesting the Last Activity");
|
||||
}
|
||||
|
||||
assertNotNull("No last activity packet", lastActivity);
|
||||
assertTrue("The last activity idle time should be greater than 0 : " +
|
||||
lastActivity.getIdleTime(), lastActivity.getIdleTime() > 0);
|
||||
}
|
||||
|
||||
public LastActivityManagerTest(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getMaxConnections() {
|
||||
return 3;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
try {
|
||||
getConnection(0).getRoster().createEntry(getBareJID(1), "User1", null);
|
||||
Thread.sleep(300);
|
||||
} catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,239 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.jivesoftware.smack.*;
|
||||
import org.jivesoftware.smack.packet.*;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* Test the MessageEvent extension using the high level API.
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class MessageEventManagerTest extends SmackTestCase {
|
||||
|
||||
public MessageEventManagerTest(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* High level API test.
|
||||
* This is a simple test to use with a XMPP client and check if the client receives the
|
||||
* message
|
||||
* 1. User_1 will send a message to user_2 requesting to be notified when any of these events
|
||||
* occurs: offline, composing, displayed or delivered
|
||||
*/
|
||||
public void testSendMessageEventRequest() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
|
||||
// Create the message to send with the roster
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("An interesting body comes here...");
|
||||
// Add to the message all the notifications requests (offline, delivered, displayed,
|
||||
// composing)
|
||||
MessageEventManager.addNotificationsRequests(msg, true, true, true, true);
|
||||
|
||||
// Send the message that contains the notifications request
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
} catch (Exception e) {
|
||||
fail("An error occured sending the message");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* High level API test.
|
||||
* This is a simple test to use with a XMPP client, check if the client receives the
|
||||
* message and display in the console any notification
|
||||
* 1. User_1 will send a message to user_2 requesting to be notified when any of these events
|
||||
* occurs: offline, composing, displayed or delivered
|
||||
* 2. User_2 will use a XMPP client (like Exodus) to display the message and compose a reply
|
||||
* 3. User_1 will display any notification that receives
|
||||
*/
|
||||
public void testSendMessageEventRequestAndDisplayNotifications() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
|
||||
MessageEventManager messageEventManager = new MessageEventManager(getConnection(0));
|
||||
messageEventManager
|
||||
.addMessageEventNotificationListener(new MessageEventNotificationListener() {
|
||||
public void deliveredNotification(String from, String packetID) {
|
||||
System.out.println("From: " + from + " PacketID: " + packetID + "(delivered)");
|
||||
}
|
||||
|
||||
public void displayedNotification(String from, String packetID) {
|
||||
System.out.println("From: " + from + " PacketID: " + packetID + "(displayed)");
|
||||
}
|
||||
|
||||
public void composingNotification(String from, String packetID) {
|
||||
System.out.println("From: " + from + " PacketID: " + packetID + "(composing)");
|
||||
}
|
||||
|
||||
public void offlineNotification(String from, String packetID) {
|
||||
System.out.println("From: " + from + " PacketID: " + packetID + "(offline)");
|
||||
}
|
||||
|
||||
public void cancelledNotification(String from, String packetID) {
|
||||
System.out.println("From: " + from + " PacketID: " + packetID + "(cancelled)");
|
||||
}
|
||||
});
|
||||
|
||||
// Create the message to send with the roster
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("An interesting body comes here...");
|
||||
// Add to the message all the notifications requests (offline, delivered, displayed,
|
||||
// composing)
|
||||
MessageEventManager.addNotificationsRequests(msg, true, true, true, true);
|
||||
|
||||
// Send the message that contains the notifications request
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
// Wait a few seconds so that the XMPP client can send any event
|
||||
Thread.sleep(200);
|
||||
} catch (Exception e) {
|
||||
fail("An error occured sending the message");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* High level API test.
|
||||
* 1. User_1 will send a message to user_2 requesting to be notified when any of these events
|
||||
* occurs: offline, composing, displayed or delivered
|
||||
* 2. User_2 will receive the message
|
||||
* 3. User_2 will simulate that the message was displayed
|
||||
* 4. User_2 will simulate that he/she is composing a reply
|
||||
* 5. User_2 will simulate that he/she has cancelled the reply
|
||||
*/
|
||||
public void testRequestsAndNotifications() {
|
||||
final ArrayList<String> results = new ArrayList<String>();
|
||||
ArrayList<String> resultsExpected = new ArrayList<String>();
|
||||
resultsExpected.add("deliveredNotificationRequested");
|
||||
resultsExpected.add("composingNotificationRequested");
|
||||
resultsExpected.add("displayedNotificationRequested");
|
||||
resultsExpected.add("offlineNotificationRequested");
|
||||
resultsExpected.add("deliveredNotification");
|
||||
resultsExpected.add("displayedNotification");
|
||||
resultsExpected.add("composingNotification");
|
||||
resultsExpected.add("cancelledNotification");
|
||||
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
|
||||
MessageEventManager messageEventManager1 = new MessageEventManager(getConnection(0));
|
||||
messageEventManager1
|
||||
.addMessageEventNotificationListener(new MessageEventNotificationListener() {
|
||||
public void deliveredNotification(String from, String packetID) {
|
||||
results.add("deliveredNotification");
|
||||
}
|
||||
|
||||
public void displayedNotification(String from, String packetID) {
|
||||
results.add("displayedNotification");
|
||||
}
|
||||
|
||||
public void composingNotification(String from, String packetID) {
|
||||
results.add("composingNotification");
|
||||
}
|
||||
|
||||
public void offlineNotification(String from, String packetID) {
|
||||
results.add("offlineNotification");
|
||||
}
|
||||
|
||||
public void cancelledNotification(String from, String packetID) {
|
||||
results.add("cancelledNotification");
|
||||
}
|
||||
});
|
||||
|
||||
MessageEventManager messageEventManager2 = new MessageEventManager(getConnection(1));
|
||||
messageEventManager2
|
||||
.addMessageEventRequestListener(new DefaultMessageEventRequestListener() {
|
||||
public void deliveredNotificationRequested(
|
||||
String from,
|
||||
String packetID,
|
||||
MessageEventManager messageEventManager) {
|
||||
super.deliveredNotificationRequested(from, packetID, messageEventManager);
|
||||
results.add("deliveredNotificationRequested");
|
||||
}
|
||||
|
||||
public void displayedNotificationRequested(
|
||||
String from,
|
||||
String packetID,
|
||||
MessageEventManager messageEventManager) {
|
||||
super.displayedNotificationRequested(from, packetID, messageEventManager);
|
||||
results.add("displayedNotificationRequested");
|
||||
}
|
||||
|
||||
public void composingNotificationRequested(
|
||||
String from,
|
||||
String packetID,
|
||||
MessageEventManager messageEventManager) {
|
||||
super.composingNotificationRequested(from, packetID, messageEventManager);
|
||||
results.add("composingNotificationRequested");
|
||||
}
|
||||
|
||||
public void offlineNotificationRequested(
|
||||
String from,
|
||||
String packetID,
|
||||
MessageEventManager messageEventManager) {
|
||||
super.offlineNotificationRequested(from, packetID, messageEventManager);
|
||||
results.add("offlineNotificationRequested");
|
||||
}
|
||||
});
|
||||
|
||||
// Create the message to send with the roster
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("An interesting body comes here...");
|
||||
// Add to the message all the notifications requests (offline, delivered, displayed,
|
||||
// composing)
|
||||
MessageEventManager.addNotificationsRequests(msg, true, true, true, true);
|
||||
|
||||
// Send the message that contains the notifications request
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
messageEventManager2.sendDisplayedNotification(getBareJID(0), msg.getPacketID());
|
||||
messageEventManager2.sendComposingNotification(getBareJID(0), msg.getPacketID());
|
||||
messageEventManager2.sendCancelledNotification(getBareJID(0), msg.getPacketID());
|
||||
// Wait up to 2 seconds
|
||||
long initial = System.currentTimeMillis();
|
||||
while (System.currentTimeMillis() - initial < 2000 &&
|
||||
(!results.containsAll(resultsExpected))) {
|
||||
Thread.sleep(100);
|
||||
}
|
||||
assertTrue(
|
||||
"Test failed due to bad results (1)" + resultsExpected,
|
||||
resultsExpected.containsAll(results));
|
||||
assertTrue(
|
||||
"Test failed due to bad results (2)" + results,
|
||||
results.containsAll(resultsExpected));
|
||||
|
||||
} catch (Exception e) {
|
||||
fail("An error occured sending the message");
|
||||
}
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smackx.packet.MessageEventTest;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
*
|
||||
* Test suite that runs all the Message Event extension tests
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class MessageEventTests {
|
||||
|
||||
public static Test suite() {
|
||||
TestSuite suite = new TestSuite("High and low level API tests for message event extension");
|
||||
//$JUnit-BEGIN$
|
||||
suite.addTest(new TestSuite(MessageEventManagerTest.class));
|
||||
suite.addTest(new TestSuite(MessageEventTest.class));
|
||||
//$JUnit-END$
|
||||
return suite;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,251 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2006 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smack.PacketCollector;
|
||||
import org.jivesoftware.smack.SmackConfiguration;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.filter.MessageTypeFilter;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.packet.MultipleAddresses;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Tests that JEP-33 support in Smack is correct.
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class MultipleRecipientManagerTest extends SmackTestCase {
|
||||
|
||||
public MultipleRecipientManagerTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that sending and receiving of packets is ok.
|
||||
*/
|
||||
public void testSending() throws XMPPException {
|
||||
|
||||
PacketCollector collector1 =
|
||||
getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
|
||||
PacketCollector collector2 =
|
||||
getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
|
||||
PacketCollector collector3 =
|
||||
getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
|
||||
|
||||
Message message = new Message();
|
||||
message.setBody("Hola");
|
||||
List<String> to = Arrays.asList(new String[]{getBareJID(1)});
|
||||
List<String> cc = Arrays.asList(new String[]{getBareJID(2)});
|
||||
List<String> bcc = Arrays.asList(new String[]{getBareJID(3)});
|
||||
MultipleRecipientManager.send(getConnection(0), message, to, cc, bcc);
|
||||
|
||||
Packet message1 = collector1.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection 1 never received the message", message1);
|
||||
MultipleRecipientInfo info1 = MultipleRecipientManager.getMultipleRecipientInfo(message1);
|
||||
assertNotNull("Message 1 does not contain MultipleRecipientInfo", info1);
|
||||
assertFalse("Message 1 should be 'replyable'", info1.shouldNotReply());
|
||||
List<?> addresses1 = info1.getTOAddresses();
|
||||
assertEquals("Incorrect number of TO addresses", 1, addresses1.size());
|
||||
String address1 = ((MultipleAddresses.Address) addresses1.get(0)).getJid();
|
||||
assertEquals("Incorrect TO address", getBareJID(1), address1);
|
||||
addresses1 = info1.getCCAddresses();
|
||||
assertEquals("Incorrect number of CC addresses", 1, addresses1.size());
|
||||
address1 = ((MultipleAddresses.Address) addresses1.get(0)).getJid();
|
||||
assertEquals("Incorrect CC address", getBareJID(2), address1);
|
||||
|
||||
Packet message2 = collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection 2 never received the message", message2);
|
||||
MultipleRecipientInfo info2 = MultipleRecipientManager.getMultipleRecipientInfo(message2);
|
||||
assertNotNull("Message 2 does not contain MultipleRecipientInfo", info2);
|
||||
assertFalse("Message 2 should be 'replyable'", info2.shouldNotReply());
|
||||
List<MultipleAddresses.Address> addresses2 = info2.getTOAddresses();
|
||||
assertEquals("Incorrect number of TO addresses", 1, addresses2.size());
|
||||
String address2 = ((MultipleAddresses.Address) addresses2.get(0)).getJid();
|
||||
assertEquals("Incorrect TO address", getBareJID(1), address2);
|
||||
addresses2 = info2.getCCAddresses();
|
||||
assertEquals("Incorrect number of CC addresses", 1, addresses2.size());
|
||||
address2 = ((MultipleAddresses.Address) addresses2.get(0)).getJid();
|
||||
assertEquals("Incorrect CC address", getBareJID(2), address2);
|
||||
|
||||
Packet message3 = collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection 3 never received the message", message3);
|
||||
MultipleRecipientInfo info3 = MultipleRecipientManager.getMultipleRecipientInfo(message3);
|
||||
assertNotNull("Message 3 does not contain MultipleRecipientInfo", info3);
|
||||
assertFalse("Message 3 should be 'replyable'", info3.shouldNotReply());
|
||||
List<MultipleAddresses.Address> addresses3 = info3.getTOAddresses();
|
||||
assertEquals("Incorrect number of TO addresses", 1, addresses3.size());
|
||||
String address3 = ((MultipleAddresses.Address) addresses3.get(0)).getJid();
|
||||
assertEquals("Incorrect TO address", getBareJID(1), address3);
|
||||
addresses3 = info3.getCCAddresses();
|
||||
assertEquals("Incorrect number of CC addresses", 1, addresses3.size());
|
||||
address3 = ((MultipleAddresses.Address) addresses3.get(0)).getJid();
|
||||
assertEquals("Incorrect CC address", getBareJID(2), address3);
|
||||
|
||||
collector1.cancel();
|
||||
collector2.cancel();
|
||||
collector3.cancel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that replying to packets is ok.
|
||||
*/
|
||||
public void testReplying() throws XMPPException {
|
||||
PacketCollector collector0 =
|
||||
getConnection(0).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
|
||||
PacketCollector collector1 =
|
||||
getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
|
||||
PacketCollector collector2 =
|
||||
getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
|
||||
PacketCollector collector3 =
|
||||
getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
|
||||
|
||||
// Send the intial message with multiple recipients
|
||||
Message message = new Message();
|
||||
message.setBody("Hola");
|
||||
List<String> to = Arrays.asList(new String[]{getBareJID(1)});
|
||||
List<String> cc = Arrays.asList(new String[]{getBareJID(2)});
|
||||
List<String> bcc = Arrays.asList(new String[]{getBareJID(3)});
|
||||
MultipleRecipientManager.send(getConnection(0), message, to, cc, bcc);
|
||||
|
||||
// Get the message and ensure it's ok
|
||||
Message message1 =
|
||||
(Message) collector1.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection 1 never received the message", message1);
|
||||
MultipleRecipientInfo info = MultipleRecipientManager.getMultipleRecipientInfo(message1);
|
||||
assertNotNull("Message 1 does not contain MultipleRecipientInfo", info);
|
||||
assertFalse("Message 1 should be 'replyable'", info.shouldNotReply());
|
||||
assertEquals("Incorrect number of TO addresses", 1, info.getTOAddresses().size());
|
||||
assertEquals("Incorrect number of CC addresses", 1, info.getCCAddresses().size());
|
||||
|
||||
// Prepare and send the reply
|
||||
Message reply1 = new Message();
|
||||
reply1.setBody("This is my reply");
|
||||
MultipleRecipientManager.reply(getConnection(1), message1, reply1);
|
||||
|
||||
// Get the reply and ensure it's ok
|
||||
reply1 = (Message) collector0.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection 0 never received the reply", reply1);
|
||||
info = MultipleRecipientManager.getMultipleRecipientInfo(reply1);
|
||||
assertNotNull("Replied message does not contain MultipleRecipientInfo", info);
|
||||
assertFalse("Replied message should be 'replyable'", info.shouldNotReply());
|
||||
assertEquals("Incorrect number of TO addresses", 1, info.getTOAddresses().size());
|
||||
assertEquals("Incorrect number of CC addresses", 1, info.getCCAddresses().size());
|
||||
|
||||
// Send a reply to the reply
|
||||
Message reply2 = new Message();
|
||||
reply2.setBody("This is my reply to your reply");
|
||||
reply2.setFrom(getBareJID(0));
|
||||
MultipleRecipientManager.reply(getConnection(0), reply1, reply2);
|
||||
|
||||
// Get the reply and ensure it's ok
|
||||
reply2 = (Message) collector1.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection 1 never received the reply", reply2);
|
||||
info = MultipleRecipientManager.getMultipleRecipientInfo(reply2);
|
||||
assertNotNull("Replied message does not contain MultipleRecipientInfo", info);
|
||||
assertFalse("Replied message should be 'replyable'", info.shouldNotReply());
|
||||
assertEquals("Incorrect number of TO addresses", 1, info.getTOAddresses().size());
|
||||
assertEquals("Incorrect number of CC addresses", 1, info.getCCAddresses().size());
|
||||
|
||||
// Check that connection2 recevied 3 messages
|
||||
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection2 didn't receive the 1 message", message1);
|
||||
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection2 didn't receive the 2 message", message1);
|
||||
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection2 didn't receive the 3 message", message1);
|
||||
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNull("Connection2 received 4 messages", message1);
|
||||
|
||||
// Check that connection3 recevied only 1 message (was BCC in the first message)
|
||||
message1 = (Message) collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection3 didn't receive the 1 message", message1);
|
||||
message1 = (Message) collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNull("Connection2 received 2 messages", message1);
|
||||
|
||||
collector0.cancel();
|
||||
collector1.cancel();
|
||||
collector2.cancel();
|
||||
collector3.cancel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that replying is not allowed when disabled.
|
||||
*/
|
||||
public void testNoReply() throws XMPPException {
|
||||
PacketCollector collector1 =
|
||||
getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
|
||||
PacketCollector collector2 =
|
||||
getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
|
||||
PacketCollector collector3 =
|
||||
getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.normal));
|
||||
|
||||
// Send the intial message with multiple recipients
|
||||
Message message = new Message();
|
||||
message.setBody("Hola");
|
||||
List<String> to = Arrays.asList(new String[]{getBareJID(1)});
|
||||
List<String> cc = Arrays.asList(new String[]{getBareJID(2)});
|
||||
List<String> bcc = Arrays.asList(new String[]{getBareJID(3)});
|
||||
MultipleRecipientManager.send(getConnection(0), message, to, cc, bcc, null, null, true);
|
||||
|
||||
// Get the message and ensure it's ok
|
||||
Message message1 =
|
||||
(Message) collector1.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection 1 never received the message", message1);
|
||||
MultipleRecipientInfo info = MultipleRecipientManager.getMultipleRecipientInfo(message1);
|
||||
assertNotNull("Message 1 does not contain MultipleRecipientInfo", info);
|
||||
assertTrue("Message 1 should be not 'replyable'", info.shouldNotReply());
|
||||
assertEquals("Incorrect number of TO addresses", 1, info.getTOAddresses().size());
|
||||
assertEquals("Incorrect number of CC addresses", 1, info.getCCAddresses().size());
|
||||
|
||||
// Prepare and send the reply
|
||||
Message reply1 = new Message();
|
||||
reply1.setBody("This is my reply");
|
||||
try {
|
||||
MultipleRecipientManager.reply(getConnection(1), message1, reply1);
|
||||
fail("It was possible to send a reply to a not replyable message");
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
// Exception was expected since replying was not allowed
|
||||
}
|
||||
|
||||
// Check that connection2 recevied 1 messages
|
||||
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection2 didn't receive the 1 message", message1);
|
||||
message1 = (Message) collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNull("Connection2 received 2 messages", message1);
|
||||
|
||||
// Check that connection3 recevied only 1 message (was BCC in the first message)
|
||||
message1 = (Message) collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNotNull("Connection3 didn't receive the 1 message", message1);
|
||||
message1 = (Message) collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
|
||||
assertNull("Connection2 received 2 messages", message1);
|
||||
|
||||
collector1.cancel();
|
||||
collector2.cancel();
|
||||
collector3.cancel();
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,181 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smack.Chat;
|
||||
import org.jivesoftware.smack.PacketCollector;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.filter.MessageTypeFilter;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.packet.Presence;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.packet.OfflineMessageInfo;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Tests handling of offline messaging using OfflineMessageManager. This server requires the
|
||||
* server to support JEP-0013: Flexible Offline Message Retrieval.
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class OfflineMessageManagerTest extends SmackTestCase {
|
||||
|
||||
public OfflineMessageManagerTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
public void testDiscoverFlexibleRetrievalSupport() throws XMPPException {
|
||||
OfflineMessageManager offlineManager = new OfflineMessageManager(getConnection(1));
|
||||
assertTrue("Server does not support JEP-13", offlineManager.supportsFlexibleRetrieval());
|
||||
}
|
||||
|
||||
/**
|
||||
* While user2 is connected but unavailable, user1 sends 2 messages to user1. User2 then
|
||||
* performs some "Flexible Offline Message Retrieval" checking the number of offline messages,
|
||||
* retriving the headers, then the real messages of the headers and finally removing the
|
||||
* loaded messages.
|
||||
*/
|
||||
public void testReadAndDelete() {
|
||||
// Make user2 unavailable
|
||||
getConnection(1).sendPacket(new Presence(Presence.Type.unavailable));
|
||||
|
||||
try {
|
||||
Thread.sleep(500);
|
||||
|
||||
// User1 sends some messages to User2 which is not available at the moment
|
||||
Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
chat.sendMessage("Test 1");
|
||||
chat.sendMessage("Test 2");
|
||||
|
||||
Thread.sleep(500);
|
||||
|
||||
// User2 checks the number of offline messages
|
||||
OfflineMessageManager offlineManager = new OfflineMessageManager(getConnection(1));
|
||||
assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
|
||||
// Check the message headers
|
||||
Iterator<OfflineMessageHeader> headers = offlineManager.getHeaders();
|
||||
assertTrue("No message header was found", headers.hasNext());
|
||||
List<String> stamps = new ArrayList<String>();
|
||||
while (headers.hasNext()) {
|
||||
OfflineMessageHeader header = headers.next();
|
||||
assertEquals("Incorrect sender", getFullJID(0), header.getJid());
|
||||
assertNotNull("No stamp was found in the message header", header.getStamp());
|
||||
stamps.add(header.getStamp());
|
||||
}
|
||||
assertEquals("Wrong number of headers", 2, stamps.size());
|
||||
// Get the offline messages
|
||||
Iterator<Message> messages = offlineManager.getMessages(stamps);
|
||||
assertTrue("No message was found", messages.hasNext());
|
||||
stamps = new ArrayList<String>();
|
||||
while (messages.hasNext()) {
|
||||
Message message = messages.next();
|
||||
OfflineMessageInfo info = (OfflineMessageInfo) message.getExtension("offline",
|
||||
"http://jabber.org/protocol/offline");
|
||||
assertNotNull("No offline information was included in the offline message", info);
|
||||
assertNotNull("No stamp was found in the message header", info.getNode());
|
||||
stamps.add(info.getNode());
|
||||
}
|
||||
assertEquals("Wrong number of messages", 2, stamps.size());
|
||||
// Check that the offline messages have not been deleted
|
||||
assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
|
||||
|
||||
// User2 becomes available again
|
||||
PacketCollector collector = getConnection(1).createPacketCollector(
|
||||
new MessageTypeFilter(Message.Type.chat));
|
||||
getConnection(1).sendPacket(new Presence(Presence.Type.available));
|
||||
|
||||
// Check that no offline messages was sent to the user
|
||||
Message message = (Message) collector.nextResult(2500);
|
||||
assertNull("An offline message was sent from the server", message);
|
||||
|
||||
// Delete the retrieved offline messages
|
||||
offlineManager.deleteMessages(stamps);
|
||||
// Check that there are no offline message for this user
|
||||
assertEquals("Wrong number of offline messages", 0, offlineManager.getMessageCount());
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* While user2 is connected but unavailable, user1 sends 2 messages to user1. User2 then
|
||||
* performs some "Flexible Offline Message Retrieval" by fetching all the offline messages
|
||||
* and then removing all the offline messages.
|
||||
*/
|
||||
public void testFetchAndPurge() {
|
||||
// Make user2 unavailable
|
||||
getConnection(1).sendPacket(new Presence(Presence.Type.unavailable));
|
||||
|
||||
try {
|
||||
Thread.sleep(500);
|
||||
|
||||
// User1 sends some messages to User2 which is not available at the moment
|
||||
Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
chat.sendMessage("Test 1");
|
||||
chat.sendMessage("Test 2");
|
||||
|
||||
Thread.sleep(500);
|
||||
|
||||
// User2 checks the number of offline messages
|
||||
OfflineMessageManager offlineManager = new OfflineMessageManager(getConnection(1));
|
||||
assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
|
||||
// Get all offline messages
|
||||
Iterator<Message> messages = offlineManager.getMessages();
|
||||
assertTrue("No message was found", messages.hasNext());
|
||||
List<String> stamps = new ArrayList<String>();
|
||||
while (messages.hasNext()) {
|
||||
Message message = messages.next();
|
||||
OfflineMessageInfo info = (OfflineMessageInfo) message.getExtension("offline",
|
||||
"http://jabber.org/protocol/offline");
|
||||
assertNotNull("No offline information was included in the offline message", info);
|
||||
assertNotNull("No stamp was found in the message header", info.getNode());
|
||||
stamps.add(info.getNode());
|
||||
}
|
||||
assertEquals("Wrong number of messages", 2, stamps.size());
|
||||
// Check that the offline messages have not been deleted
|
||||
assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
|
||||
|
||||
// User2 becomes available again
|
||||
PacketCollector collector = getConnection(1).createPacketCollector(
|
||||
new MessageTypeFilter(Message.Type.chat));
|
||||
getConnection(1).sendPacket(new Presence(Presence.Type.available));
|
||||
|
||||
// Check that no offline messages was sent to the user
|
||||
Message message = (Message) collector.nextResult(2500);
|
||||
assertNull("An offline message was sent from the server", message);
|
||||
|
||||
// Delete all offline messages
|
||||
offlineManager.deleteMessages();
|
||||
// Check that there are no offline message for this user
|
||||
assertEquals("Wrong number of offline messages", 0, offlineManager.getMessageCount());
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,210 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.jivesoftware.smack.*;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* Test the Roster Exchange extension using the high level API
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class RosterExchangeManagerTest extends SmackTestCase {
|
||||
|
||||
private int entriesSent;
|
||||
private int entriesReceived;
|
||||
|
||||
/**
|
||||
* Constructor for RosterExchangeManagerTest.
|
||||
* @param name
|
||||
*/
|
||||
public RosterExchangeManagerTest(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* High level API test.
|
||||
* This is a simple test to use with a XMPP client and check if the client receives user1's
|
||||
* roster
|
||||
* 1. User_1 will send his/her roster to user_2
|
||||
*/
|
||||
public void testSendRoster() {
|
||||
// Send user1's roster to user2
|
||||
try {
|
||||
RosterExchangeManager rosterExchangeManager =
|
||||
new RosterExchangeManager(getConnection(0));
|
||||
rosterExchangeManager.send(getConnection(0).getRoster(), getBareJID(1));
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
fail("An error occured sending the roster");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* High level API test.
|
||||
* This is a simple test to use with a XMPP client and check if the client receives user1's
|
||||
* roster groups
|
||||
* 1. User_1 will send his/her RosterGroups to user_2
|
||||
*/
|
||||
public void testSendRosterGroup() {
|
||||
// Send user1's RosterGroups to user2
|
||||
try {
|
||||
RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(getConnection(0));
|
||||
for (RosterGroup rosterGroup : getConnection(0).getRoster().getGroups()) {
|
||||
rosterExchangeManager.send(rosterGroup, getBareJID(1));
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
fail("An error occured sending the roster");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* High level API test.
|
||||
* 1. User_1 will send his/her roster to user_2
|
||||
* 2. User_2 will receive the entries and iterate over them to check if everything is fine
|
||||
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
|
||||
* something is wrong
|
||||
*/
|
||||
public void testSendAndReceiveRoster() {
|
||||
RosterExchangeManager rosterExchangeManager1 = new RosterExchangeManager(getConnection(0));
|
||||
RosterExchangeManager rosterExchangeManager2 = new RosterExchangeManager(getConnection(1));
|
||||
|
||||
// Create a RosterExchangeListener that will iterate over the received roster entries
|
||||
RosterExchangeListener rosterExchangeListener = new RosterExchangeListener() {
|
||||
public void entriesReceived(String from, Iterator<RemoteRosterEntry> remoteRosterEntries) {
|
||||
int received = 0;
|
||||
assertNotNull("From is null", from);
|
||||
assertNotNull("rosterEntries is null", remoteRosterEntries);
|
||||
assertTrue("Roster without entries", remoteRosterEntries.hasNext());
|
||||
while (remoteRosterEntries.hasNext()) {
|
||||
received++;
|
||||
RemoteRosterEntry remoteEntry = remoteRosterEntries.next();
|
||||
System.out.println(remoteEntry);
|
||||
}
|
||||
entriesReceived = received;
|
||||
}
|
||||
};
|
||||
rosterExchangeManager2.addRosterListener(rosterExchangeListener);
|
||||
|
||||
// Send user1's roster to user2
|
||||
try {
|
||||
entriesSent = getConnection(0).getRoster().getEntryCount();
|
||||
entriesReceived = 0;
|
||||
rosterExchangeManager1.send(getConnection(0).getRoster(), getBareJID(1));
|
||||
// Wait up to 2 seconds
|
||||
long initial = System.currentTimeMillis();
|
||||
while (System.currentTimeMillis() - initial < 2000 &&
|
||||
(entriesSent != entriesReceived)) {
|
||||
Thread.sleep(100);
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail("An error occured sending the message with the roster");
|
||||
}
|
||||
assertEquals(
|
||||
"Number of sent and received entries does not match",
|
||||
entriesSent,
|
||||
entriesReceived);
|
||||
}
|
||||
|
||||
/**
|
||||
* High level API test.
|
||||
* 1. User_1 will send his/her roster to user_2
|
||||
* 2. User_2 will automatically add the entries that receives to his/her roster in the
|
||||
* corresponding group
|
||||
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
|
||||
* something is wrong
|
||||
*/
|
||||
public void testSendAndAcceptRoster() {
|
||||
RosterExchangeManager rosterExchangeManager1 = new RosterExchangeManager(getConnection(0));
|
||||
RosterExchangeManager rosterExchangeManager2 = new RosterExchangeManager(getConnection(1));
|
||||
|
||||
// Create a RosterExchangeListener that will accept all the received roster entries
|
||||
RosterExchangeListener rosterExchangeListener = new RosterExchangeListener() {
|
||||
public void entriesReceived(String from, Iterator<RemoteRosterEntry> remoteRosterEntries) {
|
||||
int received = 0;
|
||||
assertNotNull("From is null", from);
|
||||
assertNotNull("remoteRosterEntries is null", remoteRosterEntries);
|
||||
assertTrue("Roster without entries", remoteRosterEntries.hasNext());
|
||||
while (remoteRosterEntries.hasNext()) {
|
||||
received++;
|
||||
try {
|
||||
RemoteRosterEntry remoteRosterEntry = remoteRosterEntries.next();
|
||||
getConnection(1).getRoster().createEntry(
|
||||
remoteRosterEntry.getUser(),
|
||||
remoteRosterEntry.getName(),
|
||||
remoteRosterEntry.getGroupArrayNames());
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.toString());
|
||||
}
|
||||
}
|
||||
entriesReceived = received;
|
||||
}
|
||||
};
|
||||
rosterExchangeManager2.addRosterListener(rosterExchangeListener);
|
||||
|
||||
// Send user1's roster to user2
|
||||
try {
|
||||
entriesSent = getConnection(0).getRoster().getEntryCount();
|
||||
entriesReceived = 0;
|
||||
rosterExchangeManager1.send(getConnection(0).getRoster(), getBareJID(1));
|
||||
// Wait up to 2 seconds
|
||||
long initial = System.currentTimeMillis();
|
||||
while (System.currentTimeMillis() - initial < 2000 &&
|
||||
(entriesSent != entriesReceived)) {
|
||||
Thread.sleep(100);
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail("An error occured sending the message with the roster");
|
||||
}
|
||||
assertEquals(
|
||||
"Number of sent and received entries does not match",
|
||||
entriesSent,
|
||||
entriesReceived);
|
||||
assertTrue("Roster2 has no entries", getConnection(1).getRoster().getEntryCount() > 0);
|
||||
}
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
try {
|
||||
getConnection(0).getRoster().createEntry(
|
||||
getBareJID(2),
|
||||
"gato5",
|
||||
new String[] { "Friends, Coworker" });
|
||||
getConnection(0).getRoster().createEntry(getBareJID(3), "gato6", null);
|
||||
Thread.sleep(100);
|
||||
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smackx.packet.RosterExchangeTest;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
*
|
||||
* Test suite that runs all the Roster Exchange extension tests
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class RosterExchangeTests {
|
||||
|
||||
public static Test suite() {
|
||||
TestSuite suite = new TestSuite("High and low level API tests for roster exchange extension");
|
||||
//$JUnit-BEGIN$
|
||||
suite.addTest(new TestSuite(RosterExchangeManagerTest.class));
|
||||
suite.addTest(new TestSuite(RosterExchangeTest.class));
|
||||
//$JUnit-END$
|
||||
return suite;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,150 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.packet.DiscoverInfo;
|
||||
import org.jivesoftware.smackx.packet.DiscoverInfo.Identity;
|
||||
|
||||
|
||||
/**
|
||||
* Tests the service discovery functionality.
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class ServiceDiscoveryManagerTest extends SmackTestCase {
|
||||
|
||||
public ServiceDiscoveryManagerTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests info discovery of a Smack client.
|
||||
*/
|
||||
public void testSmackInfo() {
|
||||
|
||||
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager
|
||||
.getInstanceFor(getConnection(0));
|
||||
try {
|
||||
// Discover the information of another Smack client
|
||||
DiscoverInfo info = discoManager.discoverInfo(getFullJID(1));
|
||||
// Check the identity of the Smack client
|
||||
Iterator<Identity> identities = info.getIdentities();
|
||||
assertTrue("No identities were found", identities.hasNext());
|
||||
Identity identity = identities.next();
|
||||
assertEquals("Name in identity is wrong", discoManager.getIdentityName(),
|
||||
identity.getName());
|
||||
assertEquals("Category in identity is wrong", "client", identity.getCategory());
|
||||
assertEquals("Type in identity is wrong", discoManager.getIdentityType(),
|
||||
identity.getType());
|
||||
assertFalse("More identities were found", identities.hasNext());
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that ensures that Smack answers a 404 error when the disco#info includes a node.
|
||||
*/
|
||||
public void testInfoWithNode() {
|
||||
|
||||
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager
|
||||
.getInstanceFor(getConnection(0));
|
||||
try {
|
||||
// Discover the information of another Smack client
|
||||
discoManager.discoverInfo(getFullJID(1), "some node");
|
||||
// Check the identity of the Smack client
|
||||
fail("Unexpected identities were returned instead of a 404 error");
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
assertEquals("Incorrect error", 404, e.getXMPPError().getCode());
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests service discovery of XHTML support.
|
||||
*/
|
||||
public void testXHTMLFeature() {
|
||||
// Check for local XHTML service support
|
||||
// By default the XHTML service support is enabled in all the connections
|
||||
assertTrue(XHTMLManager.isServiceEnabled(getConnection(0)));
|
||||
assertTrue(XHTMLManager.isServiceEnabled(getConnection(1)));
|
||||
// Check for XHTML support in connection1 from connection2
|
||||
// Must specify a full JID and not a bare JID. Ensure that the server is working ok.
|
||||
assertFalse(XHTMLManager.isServiceEnabled(getConnection(1), getBareJID(0)));
|
||||
// Using a full JID check that the other client supports XHTML.
|
||||
assertTrue(XHTMLManager.isServiceEnabled(getConnection(1), getFullJID(0)));
|
||||
|
||||
// Disable the XHTML Message support in connection1
|
||||
XHTMLManager.setServiceEnabled(getConnection(0), false);
|
||||
// Check for local XHTML service support
|
||||
assertFalse(XHTMLManager.isServiceEnabled(getConnection(0)));
|
||||
assertTrue(XHTMLManager.isServiceEnabled(getConnection(1)));
|
||||
// Check for XHTML support in connection1 from connection2
|
||||
assertFalse(XHTMLManager.isServiceEnabled(getConnection(1), getFullJID(0)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests support for publishing items to another entity.
|
||||
*/
|
||||
public void testDiscoverPublishItemsSupport() {
|
||||
try {
|
||||
boolean canPublish = ServiceDiscoveryManager.getInstanceFor(getConnection(0))
|
||||
.canPublishItems(getServiceName());
|
||||
assertFalse("Wildfire does not support publishing...so far!!", canPublish);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests publishing items to another entity.
|
||||
*/
|
||||
/*public void testPublishItems() {
|
||||
DiscoverItems itemsToPublish = new DiscoverItems();
|
||||
DiscoverItems.Item itemToPublish = new DiscoverItems.Item("pubsub.shakespeare.lit");
|
||||
itemToPublish.setName("Avatar");
|
||||
itemToPublish.setNode("romeo/avatar");
|
||||
itemToPublish.setAction(DiscoverItems.Item.UPDATE_ACTION);
|
||||
itemsToPublish.addItem(itemToPublish);
|
||||
|
||||
try {
|
||||
ServiceDiscoveryManager.getInstanceFor(getConnection(0)).publishItems(getServiceName(),
|
||||
itemsToPublish);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
|
||||
}*/
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Test cases for getting the shared groups of a user.<p>
|
||||
*
|
||||
* Important note: This functionality is not part of the XMPP spec and it will only work
|
||||
* with Wildfire.
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class SharedGroupsTest extends SmackTestCase {
|
||||
|
||||
public SharedGroupsTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
public void testGetUserSharedGroups() throws XMPPException {
|
||||
List<String> groups = SharedGroupManager.getSharedGroups(getConnection(0));
|
||||
|
||||
assertNotNull("User groups was null", groups);
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
167
integration-test/org/jivesoftware/smackx/VCardTest.java
Normal file
167
integration-test/org/jivesoftware/smackx/VCardTest.java
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smack.util.StringUtils;
|
||||
import org.jivesoftware.smackx.packet.VCard;
|
||||
|
||||
/**
|
||||
* Created by IntelliJ IDEA.
|
||||
* User: Gaston
|
||||
* Date: Jun 18, 2005
|
||||
* Time: 1:29:30 AM
|
||||
* To change this template use File | Settings | File Templates.
|
||||
*/
|
||||
public class VCardTest extends SmackTestCase {
|
||||
|
||||
public VCardTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
public void testBigFunctional() throws XMPPException {
|
||||
VCard origVCard = new VCard();
|
||||
|
||||
origVCard.setFirstName("kir");
|
||||
origVCard.setLastName("max");
|
||||
origVCard.setEmailHome("foo@fee.bar");
|
||||
origVCard.setEmailWork("foo@fee.www.bar");
|
||||
|
||||
origVCard.setJabberId("jabber@id.org");
|
||||
origVCard.setOrganization("Jetbrains, s.r.o");
|
||||
origVCard.setNickName("KIR");
|
||||
|
||||
origVCard.setField("TITLE", "Mr");
|
||||
origVCard.setAddressFieldHome("STREET", "Some street & House");
|
||||
origVCard.setAddressFieldWork("STREET", "Some street work");
|
||||
|
||||
origVCard.setPhoneWork("FAX", "3443233");
|
||||
origVCard.setPhoneHome("VOICE", "3443233");
|
||||
|
||||
origVCard.save(getConnection(0));
|
||||
|
||||
VCard loaded = new VCard();
|
||||
try {
|
||||
loaded.load(getConnection(0));
|
||||
} catch (XMPPException e) {
|
||||
e.printStackTrace();
|
||||
fail(e.getMessage());
|
||||
}
|
||||
|
||||
assertEquals("Should load own VCard successfully", origVCard, loaded);
|
||||
|
||||
loaded = new VCard();
|
||||
try {
|
||||
loaded.load(getConnection(1), getBareJID(0));
|
||||
} catch (XMPPException e) {
|
||||
e.printStackTrace();
|
||||
fail(e.getMessage());
|
||||
}
|
||||
|
||||
assertEquals("Should load another user's VCard successfully", origVCard, loaded);
|
||||
}
|
||||
|
||||
public void testBinaryAvatar() throws Throwable {
|
||||
VCard card = new VCard();
|
||||
card.setAvatar(getAvatarBinary());
|
||||
card.save(getConnection(0));
|
||||
|
||||
VCard loaded = new VCard();
|
||||
try {
|
||||
loaded.load(getConnection(0));
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
e.printStackTrace();
|
||||
fail(e.getMessage());
|
||||
}
|
||||
|
||||
byte[] initialAvatar = card.getAvatar();
|
||||
byte[] loadedAvatar = loaded.getAvatar();
|
||||
assertEquals("Should load own Avatar successfully", initialAvatar, loadedAvatar);
|
||||
|
||||
loaded = new VCard();
|
||||
try {
|
||||
loaded.load(getConnection(1), getBareJID(0));
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
e.printStackTrace();
|
||||
fail(e.getMessage());
|
||||
}
|
||||
|
||||
assertEquals("Should load avatar successfully", card.getAvatar(), loaded.getAvatar());
|
||||
}
|
||||
|
||||
public static byte[] getAvatarBinary() {
|
||||
return StringUtils.decodeBase64(getAvatarEncoded());
|
||||
}
|
||||
|
||||
public static String getAvatarEncoded() {
|
||||
return "/9j/4AAQSkZJRgABAQEASABIAAD/4QAWRXhpZgAATU0AKgAAAAgAAAAAAAD/2wBDAAUDBAQEAwUE\n" +
|
||||
"BAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/\n" +
|
||||
"2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e\n" +
|
||||
"Hh4eHh4eHh4eHh7/wAARCABQAFADASIAAhEBAxEB/8QAHAAAAgIDAQEAAAAAAAAAAAAABwgFBgID\n" +
|
||||
"BAkB/8QAORAAAgEDAwIDBwIDBwUAAAAAAQIDBAURAAYSITEHE0EIFBUiMlFxYbEjUqEkQoGR0eHw\n" +
|
||||
"M0NicsH/xAAZAQADAQEBAAAAAAAAAAAAAAACAwQBAAX/xAAgEQACAgMAAwADAAAAAAAAAAAAAQIR\n" +
|
||||
"AxIhBBMxMmGR/9oADAMBAAIRAxEAPwDOor6ir6RqwhH0hfX9fx++t1FbGmYRUyEg4A6k5Ot9staw\n" +
|
||||
"ny4FP8R+RDNkE9s6s1TR2yzW0190QVGOiq/0k/bj21Ko2/0Miv6bKSOKyW1aeAqzjq5B+pvXXKdy\n" +
|
||||
"BRyYkYOqVd9xw1crSQWiCKnXIXCDl/nj9tUu80016u8dPPdKyC3ypzMMT4ZmGAUz9hkHJz3xqlTa\n" +
|
||||
"4ilRk/oYJd8WunJjlr6NJT2RplB/fWUO7AwBDhhjIIPTVSsXhltF6FXlslLKGHzNLlmb9e+uC8bC\n" +
|
||||
"t9muNHJa2qKeJ5eJhErFGABbA69Ppx+M6KUnR3Y/UFa17pilK8I5JSTjIIA/rqJ3TYWeve8UlH5a\n" +
|
||||
"VKjzgGGCw7N+cd/wNDykNdBKI5KgD5sjI6aJW3qyueDyJI/MjIwSDlW/00vdPjMyRlVFMqoOMhjZ\n" +
|
||||
"WR/5WGD/AIffUVUUoZ8EaIlDQJXVr0VTGfLlbA/8WJ6ah9zbdms1XGkh5JMnJGx9uhB/UHQShy0T\n" +
|
||||
"X2iatSxSX96RXTIYRL64Oev761+L7UduTlc3ZII8BEHdjj0GrPZbRTVV5MskKJ5vE5Ax17Hr/wA9\n" +
|
||||
"NUv2p57BtHbluul4q55qjzpFo7fM4Z6h1CgovqEGQWbOACO5KqdriDxy1fQSVO8DXF4LfZ3SmQdW\n" +
|
||||
"diCfX0H21Xqu+Ri726oWadY3ZgyDDBBhcgEfc4z+NBi7XGqula9VVPlmJIUdFQfZR6D/AIdc8Ukk\n" +
|
||||
"MqSxO0ciMGR1OCpHYg+h0aib7h69rCoa2RK7FSVGVHpqq+KNS1NV2aGeOsZ0qTxkhcqEVhxYnH5H\n" +
|
||||
"X0xoXeDfjlNZsWnejz1dGSiwV0cYaSEDCkSAYLrj5uXV8g/VkYZyJbRfrRDdqCWiudG2QskTpLFK\n" +
|
||||
"uSGAIJBwQR+Rps6cEGpbWAzdFpv07T8I63hEAIwwPXPc4Hr+dTnh8246CzPdUmm8mneNJ6eo+vkx\n" +
|
||||
"IIH3HTP40cK+009SvvMYCiTv9gfXX21USUswWWKCcN0yy9QNI1oZJ7dIinSasus7UsL8iiuxxhQD\n" +
|
||||
"+v37nXd4g2mtjstFVVlQ0s5qWV1KBRllznH7/jVlsdsaTckwY8YXwf0C46n/AC1xeLknvtdQW2PJ\n" +
|
||||
"bLSOq+nLB/Yf10VtRaJH+RYLrZaSyxz1k9XFT0VPG0ss8zBI4kUFmLMegUKCST0AGvNvxs35W+JH\n" +
|
||||
"iRdN0VUk3u8r+TQRSEjyaZOka8eTBSR8zBTjm7kd9Nr7fPiDd7LsW0bZs881Ku4pJxWzxS8S1PEq\n" +
|
||||
"coCMZw5mXJBHRCpyHI0i2iquAXfSV2rYLnuW8xWq1QiSaTqzMcJEg7u59FGf2AySASJv3wVu1ktE\n" +
|
||||
"V0sM816jBVJ6dIP46HAHNVBPJS2eg6qCPqALC5+DO2327sVLpMh9+uwWpIDdocfwh0JByCWz0Pz4\n" +
|
||||
"PbRXscVQLYWqj8zDOMems7ZbHxl69m+iOa6fiFf8L+Fe/VPw/wA/3j3XzW8nzePHzOGccuPTljOO\n" +
|
||||
"mmO8TPDSy7qc1dseC1Xnk7M6wgRVGcn+IB2bkf8AqDJwTkN0wud5oJrVd622VDxvNR1EkEjRklSy\n" +
|
||||
"MVJGQDjI+w0TVE08cofQneylfrlafF2gt9NXSQ2+5RzR11PnMc4SGR05A+oYDBHUZIzhiC5lPV07\n" +
|
||||
"SBlmHQ9j/rpV/ZB2tSXw7pu3u6SXS1rS+5yN1KLJ53mADsCQijPfGR2Jywe3qoeeUcYcdMY7aXKT\n" +
|
||||
"TLfGxp47YSTc/crcayni8xuisxOPxqFo6ee43ISVEhWpq34tIf8Atqx/c6kaFTLZ5CygoHQnp07j\n" +
|
||||
"UxV0kFPNNIsfFoqlXBX8jQyl0kyJKXBS/boqZrpZtk3CKCY00T1sckvA8UZxAUUnsCQjED14t9jp\n" +
|
||||
"W9ej1bbrbuKxVtnvlFFWUFbmOaGQfKQT0P3BBAIIwQQCCCAdKn4kezjuayxz3Pacvx+2qSwp8BKy\n" +
|
||||
"NfmOOPaXACjK4ZmPRNV5MTXUIj8Iza/jfclaODdlL8QiUn+1UyKk3949U6I390dOOAM/MdT27vaF\n" +
|
||||
"5U4ptq2Tjzw0k9xHUd8qqI3/AKnkW+44+ugPV01RR1c1JVwS09RBI0csUqFXjdTgqwPUEEEEHWrS\n" +
|
||||
"KH+/JVWXCbxM3nJVvULdhGWYkKtPGVUfYZUnA/Uk6gNxXu5bguJuN2mjnqigRpFgSMsB25cAMnHT\n" +
|
||||
"J64AHYDVs234Q75vfkyfDIrbTy8szXCdYfLxn6kyZBkjA+X1B7ddWOP2e94StxhvO25TnrwqJiF/\n" +
|
||||
"J8rWnOOWa7ZXtgeMO/djW2ntW3rnSwW2Kfz3pGoICs7Egt5j8PMbIAXPLkFAAIwMNB4d7xsW/bdS\n" +
|
||||
"3iyAwVYZYq+hZ8yUrkdc/wAynB4t2IB7EMoTbeG3rjtXctbt+6iL3ujcK5ifmjggMrKfsVIIyAev\n" +
|
||||
"UA5GurZ28dwbRW5fAK+Sje40vu0siMQyDkDzTrgSABlDd1DtjBIIySs7HkeN9HFvftPeGFjWp2/D\n" +
|
||||
"T326SU8oV6yhghemkYYzwZpVLAHI5YwcZBIIJLuyN5WDxB2jJubbVX59FUModJFCy08gC8opFyeL\n" +
|
||||
"rkZGSCCCCVIJ8vdO97EsZtfgZWS148lbjeZZ6Y8gecYSKItgHp88bjBwemexBIuKF3bCZMDTgggg\n" +
|
||||
"GZSNStuhLRlyAAGP9P8AfOoKW6Udbeqe38i0kANQwHoFHrq0WpG9yp+fdkBb8nrr1GhexDbk2zaN\n" +
|
||||
"x0vul8tlHcaZG8xI6qBZVVwCOYDAjOCRn9Toe1GwNsWyqBpduWihqkBaKogoo43AIwcMoBHQkaNP\n" +
|
||||
"lgxYx6ai9xWb4lQfwQBURLyjP3HqupM2NfUPwZNWAi4WmvimKxvLxB6FW1O7XpK1VXzeROe7tqSq\n" +
|
||||
"/PilaGWNkkU4ZWHUayo5nV8Fv8MakU2uHr+1uIvHtW+Hl5oNy1G+6fFZaK4RLO0a/NRyKixgOP5W\n" +
|
||||
"4jD9snicHiWBGvTnaFtnnmSeZCsQIKgj6v8AbV5jlDS1AXsqBRqqGJyVs8bM0pcEL9mz2e7pvivi\n" +
|
||||
"3BvCirLZteMLLDHKjRS3QlQyiPsRCQQTIO4PFDnLI9NBZKKgpaCjtdPDR0YaPhBGgRI1UfKiqOgA\n" +
|
||||
"CgADtrKoqPLpKaXPVXUdPtnXTNUBLlTQR4xHlj+gHT/7pjw8oTsf/9k=";
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
67
integration-test/org/jivesoftware/smackx/VersionTest.java
Normal file
67
integration-test/org/jivesoftware/smackx/VersionTest.java
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smack.PacketCollector;
|
||||
import org.jivesoftware.smack.filter.PacketIDFilter;
|
||||
import org.jivesoftware.smack.packet.IQ;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.packet.Version;
|
||||
|
||||
/**
|
||||
* Test case to ensure that Smack is able to get and parse correctly iq:version packets.
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class VersionTest extends SmackTestCase {
|
||||
|
||||
public VersionTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the version of the server and make sure that all the required data is present
|
||||
*
|
||||
* Note: This test expects the server to answer an iq:version packet.
|
||||
*/
|
||||
public void testGetServerVersion() {
|
||||
Version version = new Version();
|
||||
version.setType(IQ.Type.GET);
|
||||
version.setTo(getServiceName());
|
||||
|
||||
// Create a packet collector to listen for a response.
|
||||
PacketCollector collector = getConnection(0).createPacketCollector(new PacketIDFilter(version.getPacketID()));
|
||||
|
||||
getConnection(0).sendPacket(version);
|
||||
|
||||
// Wait up to 5 seconds for a result.
|
||||
IQ result = (IQ)collector.nextResult(5000);
|
||||
// Close the collector
|
||||
collector.cancel();
|
||||
|
||||
assertNotNull("No result from the server", result);
|
||||
|
||||
assertEquals("Incorrect result type", IQ.Type.RESULT, result.getType());
|
||||
assertNotNull("No name specified in the result", ((Version)result).getName());
|
||||
assertNotNull("No version specified in the result", ((Version)result).getVersion());
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
234
integration-test/org/jivesoftware/smackx/XHTMLManagerTest.java
Normal file
234
integration-test/org/jivesoftware/smackx/XHTMLManagerTest.java
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.jivesoftware.smack.*;
|
||||
import org.jivesoftware.smack.filter.ThreadFilter;
|
||||
import org.jivesoftware.smack.packet.*;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
|
||||
/**
|
||||
* Test the XHTML extension using the high level API
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class XHTMLManagerTest extends SmackTestCase {
|
||||
|
||||
private int bodiesSent;
|
||||
private int bodiesReceived;
|
||||
|
||||
/**
|
||||
* Constructor for XHTMLManagerTest.
|
||||
* @param name
|
||||
*/
|
||||
public XHTMLManagerTest(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* High level API test.
|
||||
* This is a simple test to use with a XMPP client and check if the client receives the message
|
||||
* 1. User_1 will send a message with formatted text (XHTML) to user_2
|
||||
*/
|
||||
public void testSendSimpleXHTMLMessage() {
|
||||
// User1 creates a chat with user2
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
|
||||
// User1 creates a message to send to user2
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("Hey John, this is my new green!!!!");
|
||||
|
||||
// Create an XHTMLText to send with the message
|
||||
XHTMLText xhtmlText = new XHTMLText(null, null);
|
||||
xhtmlText.appendOpenParagraphTag("font-size:large");
|
||||
xhtmlText.append("Hey John, this is my new ");
|
||||
xhtmlText.appendOpenSpanTag("color:green");
|
||||
xhtmlText.append("green");
|
||||
xhtmlText.appendCloseSpanTag();
|
||||
xhtmlText.appendOpenEmTag();
|
||||
xhtmlText.append("!!!!");
|
||||
xhtmlText.appendCloseEmTag();
|
||||
xhtmlText.appendCloseParagraphTag();
|
||||
// Add the XHTML text to the message
|
||||
XHTMLManager.addBody(msg, xhtmlText.toString());
|
||||
|
||||
// User1 sends the message that contains the XHTML to user2
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
Thread.sleep(200);
|
||||
} catch (Exception e) {
|
||||
fail("An error occured sending the message with XHTML");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* High level API test.
|
||||
* 1. User_1 will send a message with XHTML to user_2
|
||||
* 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything
|
||||
* is fine
|
||||
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
|
||||
* something is wrong
|
||||
*/
|
||||
public void testSendSimpleXHTMLMessageAndDisplayReceivedXHTMLMessage() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
final PacketCollector chat2 = getConnection(1).createPacketCollector(
|
||||
new ThreadFilter(chat1.getThreadID()));
|
||||
|
||||
// User1 creates a message to send to user2
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("Hey John, this is my new green!!!!");
|
||||
|
||||
// Create an XHTMLText to send with the message
|
||||
XHTMLText xhtmlText = new XHTMLText(null, null);
|
||||
xhtmlText.appendOpenParagraphTag("font-size:large");
|
||||
xhtmlText.append("Hey John, this is my new ");
|
||||
xhtmlText.appendOpenSpanTag("color:green");
|
||||
xhtmlText.append("green");
|
||||
xhtmlText.appendCloseSpanTag();
|
||||
xhtmlText.appendOpenEmTag();
|
||||
xhtmlText.append("!!!!");
|
||||
xhtmlText.appendCloseEmTag();
|
||||
xhtmlText.appendCloseParagraphTag();
|
||||
// Add the XHTML text to the message
|
||||
XHTMLManager.addBody(msg, xhtmlText.toString());
|
||||
|
||||
// User1 sends the message that contains the XHTML to user2
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
} catch (Exception e) {
|
||||
fail("An error occured sending the message with XHTML");
|
||||
}
|
||||
|
||||
Packet packet = chat2.nextResult(2000);
|
||||
Message message = (Message) packet;
|
||||
assertTrue(
|
||||
"The received message is not an XHTML Message",
|
||||
XHTMLManager.isXHTMLMessage(message));
|
||||
try {
|
||||
assertTrue(
|
||||
"Message without XHTML bodies",
|
||||
XHTMLManager.getBodies(message).hasNext());
|
||||
for (Iterator<String> it = XHTMLManager.getBodies(message); it.hasNext();) {
|
||||
String body = it.next();
|
||||
System.out.println(body);
|
||||
}
|
||||
}
|
||||
catch (ClassCastException e) {
|
||||
fail("ClassCastException - Most probable cause is that smack providers is misconfigured");
|
||||
}
|
||||
assertNotNull("No reply received", msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Low level API test. Test a message with two XHTML bodies and several XHTML tags.
|
||||
* 1. User_1 will send a message with XHTML to user_2
|
||||
* 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything
|
||||
* is fine
|
||||
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
|
||||
* something is wrong
|
||||
*/
|
||||
public void testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
final PacketCollector chat2 = getConnection(1).createPacketCollector(
|
||||
new ThreadFilter(chat1.getThreadID()));
|
||||
|
||||
// User1 creates a message to send to user2
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody(
|
||||
"awesome! As Emerson once said: A foolish consistency is the hobgoblin of little minds.");
|
||||
|
||||
// Create an XHTMLText to send with the message (in Spanish)
|
||||
XHTMLText xhtmlText = new XHTMLText(null, "es-ES");
|
||||
xhtmlText.appendOpenHeaderTag(1, null);
|
||||
xhtmlText.append("impresionante!");
|
||||
xhtmlText.appendCloseHeaderTag(1);
|
||||
xhtmlText.appendOpenParagraphTag(null);
|
||||
xhtmlText.append("Como Emerson dijo una vez:");
|
||||
xhtmlText.appendCloseParagraphTag();
|
||||
xhtmlText.appendOpenBlockQuoteTag(null);
|
||||
xhtmlText.appendOpenParagraphTag(null);
|
||||
xhtmlText.append("Una consistencia ridícula es el espantajo de mentes pequeñas.");
|
||||
xhtmlText.appendCloseParagraphTag();
|
||||
xhtmlText.appendCloseBlockQuoteTag();
|
||||
// Add the XHTML text to the message
|
||||
XHTMLManager.addBody(msg, xhtmlText.toString());
|
||||
|
||||
// Create an XHTMLText to send with the message (in English)
|
||||
xhtmlText = new XHTMLText(null, "en-US");
|
||||
xhtmlText.appendOpenHeaderTag(1, null);
|
||||
xhtmlText.append("awesome!");
|
||||
xhtmlText.appendCloseHeaderTag(1);
|
||||
xhtmlText.appendOpenParagraphTag(null);
|
||||
xhtmlText.append("As Emerson once said:");
|
||||
xhtmlText.appendCloseParagraphTag();
|
||||
xhtmlText.appendOpenBlockQuoteTag(null);
|
||||
xhtmlText.appendOpenParagraphTag(null);
|
||||
xhtmlText.append("A foolish consistency is the hobgoblin of little minds.");
|
||||
xhtmlText.appendCloseParagraphTag();
|
||||
xhtmlText.appendCloseBlockQuoteTag();
|
||||
// Add the XHTML text to the message
|
||||
XHTMLManager.addBody(msg, xhtmlText.toString());
|
||||
|
||||
// User1 sends the message that contains the XHTML to user2
|
||||
try {
|
||||
bodiesSent = 2;
|
||||
bodiesReceived = 0;
|
||||
chat1.sendMessage(msg);
|
||||
} catch (Exception e) {
|
||||
fail("An error occured sending the message with XHTML");
|
||||
}
|
||||
|
||||
Packet packet = chat2.nextResult(2000);
|
||||
int received = 0;
|
||||
Message message = (Message) packet;
|
||||
assertTrue(
|
||||
"The received message is not an XHTML Message",
|
||||
XHTMLManager.isXHTMLMessage(message));
|
||||
try {
|
||||
assertTrue(
|
||||
"Message without XHTML bodies",
|
||||
XHTMLManager.getBodies(message).hasNext());
|
||||
for (Iterator<String> it = XHTMLManager.getBodies(message); it.hasNext();) {
|
||||
received++;
|
||||
String body = it.next();
|
||||
System.out.println(body);
|
||||
}
|
||||
bodiesReceived = received;
|
||||
}
|
||||
catch (ClassCastException e) {
|
||||
fail("ClassCastException - Most probable cause is that smack providers" +
|
||||
"is misconfigured");
|
||||
}
|
||||
assertEquals(
|
||||
"Number of sent and received XHTMP bodies does not match",
|
||||
bodiesSent,
|
||||
bodiesReceived);
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx;
|
||||
|
||||
import org.jivesoftware.smackx.packet.XHTMLExtensionTest;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Test suite that runs all the XHTML support tests
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class XHTMLSupportTests {
|
||||
|
||||
public static Test suite() {
|
||||
TestSuite suite = new TestSuite("High and low level API tests for XHTML support");
|
||||
//$JUnit-BEGIN$
|
||||
suite.addTest(new TestSuite(XHTMLManagerTest.class));
|
||||
suite.addTest(new TestSuite(XHTMLExtensionTest.class));
|
||||
//$JUnit-END$
|
||||
return suite;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,259 @@
|
|||
/**
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.bytestreams.ibb;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.SynchronousQueue;
|
||||
|
||||
import org.jivesoftware.smack.Connection;
|
||||
import org.jivesoftware.smack.PacketCollector;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.filter.PacketIDFilter;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.jivesoftware.smack.packet.XMPPError;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamListener;
|
||||
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamManager;
|
||||
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamRequest;
|
||||
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamSession;
|
||||
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamManager.StanzaType;
|
||||
import org.jivesoftware.smackx.bytestreams.ibb.packet.Open;
|
||||
|
||||
/**
|
||||
* Test for In-Band Bytestreams with real XMPP servers.
|
||||
*
|
||||
* @author Henning Staib
|
||||
*/
|
||||
public class InBandBytestreamTest extends SmackTestCase {
|
||||
|
||||
/* the amount of data transmitted in each test */
|
||||
int dataSize = 1024000;
|
||||
|
||||
public InBandBytestreamTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Target should respond with not-acceptable error if no listeners for incoming In-Band
|
||||
* Bytestream requests are registered.
|
||||
*
|
||||
* @throws XMPPException should not happen
|
||||
*/
|
||||
public void testRespondWithErrorOnInBandBytestreamRequest() throws XMPPException {
|
||||
Connection targetConnection = getConnection(0);
|
||||
|
||||
Connection initiatorConnection = getConnection(1);
|
||||
|
||||
Open open = new Open("sessionID", 1024);
|
||||
open.setFrom(initiatorConnection.getUser());
|
||||
open.setTo(targetConnection.getUser());
|
||||
|
||||
PacketCollector collector = initiatorConnection.createPacketCollector(new PacketIDFilter(
|
||||
open.getPacketID()));
|
||||
initiatorConnection.sendPacket(open);
|
||||
Packet result = collector.nextResult();
|
||||
|
||||
assertNotNull(result.getError());
|
||||
assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition());
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* An In-Band Bytestream should be successfully established using IQ stanzas.
|
||||
*
|
||||
* @throws Exception should not happen
|
||||
*/
|
||||
public void testInBandBytestreamWithIQStanzas() throws Exception {
|
||||
|
||||
Connection initiatorConnection = getConnection(0);
|
||||
Connection targetConnection = getConnection(1);
|
||||
|
||||
// test data
|
||||
Random rand = new Random();
|
||||
final byte[] data = new byte[dataSize];
|
||||
rand.nextBytes(data);
|
||||
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
|
||||
|
||||
InBandBytestreamManager targetByteStreamManager = InBandBytestreamManager.getByteStreamManager(targetConnection);
|
||||
|
||||
InBandBytestreamListener incomingByteStreamListener = new InBandBytestreamListener() {
|
||||
|
||||
public void incomingBytestreamRequest(InBandBytestreamRequest request) {
|
||||
InputStream inputStream;
|
||||
try {
|
||||
inputStream = request.accept().getInputStream();
|
||||
byte[] receivedData = new byte[dataSize];
|
||||
int totalRead = 0;
|
||||
while (totalRead < dataSize) {
|
||||
int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
|
||||
totalRead += read;
|
||||
}
|
||||
queue.put(receivedData);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
|
||||
|
||||
InBandBytestreamManager initiatorByteStreamManager = InBandBytestreamManager.getByteStreamManager(initiatorConnection);
|
||||
|
||||
OutputStream outputStream = initiatorByteStreamManager.establishSession(
|
||||
targetConnection.getUser()).getOutputStream();
|
||||
|
||||
// verify stream
|
||||
outputStream.write(data);
|
||||
outputStream.flush();
|
||||
outputStream.close();
|
||||
|
||||
assertEquals("received data not equal to sent data", data, queue.take());
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* An In-Band Bytestream should be successfully established using message stanzas.
|
||||
*
|
||||
* @throws Exception should not happen
|
||||
*/
|
||||
public void testInBandBytestreamWithMessageStanzas() throws Exception {
|
||||
|
||||
Connection initiatorConnection = getConnection(0);
|
||||
Connection targetConnection = getConnection(1);
|
||||
|
||||
// test data
|
||||
Random rand = new Random();
|
||||
final byte[] data = new byte[dataSize];
|
||||
rand.nextBytes(data);
|
||||
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
|
||||
|
||||
InBandBytestreamManager targetByteStreamManager = InBandBytestreamManager.getByteStreamManager(targetConnection);
|
||||
|
||||
InBandBytestreamListener incomingByteStreamListener = new InBandBytestreamListener() {
|
||||
|
||||
public void incomingBytestreamRequest(InBandBytestreamRequest request) {
|
||||
InputStream inputStream;
|
||||
try {
|
||||
inputStream = request.accept().getInputStream();
|
||||
byte[] receivedData = new byte[dataSize];
|
||||
int totalRead = 0;
|
||||
while (totalRead < dataSize) {
|
||||
int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
|
||||
totalRead += read;
|
||||
}
|
||||
queue.put(receivedData);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
|
||||
|
||||
InBandBytestreamManager initiatorByteStreamManager = InBandBytestreamManager.getByteStreamManager(initiatorConnection);
|
||||
initiatorByteStreamManager.setStanza(StanzaType.MESSAGE);
|
||||
|
||||
OutputStream outputStream = initiatorByteStreamManager.establishSession(
|
||||
targetConnection.getUser()).getOutputStream();
|
||||
|
||||
// verify stream
|
||||
outputStream.write(data);
|
||||
outputStream.flush();
|
||||
outputStream.close();
|
||||
|
||||
assertEquals("received data not equal to sent data", data, queue.take());
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* An In-Band Bytestream should be successfully established using IQ stanzas. The established
|
||||
* session should transfer data bidirectional.
|
||||
*
|
||||
* @throws Exception should not happen
|
||||
*/
|
||||
public void testBiDirectionalInBandBytestream() throws Exception {
|
||||
|
||||
Connection initiatorConnection = getConnection(0);
|
||||
|
||||
Connection targetConnection = getConnection(1);
|
||||
|
||||
// test data
|
||||
Random rand = new Random();
|
||||
final byte[] data = new byte[dataSize];
|
||||
rand.nextBytes(data);
|
||||
|
||||
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
|
||||
|
||||
InBandBytestreamManager targetByteStreamManager = InBandBytestreamManager.getByteStreamManager(targetConnection);
|
||||
|
||||
InBandBytestreamListener incomingByteStreamListener = new InBandBytestreamListener() {
|
||||
|
||||
public void incomingBytestreamRequest(InBandBytestreamRequest request) {
|
||||
try {
|
||||
InBandBytestreamSession session = request.accept();
|
||||
OutputStream outputStream = session.getOutputStream();
|
||||
outputStream.write(data);
|
||||
outputStream.flush();
|
||||
InputStream inputStream = session.getInputStream();
|
||||
byte[] receivedData = new byte[dataSize];
|
||||
int totalRead = 0;
|
||||
while (totalRead < dataSize) {
|
||||
int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
|
||||
totalRead += read;
|
||||
}
|
||||
queue.put(receivedData);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
|
||||
|
||||
InBandBytestreamManager initiatorByteStreamManager = InBandBytestreamManager.getByteStreamManager(initiatorConnection);
|
||||
|
||||
InBandBytestreamSession session = initiatorByteStreamManager.establishSession(targetConnection.getUser());
|
||||
|
||||
// verify stream
|
||||
byte[] receivedData = new byte[dataSize];
|
||||
InputStream inputStream = session.getInputStream();
|
||||
int totalRead = 0;
|
||||
while (totalRead < dataSize) {
|
||||
int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
|
||||
totalRead += read;
|
||||
}
|
||||
|
||||
assertEquals("sent data not equal to received data", data, receivedData);
|
||||
|
||||
OutputStream outputStream = session.getOutputStream();
|
||||
|
||||
outputStream.write(data);
|
||||
outputStream.flush();
|
||||
outputStream.close();
|
||||
|
||||
assertEquals("received data not equal to sent data", data, queue.take());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,337 @@
|
|||
/**
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.bytestreams.socks5;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.concurrent.SynchronousQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import org.jivesoftware.smack.Connection;
|
||||
import org.jivesoftware.smack.PacketCollector;
|
||||
import org.jivesoftware.smack.SmackConfiguration;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.filter.PacketIDFilter;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.jivesoftware.smack.packet.XMPPError;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.ServiceDiscoveryManager;
|
||||
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamListener;
|
||||
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamManager;
|
||||
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamRequest;
|
||||
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamSession;
|
||||
import org.jivesoftware.smackx.bytestreams.socks5.Socks5PacketUtils;
|
||||
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy;
|
||||
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream;
|
||||
|
||||
/**
|
||||
* Test for Socks5 bytestreams with real XMPP servers.
|
||||
*
|
||||
* @author Henning Staib
|
||||
*/
|
||||
public class Socks5ByteStreamTest extends SmackTestCase {
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param arg0
|
||||
*/
|
||||
public Socks5ByteStreamTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Socks5 feature should be added to the service discovery on Smack startup.
|
||||
*
|
||||
* @throws XMPPException should not happen
|
||||
*/
|
||||
public void testInitializationSocks5FeaturesAndListenerOnStartup() throws XMPPException {
|
||||
Connection connection = getConnection(0);
|
||||
|
||||
assertTrue(ServiceDiscoveryManager.getInstanceFor(connection).includesFeature(
|
||||
Socks5BytestreamManager.NAMESPACE));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Target should respond with not-acceptable error if no listeners for incoming Socks5
|
||||
* bytestream requests are registered.
|
||||
*
|
||||
* @throws XMPPException should not happen
|
||||
*/
|
||||
public void testRespondWithErrorOnSocks5BytestreamRequest() throws XMPPException {
|
||||
Connection targetConnection = getConnection(0);
|
||||
|
||||
Connection initiatorConnection = getConnection(1);
|
||||
|
||||
Bytestream bytestreamInitiation = Socks5PacketUtils.createBytestreamInitiation(
|
||||
initiatorConnection.getUser(), targetConnection.getUser(), "session_id");
|
||||
bytestreamInitiation.addStreamHost("proxy.localhost", "127.0.0.1", 7777);
|
||||
|
||||
PacketCollector collector = initiatorConnection.createPacketCollector(new PacketIDFilter(
|
||||
bytestreamInitiation.getPacketID()));
|
||||
initiatorConnection.sendPacket(bytestreamInitiation);
|
||||
Packet result = collector.nextResult();
|
||||
|
||||
assertNotNull(result.getError());
|
||||
assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition());
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Socks5 bytestream should be successfully established using the local Socks5 proxy.
|
||||
*
|
||||
* @throws Exception should not happen
|
||||
*/
|
||||
public void testSocks5BytestreamWithLocalSocks5Proxy() throws Exception {
|
||||
|
||||
// setup port for local socks5 proxy
|
||||
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
|
||||
SmackConfiguration.setLocalSocks5ProxyPort(7778);
|
||||
Socks5Proxy socks5Proxy = Socks5Proxy.getSocks5Proxy();
|
||||
socks5Proxy.start();
|
||||
|
||||
assertTrue(socks5Proxy.isRunning());
|
||||
|
||||
Connection initiatorConnection = getConnection(0);
|
||||
Connection targetConnection = getConnection(1);
|
||||
|
||||
// test data
|
||||
final byte[] data = new byte[] { 1, 2, 3 };
|
||||
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
|
||||
|
||||
Socks5BytestreamManager targetByteStreamManager = Socks5BytestreamManager.getBytestreamManager(targetConnection);
|
||||
|
||||
Socks5BytestreamListener incomingByteStreamListener = new Socks5BytestreamListener() {
|
||||
|
||||
public void incomingBytestreamRequest(Socks5BytestreamRequest request) {
|
||||
InputStream inputStream;
|
||||
try {
|
||||
Socks5BytestreamSession session = request.accept();
|
||||
inputStream = session.getInputStream();
|
||||
byte[] receivedData = new byte[3];
|
||||
inputStream.read(receivedData);
|
||||
queue.put(receivedData);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
|
||||
|
||||
Socks5BytestreamManager initiatorByteStreamManager = Socks5BytestreamManager.getBytestreamManager(initiatorConnection);
|
||||
|
||||
Socks5BytestreamSession session = initiatorByteStreamManager.establishSession(
|
||||
targetConnection.getUser());
|
||||
OutputStream outputStream = session.getOutputStream();
|
||||
|
||||
assertTrue(session.isDirect());
|
||||
|
||||
// verify stream
|
||||
outputStream.write(data);
|
||||
outputStream.flush();
|
||||
outputStream.close();
|
||||
|
||||
assertEquals("received data not equal to sent data", data, queue.take());
|
||||
|
||||
// reset default configuration
|
||||
SmackConfiguration.setLocalSocks5ProxyPort(7777);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Socks5 bytestream should be successfully established using a Socks5 proxy provided by the
|
||||
* XMPP server.
|
||||
* <p>
|
||||
* This test will fail if the XMPP server doesn't provide any Socks5 proxies or the Socks5 proxy
|
||||
* only allows Socks5 bytestreams in the context of a file transfer (like Openfire in default
|
||||
* configuration, see xmpp.proxy.transfer.required flag).
|
||||
*
|
||||
* @throws Exception if no Socks5 proxies found or proxy is unwilling to activate Socks5
|
||||
* bytestream
|
||||
*/
|
||||
public void testSocks5BytestreamWithRemoteSocks5Proxy() throws Exception {
|
||||
|
||||
// disable local socks5 proxy
|
||||
SmackConfiguration.setLocalSocks5ProxyEnabled(false);
|
||||
Socks5Proxy.getSocks5Proxy().stop();
|
||||
|
||||
assertFalse(Socks5Proxy.getSocks5Proxy().isRunning());
|
||||
|
||||
Connection initiatorConnection = getConnection(0);
|
||||
Connection targetConnection = getConnection(1);
|
||||
|
||||
// test data
|
||||
final byte[] data = new byte[] { 1, 2, 3 };
|
||||
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
|
||||
|
||||
Socks5BytestreamManager targetByteStreamManager = Socks5BytestreamManager.getBytestreamManager(targetConnection);
|
||||
|
||||
Socks5BytestreamListener incomingByteStreamListener = new Socks5BytestreamListener() {
|
||||
|
||||
public void incomingBytestreamRequest(Socks5BytestreamRequest request) {
|
||||
InputStream inputStream;
|
||||
try {
|
||||
Socks5BytestreamSession session = request.accept();
|
||||
inputStream = session.getInputStream();
|
||||
byte[] receivedData = new byte[3];
|
||||
inputStream.read(receivedData);
|
||||
queue.put(receivedData);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
|
||||
|
||||
Socks5BytestreamManager initiatorByteStreamManager = Socks5BytestreamManager.getBytestreamManager(initiatorConnection);
|
||||
|
||||
Socks5BytestreamSession session = initiatorByteStreamManager.establishSession(
|
||||
targetConnection.getUser());
|
||||
OutputStream outputStream = session.getOutputStream();
|
||||
|
||||
assertTrue(session.isMediated());
|
||||
|
||||
// verify stream
|
||||
outputStream.write(data);
|
||||
outputStream.flush();
|
||||
outputStream.close();
|
||||
|
||||
assertEquals("received data not equal to sent data", data, queue.take());
|
||||
|
||||
// reset default configuration
|
||||
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
|
||||
Socks5Proxy.getSocks5Proxy().start();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Socks5 bytestream should be successfully established using a Socks5 proxy provided by the
|
||||
* XMPP server. The established connection should transfer data bidirectional if the Socks5
|
||||
* proxy supports it.
|
||||
* <p>
|
||||
* Support for bidirectional Socks5 bytestream:
|
||||
* <ul>
|
||||
* <li>Openfire (3.6.4 and below) - no</li>
|
||||
* <li>ejabberd (2.0.5 and higher) - yes</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* This test will fail if the XMPP server doesn't provide any Socks5 proxies or the Socks5 proxy
|
||||
* only allows Socks5 bytestreams in the context of a file transfer (like Openfire in default
|
||||
* configuration, see xmpp.proxy.transfer.required flag).
|
||||
*
|
||||
* @throws Exception if no Socks5 proxies found or proxy is unwilling to activate Socks5
|
||||
* bytestream
|
||||
*/
|
||||
public void testBiDirectionalSocks5BytestreamWithRemoteSocks5Proxy() throws Exception {
|
||||
|
||||
Connection initiatorConnection = getConnection(0);
|
||||
|
||||
// disable local socks5 proxy
|
||||
SmackConfiguration.setLocalSocks5ProxyEnabled(false);
|
||||
Socks5Proxy.getSocks5Proxy().stop();
|
||||
|
||||
assertFalse(Socks5Proxy.getSocks5Proxy().isRunning());
|
||||
|
||||
Connection targetConnection = getConnection(1);
|
||||
|
||||
// test data
|
||||
final byte[] data = new byte[] { 1, 2, 3 };
|
||||
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
|
||||
|
||||
Socks5BytestreamManager targetByteStreamManager = Socks5BytestreamManager.getBytestreamManager(targetConnection);
|
||||
|
||||
Socks5BytestreamListener incomingByteStreamListener = new Socks5BytestreamListener() {
|
||||
|
||||
public void incomingBytestreamRequest(Socks5BytestreamRequest request) {
|
||||
try {
|
||||
Socks5BytestreamSession session = request.accept();
|
||||
OutputStream outputStream = session.getOutputStream();
|
||||
outputStream.write(data);
|
||||
outputStream.flush();
|
||||
InputStream inputStream = session.getInputStream();
|
||||
byte[] receivedData = new byte[3];
|
||||
inputStream.read(receivedData);
|
||||
queue.put(receivedData);
|
||||
session.close();
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
|
||||
|
||||
Socks5BytestreamManager initiatorByteStreamManager = Socks5BytestreamManager.getBytestreamManager(initiatorConnection);
|
||||
|
||||
Socks5BytestreamSession session = initiatorByteStreamManager.establishSession(targetConnection.getUser());
|
||||
|
||||
assertTrue(session.isMediated());
|
||||
|
||||
// verify stream
|
||||
final byte[] receivedData = new byte[3];
|
||||
final InputStream inputStream = session.getInputStream();
|
||||
|
||||
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
|
||||
|
||||
public Integer call() throws Exception {
|
||||
return inputStream.read(receivedData);
|
||||
}
|
||||
});
|
||||
Thread executor = new Thread(futureTask);
|
||||
executor.start();
|
||||
|
||||
try {
|
||||
futureTask.get(2000, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
catch (TimeoutException e) {
|
||||
// reset default configuration
|
||||
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
|
||||
Socks5Proxy.getSocks5Proxy().start();
|
||||
|
||||
fail("Couldn't send data from target to inititator");
|
||||
}
|
||||
|
||||
assertEquals("sent data not equal to received data", data, receivedData);
|
||||
|
||||
OutputStream outputStream = session.getOutputStream();
|
||||
|
||||
outputStream.write(data);
|
||||
outputStream.flush();
|
||||
outputStream.close();
|
||||
|
||||
assertEquals("received data not equal to sent data", data, queue.take());
|
||||
|
||||
session.close();
|
||||
|
||||
// reset default configuration
|
||||
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
|
||||
Socks5Proxy.getSocks5Proxy().start();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx.commands;
|
||||
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smackx.packet.DiscoverItems;
|
||||
import org.jivesoftware.smackx.Form;
|
||||
import org.jivesoftware.smackx.FormField;
|
||||
|
||||
/**
|
||||
* AdHocCommand tests.
|
||||
*
|
||||
* @author Matt Tucker
|
||||
*/
|
||||
public class AdHocCommandDiscoTest extends SmackTestCase {
|
||||
|
||||
/**
|
||||
* Constructor for test.
|
||||
* @param arg0 argument.
|
||||
*/
|
||||
public AdHocCommandDiscoTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
public void testAdHocCommands() {
|
||||
try {
|
||||
AdHocCommandManager manager1 = AdHocCommandManager.getAddHocCommandsManager(getConnection(0));
|
||||
manager1.registerCommand("test", "test node", LocalCommand.class);
|
||||
|
||||
manager1.registerCommand("test2", "test node", new LocalCommandFactory() {
|
||||
public LocalCommand getInstance() throws InstantiationException, IllegalAccessException {
|
||||
return new LocalCommand() {
|
||||
public boolean isLastStage() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean hasPermission(String jid) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void execute() throws XMPPException {
|
||||
Form result = new Form(Form.TYPE_RESULT);
|
||||
FormField resultField = new FormField("test2");
|
||||
resultField.setLabel("test node");
|
||||
resultField.addValue("it worked");
|
||||
result.addField(resultField);
|
||||
setForm(result);
|
||||
}
|
||||
|
||||
public void next(Form response) throws XMPPException {
|
||||
//
|
||||
}
|
||||
|
||||
public void complete(Form response) throws XMPPException {
|
||||
//
|
||||
}
|
||||
|
||||
public void prev() throws XMPPException {
|
||||
//
|
||||
}
|
||||
|
||||
public void cancel() throws XMPPException {
|
||||
//
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
AdHocCommandManager manager2 = AdHocCommandManager.getAddHocCommandsManager(getConnection(1));
|
||||
DiscoverItems items = manager2.discoverCommands(getFullJID(0));
|
||||
|
||||
assertTrue("Disco for command test failed", items.getItems().next().getNode().equals("test"));
|
||||
|
||||
RemoteCommand command = manager2.getRemoteCommand(getFullJID(0), "test2");
|
||||
command.execute();
|
||||
assertEquals("Disco for command test failed", command.getForm().getField("test2").getValues().next(), "it worked");
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,147 @@
|
|||
package org.jivesoftware.smackx.entitycaps;
|
||||
|
||||
import org.jivesoftware.smack.PacketListener;
|
||||
import org.jivesoftware.smack.SmackConfiguration;
|
||||
import org.jivesoftware.smack.XMPPConnection;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.filter.AndFilter;
|
||||
import org.jivesoftware.smack.filter.PacketTypeFilter;
|
||||
import org.jivesoftware.smack.filter.IQTypeFilter;
|
||||
import org.jivesoftware.smack.packet.IQ;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.ServiceDiscoveryManager;
|
||||
import org.jivesoftware.smackx.packet.DiscoverInfo;
|
||||
|
||||
public class EntityCapsTest extends SmackTestCase {
|
||||
|
||||
private static final String DISCOVER_TEST_FEATURE = "entityCapsTest";
|
||||
|
||||
XMPPConnection con0;
|
||||
XMPPConnection con1;
|
||||
EntityCapsManager ecm0;
|
||||
EntityCapsManager ecm1;
|
||||
ServiceDiscoveryManager sdm0;
|
||||
ServiceDiscoveryManager sdm1;
|
||||
|
||||
private boolean discoInfoSend = false;
|
||||
|
||||
public EntityCapsTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
SmackConfiguration.setAutoEnableEntityCaps(true);
|
||||
con0 = getConnection(0);
|
||||
con1 = getConnection(1);
|
||||
ecm0 = EntityCapsManager.getInstanceFor(getConnection(0));
|
||||
ecm1 = EntityCapsManager.getInstanceFor(getConnection(1));
|
||||
sdm0 = ServiceDiscoveryManager.getInstanceFor(con0);
|
||||
sdm1 = ServiceDiscoveryManager.getInstanceFor(con1);
|
||||
letsAllBeFriends();
|
||||
}
|
||||
|
||||
public void testLocalEntityCaps() throws InterruptedException {
|
||||
DiscoverInfo info = EntityCapsManager.getDiscoveryInfoByNodeVer(ecm1.getLocalNodeVer());
|
||||
assertFalse(info.containsFeature(DISCOVER_TEST_FEATURE));
|
||||
|
||||
dropWholeEntityCapsCache();
|
||||
|
||||
// This should cause a new presence stanza from con1 with and updated
|
||||
// 'ver' String
|
||||
sdm1.addFeature(DISCOVER_TEST_FEATURE);
|
||||
|
||||
// Give the server some time to handle the stanza and send it to con0
|
||||
Thread.sleep(2000);
|
||||
|
||||
// The presence stanza should get received by con0 and the data should
|
||||
// be recorded in the map
|
||||
// Note that while both connections use the same static Entity Caps
|
||||
// cache,
|
||||
// it's assured that *not* con1 added the data to the Entity Caps cache.
|
||||
// Every time the entities features
|
||||
// and identities change only a new caps 'ver' is calculated and send
|
||||
// with the presence stanza
|
||||
// The other connection has to receive this stanza and record the
|
||||
// information in order for this test to succeed.
|
||||
info = EntityCapsManager.getDiscoveryInfoByNodeVer(ecm1.getLocalNodeVer());
|
||||
assertNotNull(info);
|
||||
assertTrue(info.containsFeature(DISCOVER_TEST_FEATURE));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if entity caps actually prevent a disco info request and reply
|
||||
*
|
||||
* @throws XMPPException
|
||||
*
|
||||
*/
|
||||
public void testPreventDiscoInfo() throws XMPPException {
|
||||
con0.addPacketSendingListener(new PacketListener() {
|
||||
|
||||
@Override
|
||||
public void processPacket(Packet packet) {
|
||||
discoInfoSend = true;
|
||||
}
|
||||
|
||||
}, new AndFilter(new PacketTypeFilter(DiscoverInfo.class), new IQTypeFilter(IQ.Type.GET)));
|
||||
|
||||
// add a bogus feature so that con1 ver won't match con0's
|
||||
sdm1.addFeature(DISCOVER_TEST_FEATURE);
|
||||
|
||||
dropCapsCache();
|
||||
// discover that
|
||||
DiscoverInfo info = sdm0.discoverInfo(con1.getUser());
|
||||
// that discovery should cause a disco#info
|
||||
assertTrue(discoInfoSend);
|
||||
assertTrue(info.containsFeature(DISCOVER_TEST_FEATURE));
|
||||
discoInfoSend = false;
|
||||
|
||||
// discover that
|
||||
info = sdm0.discoverInfo(con1.getUser());
|
||||
// that discovery shouldn't cause a disco#info
|
||||
assertFalse(discoInfoSend);
|
||||
assertTrue(info.containsFeature(DISCOVER_TEST_FEATURE));
|
||||
}
|
||||
|
||||
public void testCapsChanged() {
|
||||
String nodeVerBefore = EntityCapsManager.getNodeVersionByJid(con1.getUser());
|
||||
sdm1.addFeature(DISCOVER_TEST_FEATURE);
|
||||
String nodeVerAfter = EntityCapsManager.getNodeVersionByJid(con1.getUser());
|
||||
|
||||
assertFalse(nodeVerBefore.equals(nodeVerAfter));
|
||||
}
|
||||
|
||||
public void testEntityCaps() throws XMPPException, InterruptedException {
|
||||
dropWholeEntityCapsCache();
|
||||
sdm1.addFeature(DISCOVER_TEST_FEATURE);
|
||||
|
||||
Thread.sleep(3000);
|
||||
|
||||
DiscoverInfo info = sdm0.discoverInfo(con1.getUser());
|
||||
assertTrue(info.containsFeature(DISCOVER_TEST_FEATURE));
|
||||
|
||||
String u1ver = EntityCapsManager.getNodeVersionByJid(con1.getUser());
|
||||
assertNotNull(u1ver);
|
||||
|
||||
DiscoverInfo entityInfo = EntityCapsManager.caps.get(u1ver);
|
||||
assertNotNull(entityInfo);
|
||||
|
||||
assertEquals(info.toXML(), entityInfo.toXML());
|
||||
}
|
||||
|
||||
private static void dropWholeEntityCapsCache() {
|
||||
EntityCapsManager.caps.clear();
|
||||
EntityCapsManager.jidCaps.clear();
|
||||
}
|
||||
|
||||
private static void dropCapsCache() {
|
||||
EntityCapsManager.caps.clear();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.muc;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.Form;
|
||||
import org.jivesoftware.smackx.FormField;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Tests creating new MUC rooms.
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class MultiUserChatCreationTest extends SmackTestCase {
|
||||
|
||||
private String room;
|
||||
|
||||
/**
|
||||
* Constructor for MultiUserChatCreationTest.
|
||||
* @param arg0
|
||||
*/
|
||||
public MultiUserChatCreationTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests creating a new "Reserved Room".
|
||||
*/
|
||||
public void testCreateReservedRoom() {
|
||||
MultiUserChat muc = new MultiUserChat(getConnection(0), room);
|
||||
|
||||
try {
|
||||
// Create the room
|
||||
muc.create("testbot1");
|
||||
|
||||
// Get the the room's configuration form
|
||||
Form form = muc.getConfigurationForm();
|
||||
assertNotNull("No room configuration form", form);
|
||||
// Create a new form to submit based on the original form
|
||||
Form submitForm = form.createAnswerForm();
|
||||
// Add default answers to the form to submit
|
||||
for (Iterator<FormField> fields = form.getFields(); fields.hasNext();) {
|
||||
FormField field = fields.next();
|
||||
if (!FormField.TYPE_HIDDEN.equals(field.getType())
|
||||
&& field.getVariable() != null) {
|
||||
// Sets the default value as the answer
|
||||
submitForm.setDefaultAnswer(field.getVariable());
|
||||
}
|
||||
}
|
||||
List<String> owners = new ArrayList<String>();
|
||||
owners.add(getBareJID(0));
|
||||
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
|
||||
|
||||
// Update the new room's configuration
|
||||
muc.sendConfigurationForm(submitForm);
|
||||
|
||||
// Destroy the new room
|
||||
muc.destroy("The room has almost no activity...", null);
|
||||
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
e.printStackTrace();
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests creating a new "Instant Room".
|
||||
*/
|
||||
public void testCreateInstantRoom() {
|
||||
MultiUserChat muc = new MultiUserChat(getConnection(0), room);
|
||||
|
||||
try {
|
||||
// Create the room
|
||||
muc.create("testbot");
|
||||
|
||||
// Send an empty room configuration form which indicates that we want
|
||||
// an instant room
|
||||
muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
|
||||
|
||||
// Destroy the new room
|
||||
muc.destroy("The room has almost no activity...", null);
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
e.printStackTrace();
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
room = "fruta124@" + getMUCDomain();
|
||||
}
|
||||
}
|
||||
1879
integration-test/org/jivesoftware/smackx/muc/MultiUserChatTest.java
Normal file
1879
integration-test/org/jivesoftware/smackx/muc/MultiUserChatTest.java
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,132 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx.packet;
|
||||
|
||||
import org.jivesoftware.smack.*;
|
||||
import org.jivesoftware.smack.filter.*;
|
||||
import org.jivesoftware.smack.packet.*;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* Test the MessageEvent extension using the low level API
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class MessageEventTest extends SmackTestCase {
|
||||
|
||||
public MessageEventTest(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Low level API test.
|
||||
* This is a simple test to use with a XMPP client and check if the client receives the
|
||||
* message
|
||||
* 1. User_1 will send a message to user_2 requesting to be notified when any of these events
|
||||
* occurs: offline, composing, displayed or delivered
|
||||
*/
|
||||
public void testSendMessageEventRequest() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
|
||||
// Create the message to send with the roster
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("An interesting body comes here...");
|
||||
// Create a MessageEvent Package and add it to the message
|
||||
MessageEvent messageEvent = new MessageEvent();
|
||||
messageEvent.setComposing(true);
|
||||
messageEvent.setDelivered(true);
|
||||
messageEvent.setDisplayed(true);
|
||||
messageEvent.setOffline(true);
|
||||
msg.addExtension(messageEvent);
|
||||
|
||||
// Send the message that contains the notifications request
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
// Wait half second so that the complete test can run
|
||||
Thread.sleep(200);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail("An error occured sending the message");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Low level API test.
|
||||
* This is a simple test to use with a XMPP client, check if the client receives the
|
||||
* message and display in the console any notification
|
||||
* 1. User_1 will send a message to user_2 requesting to be notified when any of these events
|
||||
* occurs: offline, composing, displayed or delivered
|
||||
* 2. User_2 will use a XMPP client (like Exodus) to display the message and compose a reply
|
||||
* 3. User_1 will display any notification that receives
|
||||
*/
|
||||
public void testSendMessageEventRequestAndDisplayNotifications() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
|
||||
// Create a Listener that listens for Messages with the extension "jabber:x:roster"
|
||||
// This listener will listen on the conn2 and answer an ACK if everything is ok
|
||||
PacketFilter packetFilter = new PacketExtensionFilter("x", "jabber:x:event");
|
||||
PacketListener packetListener = new PacketListener() {
|
||||
public void processPacket(Packet packet) {
|
||||
Message message = (Message) packet;
|
||||
try {
|
||||
MessageEvent messageEvent =
|
||||
(MessageEvent) message.getExtension("x", "jabber:x:event");
|
||||
assertNotNull("Message without extension \"jabber:x:event\"", messageEvent);
|
||||
assertTrue(
|
||||
"Message event is a request not a notification",
|
||||
!messageEvent.isMessageEventRequest());
|
||||
System.out.println(messageEvent.toXML());
|
||||
}
|
||||
catch (ClassCastException e) {
|
||||
fail("ClassCastException - Most probable cause is that smack providers is misconfigured");
|
||||
}
|
||||
}
|
||||
};
|
||||
getConnection(0).addPacketListener(packetListener, packetFilter);
|
||||
|
||||
// Create the message to send with the roster
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("An interesting body comes here...");
|
||||
// Create a MessageEvent Package and add it to the message
|
||||
MessageEvent messageEvent = new MessageEvent();
|
||||
messageEvent.setComposing(true);
|
||||
messageEvent.setDelivered(true);
|
||||
messageEvent.setDisplayed(true);
|
||||
messageEvent.setOffline(true);
|
||||
msg.addExtension(messageEvent);
|
||||
|
||||
// Send the message that contains the notifications request
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
// Wait half second so that the complete test can run
|
||||
Thread.sleep(200);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail("An error occured sending the message");
|
||||
}
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,185 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.packet;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.jivesoftware.smack.*;
|
||||
import org.jivesoftware.smack.filter.*;
|
||||
import org.jivesoftware.smack.packet.*;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* Test the Roster Exchange extension using the low level API
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class RosterExchangeTest extends SmackTestCase {
|
||||
|
||||
public RosterExchangeTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Low level API test.
|
||||
* This is a simple test to use with a XMPP client and check if the client receives the message
|
||||
* 1. User_1 will send his/her roster entries to user_2
|
||||
*/
|
||||
public void testSendRosterEntries() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
|
||||
// Create the message to send with the roster
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("This message contains roster items.");
|
||||
// Create a RosterExchange Package and add it to the message
|
||||
assertTrue("Roster has no entries", getConnection(0).getRoster().getEntryCount() > 0);
|
||||
RosterExchange rosterExchange = new RosterExchange(getConnection(0).getRoster());
|
||||
msg.addExtension(rosterExchange);
|
||||
|
||||
// Send the message that contains the roster
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
} catch (Exception e) {
|
||||
fail("An error occured sending the message with the roster");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Low level API test.
|
||||
* 1. User_1 will send his/her roster entries to user_2
|
||||
* 2. User_2 will receive the entries and iterate over them to check if everything is fine
|
||||
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then something is wrong
|
||||
*/
|
||||
public void testSendAndReceiveRosterEntries() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
final PacketCollector chat2 = getConnection(1).createPacketCollector(
|
||||
new ThreadFilter(chat1.getThreadID()));
|
||||
|
||||
// Create the message to send with the roster
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("This message contains roster items.");
|
||||
// Create a RosterExchange Package and add it to the message
|
||||
assertTrue("Roster has no entries", getConnection(0).getRoster().getEntryCount() > 0);
|
||||
RosterExchange rosterExchange = new RosterExchange(getConnection(0).getRoster());
|
||||
msg.addExtension(rosterExchange);
|
||||
|
||||
// Send the message that contains the roster
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
} catch (Exception e) {
|
||||
fail("An error occured sending the message with the roster");
|
||||
}
|
||||
// Wait for 2 seconds for a reply
|
||||
Packet packet = chat2.nextResult(2000);
|
||||
Message message = (Message) packet;
|
||||
assertNotNull("Body is null", message.getBody());
|
||||
try {
|
||||
rosterExchange =
|
||||
(RosterExchange) message.getExtension("x", "jabber:x:roster");
|
||||
assertNotNull("Message without extension \"jabber:x:roster\"", rosterExchange);
|
||||
assertTrue(
|
||||
"Roster without entries",
|
||||
rosterExchange.getRosterEntries().hasNext());
|
||||
}
|
||||
catch (ClassCastException e) {
|
||||
fail("ClassCastException - Most probable cause is that smack providers is misconfigured");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Low level API test.
|
||||
* 1. User_1 will send his/her roster entries to user_2
|
||||
* 2. User_2 will automatically add the entries that receives to his/her roster in the corresponding group
|
||||
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then something is wrong
|
||||
*/
|
||||
public void testSendAndAcceptRosterEntries() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
final PacketCollector chat2 = getConnection(1).createPacketCollector(
|
||||
new ThreadFilter(chat1.getThreadID()));
|
||||
|
||||
// Create the message to send with the roster
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("This message contains roster items.");
|
||||
// Create a RosterExchange Package and add it to the message
|
||||
assertTrue("Roster has no entries", getConnection(0).getRoster().getEntryCount() > 0);
|
||||
RosterExchange rosterExchange = new RosterExchange(getConnection(0).getRoster());
|
||||
msg.addExtension(rosterExchange);
|
||||
|
||||
// Send the message that contains the roster
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
} catch (Exception e) {
|
||||
fail("An error occured sending the message with the roster");
|
||||
}
|
||||
// Wait for 10 seconds for a reply
|
||||
Packet packet = chat2.nextResult(5000);
|
||||
Message message = (Message) packet;
|
||||
assertNotNull("Body is null", message.getBody());
|
||||
try {
|
||||
rosterExchange =
|
||||
(RosterExchange) message.getExtension("x", "jabber:x:roster");
|
||||
assertNotNull("Message without extension \"jabber:x:roster\"", rosterExchange);
|
||||
assertTrue(
|
||||
"Roster without entries",
|
||||
rosterExchange.getRosterEntries().hasNext());
|
||||
// Add the roster entries to user2's roster
|
||||
for (Iterator<RemoteRosterEntry> it = rosterExchange.getRosterEntries(); it.hasNext();) {
|
||||
RemoteRosterEntry remoteRosterEntry = it.next();
|
||||
getConnection(1).getRoster().createEntry(
|
||||
remoteRosterEntry.getUser(),
|
||||
remoteRosterEntry.getName(),
|
||||
remoteRosterEntry.getGroupArrayNames());
|
||||
}
|
||||
}
|
||||
catch (ClassCastException e) {
|
||||
fail("ClassCastException - Most probable cause is that smack providers is misconfigured");
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail(e.toString());
|
||||
}
|
||||
|
||||
assertTrue("Roster2 has no entries", getConnection(1).getRoster().getEntryCount() > 0);
|
||||
}
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
try {
|
||||
getConnection(0).getRoster().createEntry(
|
||||
getBareJID(2),
|
||||
"gato5",
|
||||
new String[] { "Friends, Coworker" });
|
||||
getConnection(0).getRoster().createEntry(getBareJID(3), "gato6", null);
|
||||
Thread.sleep(300);
|
||||
|
||||
} catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
protected int getMaxConnections() {
|
||||
return 4;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,212 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smackx.packet;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.jivesoftware.smack.Chat;
|
||||
import org.jivesoftware.smack.PacketCollector;
|
||||
import org.jivesoftware.smack.PacketListener;
|
||||
import org.jivesoftware.smack.filter.PacketExtensionFilter;
|
||||
import org.jivesoftware.smack.filter.PacketFilter;
|
||||
import org.jivesoftware.smack.filter.ThreadFilter;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
|
||||
/**
|
||||
* Test the XHTML extension using the low level API
|
||||
*
|
||||
* @author Gaston Dombiak
|
||||
*/
|
||||
public class XHTMLExtensionTest extends SmackTestCase {
|
||||
|
||||
private int bodiesSent;
|
||||
private int bodiesReceived;
|
||||
|
||||
public XHTMLExtensionTest(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Low level API test.
|
||||
* This is a simple test to use with a XMPP client and check if the client receives the message
|
||||
* 1. User_1 will send a message with formatted text (XHTML) to user_2
|
||||
*/
|
||||
public void testSendSimpleXHTMLMessage() {
|
||||
// User1 creates a chat with user2
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
|
||||
// User1 creates a message to send to user2
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("Hey John, this is my new green!!!!");
|
||||
// Create a XHTMLExtension Package and add it to the message
|
||||
XHTMLExtension xhtmlExtension = new XHTMLExtension();
|
||||
xhtmlExtension.addBody(
|
||||
"<body><p style='font-size:large'>Hey John, this is my new <span style='color:green'>green</span><em>!!!!</em></p></body>");
|
||||
msg.addExtension(xhtmlExtension);
|
||||
|
||||
// User1 sends the message that contains the XHTML to user2
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
Thread.sleep(200);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail("An error occured sending the message with XHTML");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Low level API test.
|
||||
* 1. User_1 will send a message with XHTML to user_2
|
||||
* 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything
|
||||
* is fine
|
||||
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
|
||||
* something is wrong
|
||||
*/
|
||||
public void testSendSimpleXHTMLMessageAndDisplayReceivedXHTMLMessage() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
final PacketCollector chat2 = getConnection(1).createPacketCollector(
|
||||
new ThreadFilter(chat1.getThreadID()));
|
||||
|
||||
// User1 creates a message to send to user2
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody("Hey John, this is my new green!!!!");
|
||||
// Create a XHTMLExtension Package and add it to the message
|
||||
XHTMLExtension xhtmlExtension = new XHTMLExtension();
|
||||
xhtmlExtension.addBody(
|
||||
"<body><p style='font-size:large'>Hey John, this is my new <span style='color:green'>green</span><em>!!!!</em></p></body>");
|
||||
msg.addExtension(xhtmlExtension);
|
||||
|
||||
// User1 sends the message that contains the XHTML to user2
|
||||
try {
|
||||
chat1.sendMessage(msg);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail("An error occured sending the message with XHTML");
|
||||
}
|
||||
Packet packet = chat2.nextResult(2000);
|
||||
Message message = (Message) packet;
|
||||
assertNotNull("Body is null", message.getBody());
|
||||
try {
|
||||
xhtmlExtension =
|
||||
(XHTMLExtension) message.getExtension(
|
||||
"html",
|
||||
"http://jabber.org/protocol/xhtml-im");
|
||||
assertNotNull(
|
||||
"Message without extension \"http://jabber.org/protocol/xhtml-im\"",
|
||||
xhtmlExtension);
|
||||
assertTrue("Message without XHTML bodies", xhtmlExtension.getBodiesCount() > 0);
|
||||
for (Iterator<String> it = xhtmlExtension.getBodies(); it.hasNext();) {
|
||||
String body = it.next();
|
||||
System.out.println(body);
|
||||
}
|
||||
}
|
||||
catch (ClassCastException e) {
|
||||
fail("ClassCastException - Most probable cause is that smack providers is misconfigured");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Low level API test. Test a message with two XHTML bodies and several XHTML tags.
|
||||
* 1. User_1 will send a message with XHTML to user_2
|
||||
* 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything
|
||||
* is fine
|
||||
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
|
||||
* something is wrong
|
||||
*/
|
||||
public void testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage() {
|
||||
// Create a chat for each connection
|
||||
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
|
||||
final PacketCollector chat2 = getConnection(1).createPacketCollector(
|
||||
new ThreadFilter(chat1.getThreadID()));
|
||||
|
||||
// Create a Listener that listens for Messages with the extension
|
||||
//"http://jabber.org/protocol/xhtml-im"
|
||||
// This listener will listen on the conn2 and answer an ACK if everything is ok
|
||||
PacketFilter packetFilter =
|
||||
new PacketExtensionFilter("html", "http://jabber.org/protocol/xhtml-im");
|
||||
PacketListener packetListener = new PacketListener() {
|
||||
@Override
|
||||
public void processPacket(Packet packet) {
|
||||
|
||||
}
|
||||
};
|
||||
getConnection(1).addPacketListener(packetListener, packetFilter);
|
||||
|
||||
// User1 creates a message to send to user2
|
||||
Message msg = new Message();
|
||||
msg.setSubject("Any subject you want");
|
||||
msg.setBody(
|
||||
"awesome! As Emerson once said: A foolish consistency is the hobgoblin of little minds.");
|
||||
// Create an XHTMLExtension and add it to the message
|
||||
XHTMLExtension xhtmlExtension = new XHTMLExtension();
|
||||
xhtmlExtension.addBody(
|
||||
"<body xml:lang=\"es-ES\"><h1>impresionante!</h1><p>Como Emerson dijo una vez:</p><blockquote><p>Una consistencia ridicula es el espantajo de mentes pequenas.</p></blockquote></body>");
|
||||
xhtmlExtension.addBody(
|
||||
"<body xml:lang=\"en-US\"><h1>awesome!</h1><p>As Emerson once said:</p><blockquote><p>A foolish consistency is the hobgoblin of little minds.</p></blockquote></body>");
|
||||
msg.addExtension(xhtmlExtension);
|
||||
|
||||
// User1 sends the message that contains the XHTML to user2
|
||||
try {
|
||||
bodiesSent = xhtmlExtension.getBodiesCount();
|
||||
bodiesReceived = 0;
|
||||
chat1.sendMessage(msg);
|
||||
}
|
||||
catch (Exception e) {
|
||||
fail("An error occured sending the message with XHTML");
|
||||
}
|
||||
Packet packet = chat2.nextResult(2000);
|
||||
int received = 0;
|
||||
Message message = (Message) packet;
|
||||
assertNotNull("Body is null", message.getBody());
|
||||
try {
|
||||
xhtmlExtension =
|
||||
(XHTMLExtension) message.getExtension(
|
||||
"html",
|
||||
"http://jabber.org/protocol/xhtml-im");
|
||||
assertNotNull(
|
||||
"Message without extension \"http://jabber.org/protocol/xhtml-im\"",
|
||||
xhtmlExtension);
|
||||
assertTrue("Message without XHTML bodies", xhtmlExtension.getBodiesCount() > 0);
|
||||
for (Iterator<String> it = xhtmlExtension.getBodies(); it.hasNext();) {
|
||||
received++;
|
||||
System.out.println(it.next());
|
||||
}
|
||||
bodiesReceived = received;
|
||||
}
|
||||
catch (ClassCastException e) {
|
||||
fail("ClassCastException - Most probable cause is that smack providers is " +
|
||||
"misconfigured");
|
||||
}
|
||||
// Wait half second so that the complete test can run
|
||||
assertEquals(
|
||||
"Number of sent and received XHTMP bodies does not match",
|
||||
bodiesSent,
|
||||
bodiesReceived);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getMaxConnections() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub;
|
||||
|
||||
import org.jivesoftware.smack.packet.PacketExtension;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
class CarExtension implements PacketExtension
|
||||
{
|
||||
private String color;
|
||||
private int numTires;
|
||||
|
||||
public CarExtension(String col, int num)
|
||||
{
|
||||
color = col;
|
||||
numTires = num;
|
||||
}
|
||||
|
||||
public String getColor()
|
||||
{
|
||||
return color;
|
||||
}
|
||||
|
||||
public int getNumTires()
|
||||
{
|
||||
return numTires;
|
||||
}
|
||||
|
||||
public String getElementName()
|
||||
{
|
||||
return "car";
|
||||
}
|
||||
|
||||
public String getNamespace()
|
||||
{
|
||||
return "pubsub:test:vehicle";
|
||||
}
|
||||
|
||||
public String toXML()
|
||||
{
|
||||
return "<" + getElementName() + " xmlns='" + getNamespace() + "'><paint color='" +
|
||||
getColor() + "'/><tires num='" + getNumTires() + "'/></" + getElementName() + ">";
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub;
|
||||
|
||||
import org.jivesoftware.smack.packet.PacketExtension;
|
||||
import org.jivesoftware.smack.provider.PacketExtensionProvider;
|
||||
import org.xmlpull.v1.XmlPullParser;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class CarExtensionProvider implements PacketExtensionProvider
|
||||
{
|
||||
|
||||
public PacketExtension parseExtension(XmlPullParser parser) throws Exception
|
||||
{
|
||||
String color = null;
|
||||
int numTires = 0;
|
||||
|
||||
for (int i=0; i<2; i++)
|
||||
{
|
||||
while (parser.next() != XmlPullParser.START_TAG);
|
||||
|
||||
if (parser.getName().equals("paint"))
|
||||
{
|
||||
color = parser.getAttributeValue(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
numTires = Integer.parseInt(parser.getAttributeValue(0));
|
||||
}
|
||||
}
|
||||
while (parser.next() != XmlPullParser.END_TAG);
|
||||
return new CarExtension(color, numTires);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.jivesoftware.smackx.packet.DiscoverInfo;
|
||||
import org.jivesoftware.smackx.packet.DiscoverItems;
|
||||
import org.jivesoftware.smackx.packet.DiscoverInfo.Identity;
|
||||
import org.jivesoftware.smackx.pubsub.test.SingleUserTestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class EntityUseCases extends SingleUserTestCase
|
||||
{
|
||||
public void testDiscoverPubsubInfo() throws Exception
|
||||
{
|
||||
DiscoverInfo supportedFeatures = getManager().getSupportedFeatures();
|
||||
assertNotNull(supportedFeatures);
|
||||
}
|
||||
|
||||
public void testDiscoverNodeInfo() throws Exception
|
||||
{
|
||||
LeafNode myNode = getManager().createNode("DiscoNode" + System.currentTimeMillis());
|
||||
DiscoverInfo info = myNode.discoverInfo();
|
||||
assertTrue(info.getIdentities().hasNext());
|
||||
Identity ident = info.getIdentities().next();
|
||||
|
||||
assertEquals("leaf", ident.getType());
|
||||
}
|
||||
|
||||
public void testDiscoverNodeItems() throws Exception
|
||||
{
|
||||
LeafNode myNode = getRandomPubnode(getManager(), true, false);
|
||||
myNode.send(new Item());
|
||||
myNode.send(new Item());
|
||||
myNode.send(new Item());
|
||||
myNode.send(new Item());
|
||||
DiscoverItems items = myNode.discoverItems();
|
||||
|
||||
int count = 0;
|
||||
|
||||
for(Iterator<DiscoverItems.Item> it = items.getItems(); it.hasNext(); it.next(),count++);
|
||||
|
||||
assertEquals(4, count);
|
||||
}
|
||||
|
||||
public void testDiscoverSubscriptions() throws Exception
|
||||
{
|
||||
getManager().getSubscriptions();
|
||||
}
|
||||
|
||||
public void testDiscoverNodeSubscriptions() throws Exception
|
||||
{
|
||||
LeafNode myNode = getRandomPubnode(getManager(), true, true);
|
||||
myNode.subscribe(getConnection(0).getUser());
|
||||
List<Subscription> subscriptions = myNode.getSubscriptions();
|
||||
|
||||
assertTrue(subscriptions.size() < 3);
|
||||
|
||||
for (Subscription subscription : subscriptions)
|
||||
{
|
||||
assertNull(subscription.getNode());
|
||||
}
|
||||
}
|
||||
|
||||
public void testRetrieveAffiliation() throws Exception
|
||||
{
|
||||
getManager().getAffiliations();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier.
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.packet.XMPPError;
|
||||
import org.jivesoftware.smackx.pubsub.test.PubSubTestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class MultiUserSubscriptionUseCases extends PubSubTestCase
|
||||
{
|
||||
|
||||
@Override
|
||||
protected int getMaxConnections()
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public void testGetItemsWithSingleSubscription() throws XMPPException
|
||||
{
|
||||
LeafNode node = getRandomPubnode(getManager(0), true, false);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
|
||||
LeafNode user2Node = (LeafNode) getManager(1).getNode(node.getId());
|
||||
user2Node.subscribe(getBareJID(1));
|
||||
|
||||
Collection<? extends Item> items = user2Node.getItems();
|
||||
assertTrue(items.size() == 5);
|
||||
}
|
||||
|
||||
public void testGetItemsWithMultiSubscription() throws XMPPException
|
||||
{
|
||||
LeafNode node = getRandomPubnode(getManager(0), true, false);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
|
||||
LeafNode user2Node = (LeafNode) getManager(1).getNode(node.getId());
|
||||
Subscription sub1 = user2Node.subscribe(getBareJID(1));
|
||||
|
||||
Subscription sub2 = user2Node.subscribe(getBareJID(1));
|
||||
|
||||
try
|
||||
{
|
||||
user2Node.getItems();
|
||||
}
|
||||
catch (XMPPException exc)
|
||||
{
|
||||
assertEquals("bad-request", exc.getXMPPError().getCondition());
|
||||
assertEquals(XMPPError.Type.MODIFY, exc.getXMPPError().getType());
|
||||
}
|
||||
List<Item> items = user2Node.getItems(sub1.getId());
|
||||
assertTrue(items.size() == 5);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smackx.pubsub.test.SingleUserTestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class OwnerUseCases extends SingleUserTestCase
|
||||
{
|
||||
public void testCreateInstantNode() throws Exception
|
||||
{
|
||||
LeafNode node = getManager().createNode();
|
||||
assertNotNull(node);
|
||||
assertNotNull(node.getId());
|
||||
}
|
||||
|
||||
public void testCreateNamedNode() throws Exception
|
||||
{
|
||||
String id = "TestNamedNode" + System.currentTimeMillis();
|
||||
LeafNode node = getManager().createNode(id);
|
||||
assertEquals(id, node.getId());
|
||||
}
|
||||
|
||||
public void testCreateConfiguredNode() throws Exception
|
||||
{
|
||||
// Generate reasonably unique for multiple tests
|
||||
String id = "TestConfigNode" + System.currentTimeMillis();
|
||||
|
||||
// Create and configure a node
|
||||
ConfigureForm form = new ConfigureForm(FormType.submit);
|
||||
form.setAccessModel(AccessModel.open);
|
||||
form.setDeliverPayloads(false);
|
||||
form.setNotifyRetract(true);
|
||||
form.setPersistentItems(true);
|
||||
form.setPublishModel(PublishModel.open);
|
||||
|
||||
LeafNode node = (LeafNode)getManager().createNode(id, form);
|
||||
|
||||
ConfigureForm currentForm = node.getNodeConfiguration();
|
||||
assertEquals(AccessModel.open, currentForm.getAccessModel());
|
||||
assertFalse(currentForm.isDeliverPayloads());
|
||||
assertTrue(currentForm.isNotifyRetract());
|
||||
assertTrue(currentForm.isPersistItems());
|
||||
assertEquals(PublishModel.open, currentForm.getPublishModel());
|
||||
}
|
||||
|
||||
public void testCreateAndUpdateConfiguredNode() throws Exception
|
||||
{
|
||||
// Generate reasonably unique for multiple tests
|
||||
String id = "TestConfigNode2" + System.currentTimeMillis();
|
||||
|
||||
// Create and configure a node
|
||||
ConfigureForm form = new ConfigureForm(FormType.submit);
|
||||
form.setAccessModel(AccessModel.open);
|
||||
form.setDeliverPayloads(false);
|
||||
form.setNotifyRetract(true);
|
||||
form.setPersistentItems(true);
|
||||
form.setPublishModel(PublishModel.open);
|
||||
|
||||
LeafNode myNode = (LeafNode)getManager().createNode(id, form);
|
||||
ConfigureForm config = myNode.getNodeConfiguration();
|
||||
|
||||
assertEquals(AccessModel.open, config.getAccessModel());
|
||||
assertFalse(config.isDeliverPayloads());
|
||||
assertTrue(config.isNotifyRetract());
|
||||
assertTrue(config.isPersistItems());
|
||||
assertEquals(PublishModel.open, config.getPublishModel());
|
||||
|
||||
ConfigureForm submitForm = new ConfigureForm(config.createAnswerForm());
|
||||
submitForm.setAccessModel(AccessModel.whitelist);
|
||||
submitForm.setDeliverPayloads(true);
|
||||
submitForm.setNotifyRetract(false);
|
||||
submitForm.setPersistentItems(false);
|
||||
submitForm.setPublishModel(PublishModel.publishers);
|
||||
myNode.sendConfigurationForm(submitForm);
|
||||
|
||||
ConfigureForm newConfig = myNode.getNodeConfiguration();
|
||||
assertEquals(AccessModel.whitelist, newConfig.getAccessModel());
|
||||
assertTrue(newConfig.isDeliverPayloads());
|
||||
assertFalse(newConfig.isNotifyRetract());
|
||||
assertFalse(newConfig.isPersistItems());
|
||||
assertEquals(PublishModel.publishers, newConfig.getPublishModel());
|
||||
}
|
||||
|
||||
public void testGetDefaultConfig() throws Exception
|
||||
{
|
||||
ConfigureForm form = getManager().getDefaultConfiguration();
|
||||
assertNotNull(form);
|
||||
}
|
||||
|
||||
public void testDeleteNode() throws Exception
|
||||
{
|
||||
LeafNode myNode = getManager().createNode();
|
||||
assertNotNull(getManager().getNode(myNode.getId()));
|
||||
|
||||
getManager(0).deleteNode(myNode.getId());
|
||||
|
||||
try
|
||||
{
|
||||
assertNull(getManager().getNode(myNode.getId()));
|
||||
fail("Node should not exist");
|
||||
}
|
||||
catch (XMPPException e)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public void testPurgeItems() throws XMPPException
|
||||
{
|
||||
LeafNode node = getRandomPubnode(getManager(), true, false);
|
||||
|
||||
node.send(new Item());
|
||||
node.send(new Item());
|
||||
node.send(new Item());
|
||||
node.send(new Item());
|
||||
node.send(new Item());
|
||||
|
||||
Collection<? extends Item> items = node.getItems();
|
||||
assertTrue(items.size() == 5);
|
||||
|
||||
node.deleteAllItems();
|
||||
items = node.getItems();
|
||||
|
||||
// Pubsub service may keep the last notification (in spec), so 0 or 1 may be returned on get items.
|
||||
assertTrue(items.size() < 2);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.packet.XMPPError;
|
||||
import org.jivesoftware.smack.packet.XMPPError.Condition;
|
||||
import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace;
|
||||
import org.jivesoftware.smackx.pubsub.test.SingleUserTestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class PublisherUseCases extends SingleUserTestCase
|
||||
{
|
||||
public void testSendNodeTrNot() throws Exception
|
||||
{
|
||||
getPubnode(false, false).send();
|
||||
}
|
||||
|
||||
public void testSendNodeTrPay_WithOutPayload() throws XMPPException
|
||||
{
|
||||
LeafNode node = getPubnode(false, true);
|
||||
|
||||
try
|
||||
{
|
||||
node.send(new Item());
|
||||
fail("Exception should be thrown when there is no payload");
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
XMPPError err = e.getXMPPError();
|
||||
assertTrue(err.getType().equals(XMPPError.Type.MODIFY));
|
||||
assertTrue(err.getCondition().equals(Condition.bad_request.toString()));
|
||||
assertNotNull(err.getExtension("payload-required", PubSubNamespace.ERROR.getXmlns()));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
node.send(new Item("test" + System.currentTimeMillis()));
|
||||
fail("Exception should be thrown when there is no payload");
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
XMPPError err = e.getXMPPError();
|
||||
assertTrue(err.getType().equals(XMPPError.Type.MODIFY));
|
||||
assertTrue(err.getCondition().equals(Condition.bad_request.toString()));
|
||||
assertNotNull(err.getExtension("payload-required", PubSubNamespace.ERROR.getXmlns()));
|
||||
}
|
||||
}
|
||||
|
||||
public void testSendNodeTrPay_WithPayload() throws XMPPException
|
||||
{
|
||||
LeafNode node = getPubnode(false, true);
|
||||
node.send(new PayloadItem<SimplePayload>(null,
|
||||
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Lord of the Rings</title></book>")));
|
||||
node.send(new PayloadItem<SimplePayload>("test" + System.currentTimeMillis(),
|
||||
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Two Towers</title></book>")));
|
||||
}
|
||||
|
||||
public void testSendNodePerNot() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(true, false);
|
||||
node.send(new Item());
|
||||
node.send(new Item("test" + System.currentTimeMillis()));
|
||||
node.send(new PayloadItem<SimplePayload>(null,
|
||||
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Lord of the Rings</title></book>")));
|
||||
node.send(new PayloadItem<SimplePayload>("test" + System.currentTimeMillis(),
|
||||
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Two Towers</title></book>")));
|
||||
}
|
||||
|
||||
public void testSendPerPay_WithPayload() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(true, true);
|
||||
node.send(new PayloadItem<SimplePayload>(null,
|
||||
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Lord of the Rings</title></book>")));
|
||||
node.send(new PayloadItem<SimplePayload>("test" + System.currentTimeMillis(),
|
||||
new SimplePayload("book", "pubsub:test:book", "<book xmlns='pubsub:test:book'><title>Two Towers</title></book>")));
|
||||
}
|
||||
|
||||
public void testSendPerPay_NoPayload() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(true, true);
|
||||
try
|
||||
{
|
||||
node.send(new Item());
|
||||
fail("Exception should be thrown when there is no payload");
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
XMPPError err = e.getXMPPError();
|
||||
assertTrue(err.getType().equals(XMPPError.Type.MODIFY));
|
||||
assertTrue(err.getCondition().equals(Condition.bad_request.toString()));
|
||||
assertNotNull(err.getExtension("payload-required", PubSubNamespace.ERROR.getXmlns()));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
node.send(new Item("test" + System.currentTimeMillis()));
|
||||
fail("Exception should be thrown when there is no payload");
|
||||
}
|
||||
catch (XMPPException e) {
|
||||
XMPPError err = e.getXMPPError();
|
||||
assertTrue(err.getType().equals(XMPPError.Type.MODIFY));
|
||||
assertTrue(err.getCondition().equals(Condition.bad_request.toString()));
|
||||
assertNotNull(err.getExtension("payload-required", PubSubNamespace.ERROR.getXmlns()));
|
||||
}
|
||||
}
|
||||
|
||||
public void testDeleteItems() throws XMPPException
|
||||
{
|
||||
LeafNode node = getPubnode(true, false);
|
||||
|
||||
node.send(new Item("1"));
|
||||
node.send(new Item("2"));
|
||||
node.send(new Item("3"));
|
||||
node.send(new Item("4"));
|
||||
|
||||
node.deleteItem("1");
|
||||
Collection<? extends Item> items = node.getItems();
|
||||
|
||||
assertEquals(3, items.size());
|
||||
}
|
||||
|
||||
public void testPersistItems() throws XMPPException
|
||||
{
|
||||
LeafNode node = getPubnode(true, false);
|
||||
|
||||
node.send(new Item("1"));
|
||||
node.send(new Item("2"));
|
||||
node.send(new Item("3"));
|
||||
node.send(new Item("4"));
|
||||
|
||||
Collection<? extends Item> items = node.getItems();
|
||||
|
||||
assertTrue(items.size() == 4);
|
||||
}
|
||||
|
||||
public void testItemOverwritten() throws XMPPException
|
||||
{
|
||||
LeafNode node = getPubnode(true, false);
|
||||
|
||||
node.send(new PayloadItem<SimplePayload>("1", new SimplePayload("test", null, "<test/>")));
|
||||
node.send(new PayloadItem<SimplePayload>("1", new SimplePayload("test2", null, "<test2/>")));
|
||||
|
||||
List<? extends Item> items = node.getItems();
|
||||
assertEquals(1, items.size());
|
||||
assertEquals("1", items.get(0).getId());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,280 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub;
|
||||
|
||||
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smackx.FormField;
|
||||
import org.jivesoftware.smackx.pubsub.test.SingleUserTestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class SubscriberUseCases extends SingleUserTestCase
|
||||
{
|
||||
public void testSubscribe() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(false, false);
|
||||
Subscription sub = node.subscribe(getJid());
|
||||
|
||||
assertEquals(getJid(), sub.getJid());
|
||||
assertNotNull(sub.getId());
|
||||
assertEquals(node.getId(), sub.getNode());
|
||||
assertEquals(Subscription.State.subscribed, sub.getState());
|
||||
}
|
||||
|
||||
public void testSubscribeBadJid() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(false, false);
|
||||
|
||||
try
|
||||
{
|
||||
node.subscribe("this@over.here");
|
||||
fail();
|
||||
}
|
||||
catch (XMPPException e)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public void testSubscribeWithOptions() throws Exception
|
||||
{
|
||||
SubscribeForm form = new SubscribeForm(FormType.submit);
|
||||
form.setDeliverOn(true);
|
||||
Calendar expire = Calendar.getInstance();
|
||||
expire.set(2020, 1, 1);
|
||||
form.setExpiry(expire.getTime());
|
||||
LeafNode node = getPubnode(false, false);
|
||||
node.subscribe(getJid(), form);
|
||||
}
|
||||
|
||||
public void testSubscribeConfigRequired() throws Exception
|
||||
{
|
||||
ConfigureForm form = new ConfigureForm(FormType.submit);
|
||||
form.setAccessModel(AccessModel.open);
|
||||
|
||||
// Openfire specific field - nothing in the spec yet
|
||||
FormField required = new FormField("pubsub#subscription_required");
|
||||
required.setType(FormField.TYPE_BOOLEAN);
|
||||
form.addField(required);
|
||||
form.setAnswer("pubsub#subscription_required", true);
|
||||
LeafNode node = (LeafNode)getManager().createNode("Pubnode" + System.currentTimeMillis(), form);
|
||||
|
||||
Subscription sub = node.subscribe(getJid());
|
||||
|
||||
assertEquals(getJid(), sub.getJid());
|
||||
assertNotNull(sub.getId());
|
||||
assertEquals(node.getId(), sub.getNode());
|
||||
assertEquals(true, sub.isConfigRequired());
|
||||
}
|
||||
|
||||
public void testUnsubscribe() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(false, false);
|
||||
node.subscribe(getJid());
|
||||
Collection<Subscription> subs = node.getSubscriptions();
|
||||
|
||||
node.unsubscribe(getJid());
|
||||
Collection<Subscription> afterSubs = node.getSubscriptions();
|
||||
assertEquals(subs.size()-1, afterSubs.size());
|
||||
}
|
||||
|
||||
public void testUnsubscribeWithMultipleNoSubId() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(false, false);
|
||||
node.subscribe(getBareJID(0));
|
||||
node.subscribe(getBareJID(0));
|
||||
node.subscribe(getBareJID(0));
|
||||
|
||||
try
|
||||
{
|
||||
node.unsubscribe(getBareJID(0));
|
||||
fail("Unsubscribe with no subid should fail");
|
||||
}
|
||||
catch (XMPPException e)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public void testUnsubscribeWithMultipleWithSubId() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(false, false);
|
||||
node.subscribe(getJid());
|
||||
Subscription sub = node.subscribe(getJid());
|
||||
node.subscribe(getJid());
|
||||
node.unsubscribe(getJid(), sub.getId());
|
||||
}
|
||||
|
||||
public void testGetOptions() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(false, false);
|
||||
Subscription sub = node.subscribe(getJid());
|
||||
SubscribeForm form = node.getSubscriptionOptions(getJid(), sub.getId());
|
||||
assertNotNull(form);
|
||||
}
|
||||
|
||||
// public void testSubscribeWithConfig() throws Exception
|
||||
// {
|
||||
// LeafNode node = getPubnode(false, false);
|
||||
//
|
||||
// Subscription sub = node.subscribe(getBareJID(0));
|
||||
//
|
||||
// assertEquals(getBareJID(0), sub.getJid());
|
||||
// assertNotNull(sub.getId());
|
||||
// assertEquals(node.getId(), sub.getNode());
|
||||
// assertEquals(true, sub.isConfigRequired());
|
||||
// }
|
||||
//
|
||||
public void testGetItems() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(true, false);
|
||||
runNodeTests(node);
|
||||
}
|
||||
|
||||
private void runNodeTests(LeafNode node) throws Exception
|
||||
{
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
node.send((Item)null);
|
||||
|
||||
Collection<? extends Item> items = node.getItems();
|
||||
assertTrue(items.size() == 5);
|
||||
|
||||
long curTime = System.currentTimeMillis();
|
||||
node.send(new Item("1-" + curTime));
|
||||
node.send(new Item("2-" + curTime));
|
||||
node.send(new Item("3-" + curTime));
|
||||
node.send(new Item("4-" + curTime));
|
||||
node.send(new Item("5-" + curTime));
|
||||
|
||||
items = node.getItems();
|
||||
assertTrue(items.size() == 10);
|
||||
|
||||
LeafNode payloadNode = getPubnode(true, true);
|
||||
|
||||
Map<String , String> idPayload = new HashMap<String, String>();
|
||||
idPayload.put("6-" + curTime, "<a/>");
|
||||
idPayload.put("7-" + curTime, "<a href=\"/up/here\"/>");
|
||||
idPayload.put("8-" + curTime, "<entity>text<inner></inner></entity>");
|
||||
idPayload.put("9-" + curTime, "<entity><inner><text></text></inner></entity>");
|
||||
|
||||
for (Map.Entry<String, String> payload : idPayload.entrySet())
|
||||
{
|
||||
payloadNode.send(new PayloadItem<SimplePayload>(payload.getKey(), new SimplePayload("a", "pubsub:test", payload.getValue())));
|
||||
}
|
||||
|
||||
payloadNode.send(new PayloadItem<SimplePayload>("6-" + curTime, new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test'/>")));
|
||||
payloadNode.send(new PayloadItem<SimplePayload>("7-" + curTime, new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href=\'/up/here\'/>")));
|
||||
payloadNode.send(new PayloadItem<SimplePayload>("8-" + curTime, new SimplePayload("entity", "pubsub:test", "<entity xmlns='pubsub:test'>text<inner>a</inner></entity>")));
|
||||
payloadNode.send(new PayloadItem<SimplePayload>("9-" + curTime, new SimplePayload("entity", "pubsub:test", "<entity xmlns='pubsub:test'><inner><text>b</text></inner></entity>")));
|
||||
|
||||
List<PayloadItem<SimplePayload>> payloadItems = payloadNode.getItems();
|
||||
Map<String, PayloadItem<SimplePayload>> idMap = new HashMap<String, PayloadItem<SimplePayload>>();
|
||||
|
||||
for (PayloadItem<SimplePayload> payloadItem : payloadItems)
|
||||
{
|
||||
idMap.put(payloadItem.getId(), payloadItem);
|
||||
}
|
||||
|
||||
assertEquals(4, payloadItems.size());
|
||||
|
||||
PayloadItem<SimplePayload> testItem = idMap.get("6-" + curTime);
|
||||
assertNotNull(testItem);
|
||||
assertXMLEqual("<a xmlns='pubsub:test'/>", testItem.getPayload().toXML());
|
||||
|
||||
testItem = idMap.get("7-" + curTime);
|
||||
assertNotNull(testItem);
|
||||
assertXMLEqual("<a xmlns='pubsub:test' href=\'/up/here\'/>", testItem.getPayload().toXML());
|
||||
|
||||
testItem = idMap.get("8-" + curTime);
|
||||
assertNotNull(testItem);
|
||||
assertXMLEqual("<entity xmlns='pubsub:test'>text<inner>a</inner></entity>", testItem.getPayload().toXML());
|
||||
|
||||
testItem = idMap.get("9-" + curTime);
|
||||
assertNotNull(testItem);
|
||||
assertXMLEqual("<entity xmlns='pubsub:test'><inner><text>b</text></inner></entity>", testItem.getPayload().toXML());
|
||||
}
|
||||
|
||||
public void testGetSpecifiedItems() throws Exception
|
||||
{
|
||||
LeafNode node = getPubnode(true, true);
|
||||
|
||||
node.send(new PayloadItem<SimplePayload>("1", new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='1'/>")));
|
||||
node.send(new PayloadItem<SimplePayload>("2", new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='2'/>")));
|
||||
node.send(new PayloadItem<SimplePayload>("3", new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='3'/>")));
|
||||
node.send(new PayloadItem<SimplePayload>("4", new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='4'/>")));
|
||||
node.send(new PayloadItem<SimplePayload>("5", new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='5'/>")));
|
||||
|
||||
Collection<String> ids = new ArrayList<String>(3);
|
||||
ids.add("1");
|
||||
ids.add("3");
|
||||
ids.add("4");
|
||||
|
||||
List<PayloadItem<SimplePayload>> items = node.getItems(ids);
|
||||
assertEquals(3, items.size());
|
||||
assertEquals("1", items.get(0).getId());
|
||||
assertXMLEqual("<a xmlns='pubsub:test' href='1'/>", items.get(0).getPayload().toXML());
|
||||
assertEquals( "3", items.get(1).getId());
|
||||
assertXMLEqual("<a xmlns='pubsub:test' href='3'/>", items.get(1).getPayload().toXML());
|
||||
assertEquals("4", items.get(2).getId());
|
||||
assertXMLEqual("<a xmlns='pubsub:test' href='4'/>", items.get(2).getPayload().toXML());
|
||||
}
|
||||
|
||||
public void testGetLastNItems() throws XMPPException
|
||||
{
|
||||
LeafNode node = getPubnode(true, false);
|
||||
|
||||
node.send(new Item("1"));
|
||||
node.send(new Item("2"));
|
||||
node.send(new Item("3"));
|
||||
node.send(new Item("4"));
|
||||
node.send(new Item("5"));
|
||||
|
||||
List<Item> items = node.getItems(2);
|
||||
assertEquals(2, items.size());
|
||||
assertTrue(listContainsId("4", items));
|
||||
assertTrue(listContainsId("5", items));
|
||||
}
|
||||
|
||||
private static boolean listContainsId(String id, List<Item> items)
|
||||
{
|
||||
for (Item item : items)
|
||||
{
|
||||
if (item.getId().equals(id))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String getJid()
|
||||
{
|
||||
return getConnection(0).getUser();
|
||||
}
|
||||
|
||||
}
|
||||
40
integration-test/org/jivesoftware/smackx/pubsub/TestAPI.java
Normal file
40
integration-test/org/jivesoftware/smackx/pubsub/TestAPI.java
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smackx.pubsub.test.SingleUserTestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class TestAPI extends SingleUserTestCase
|
||||
{
|
||||
public void testGetNonexistentNode()
|
||||
{
|
||||
try
|
||||
{
|
||||
getManager().getNode("" + System.currentTimeMillis());
|
||||
assertTrue(false);
|
||||
}
|
||||
catch (XMPPException e)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
598
integration-test/org/jivesoftware/smackx/pubsub/TestEvents.java
Normal file
598
integration-test/org/jivesoftware/smackx/pubsub/TestEvents.java
Normal file
|
|
@ -0,0 +1,598 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.packet.XMPPError.Type;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.pubsub.listener.ItemDeleteListener;
|
||||
import org.jivesoftware.smackx.pubsub.listener.ItemEventListener;
|
||||
import org.jivesoftware.smackx.pubsub.listener.NodeConfigListener;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class TestEvents extends SmackTestCase
|
||||
{
|
||||
|
||||
public TestEvents(String str)
|
||||
{
|
||||
super(str);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getMaxConnections()
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
private String getService()
|
||||
{
|
||||
return "pubsub." + getServiceName();
|
||||
}
|
||||
|
||||
public void testCreateAndGetNode() throws Exception
|
||||
{
|
||||
String nodeId = "MyTestNode";
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
|
||||
LeafNode creatorNode = null;
|
||||
try
|
||||
{
|
||||
creatorNode = (LeafNode)creatorMgr.getNode(nodeId);
|
||||
}
|
||||
catch (XMPPException e)
|
||||
{
|
||||
if (e.getXMPPError().getType() == Type.CANCEL && e.getXMPPError().getCondition().equals("item-not-found"))
|
||||
creatorNode = creatorMgr.createNode(nodeId);
|
||||
else
|
||||
throw e;
|
||||
}
|
||||
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
|
||||
|
||||
assertNotNull(subNode);
|
||||
}
|
||||
|
||||
public void testConfigureAndNotify() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId = "TestNode" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
|
||||
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, false, true);
|
||||
|
||||
BlockingQueue<NodeConfigCoordinator> queue = new ArrayBlockingQueue<NodeConfigCoordinator>(3);
|
||||
|
||||
// Setup event receiver
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
|
||||
|
||||
NodeConfigListener sub1Handler = new NodeConfigCoordinator(queue, "sub1");
|
||||
subNode.subscribe(getConnection(1).getUser());
|
||||
subNode.addConfigurationListener(sub1Handler);
|
||||
|
||||
ConfigureForm currentConfig = creatorNode.getNodeConfiguration();
|
||||
ConfigureForm form = new ConfigureForm(currentConfig.createAnswerForm());
|
||||
form.setPersistentItems(true);
|
||||
form.setDeliverPayloads(false);
|
||||
form.setNotifyConfig(true);
|
||||
creatorNode.sendConfigurationForm(form);
|
||||
|
||||
ConfigurationEvent event = queue.poll(5, TimeUnit.SECONDS).event;
|
||||
assertEquals(nodeId, event.getNode());
|
||||
assertNull(event.getConfiguration());
|
||||
|
||||
currentConfig = creatorNode.getNodeConfiguration();
|
||||
form = new ConfigureForm(currentConfig.createAnswerForm());
|
||||
form.setDeliverPayloads(true);
|
||||
creatorNode.sendConfigurationForm(form);
|
||||
|
||||
event = queue.poll(5, TimeUnit.SECONDS).event;
|
||||
assertEquals(nodeId, event.getNode());
|
||||
assertNotNull(event.getConfiguration());
|
||||
assertTrue(event.getConfiguration().isPersistItems());
|
||||
assertTrue(event.getConfiguration().isDeliverPayloads());
|
||||
}
|
||||
|
||||
public void testSendAndReceiveNoPayload() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId = "TestNode" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
|
||||
|
||||
BlockingQueue<ItemEventCoordinator<Item>> queue = new ArrayBlockingQueue<ItemEventCoordinator<Item>>(3);
|
||||
|
||||
// Setup event receiver
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
|
||||
|
||||
ItemEventCoordinator<Item> sub1Handler = new ItemEventCoordinator<Item>(queue, "sub1");
|
||||
subNode.addItemEventListener(sub1Handler);
|
||||
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
// Send event
|
||||
String itemId = String.valueOf(System.currentTimeMillis());
|
||||
creatorNode.send(new Item(itemId));
|
||||
|
||||
ItemEventCoordinator<Item> coord = queue.poll(5, TimeUnit.SECONDS);
|
||||
assertEquals(1, coord.events.getItems().size());
|
||||
assertEquals(itemId, coord.events.getItems().iterator().next().getId());
|
||||
}
|
||||
|
||||
public void testPublishAndReceiveNoPayload() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId = "TestNode" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
|
||||
|
||||
BlockingQueue<ItemEventCoordinator<Item>> queue = new ArrayBlockingQueue<ItemEventCoordinator<Item>>(3);
|
||||
|
||||
// Setup event receiver
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
|
||||
|
||||
ItemEventCoordinator<Item> sub1Handler = new ItemEventCoordinator<Item>(queue, "sub1");
|
||||
subNode.addItemEventListener(sub1Handler);
|
||||
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
// Send event
|
||||
String itemId = String.valueOf(System.currentTimeMillis());
|
||||
creatorNode.publish(new Item(itemId));
|
||||
|
||||
ItemEventCoordinator<Item> coord = queue.poll(5, TimeUnit.SECONDS);
|
||||
assertEquals(1, coord.events.getItems().size());
|
||||
assertEquals(itemId, coord.events.getItems().get(0).getId());
|
||||
}
|
||||
|
||||
public void testSendAndReceiveSimplePayload() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId = "TestNode" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, true);
|
||||
|
||||
BlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>> queue = new ArrayBlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>>(3);
|
||||
|
||||
// Setup event receiver
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
|
||||
|
||||
ItemEventCoordinator<PayloadItem<SimplePayload>> sub1Handler = new ItemEventCoordinator<PayloadItem<SimplePayload>>(queue, "sub1");
|
||||
subNode.addItemEventListener(sub1Handler);
|
||||
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
// Send event
|
||||
String itemId = String.valueOf(System.currentTimeMillis());
|
||||
String payloadString = "<book xmlns=\"pubsub:test:book\"><author>Sir Arthur Conan Doyle</author></book>";
|
||||
creatorNode.send(new PayloadItem<SimplePayload>(itemId, new SimplePayload("book", "pubsub:test:book", payloadString)));
|
||||
|
||||
ItemEventCoordinator<PayloadItem<SimplePayload>> coord = queue.poll(5, TimeUnit.SECONDS);
|
||||
assertEquals(1, coord.events.getItems().size());
|
||||
PayloadItem<SimplePayload> item = coord.events.getItems().get(0);
|
||||
assertEquals(itemId, item.getId());
|
||||
assertTrue(item.getPayload() instanceof SimplePayload);
|
||||
assertEquals(payloadString, item.getPayload().toXML());
|
||||
assertEquals("book", item.getPayload().getElementName());
|
||||
}
|
||||
|
||||
/*
|
||||
* For this test, the following extension needs to be added to the meta-inf/smack.providers file
|
||||
*
|
||||
* <extensionProvider>
|
||||
* <elementName>car</elementName>
|
||||
* <namespace>pubsub:test:vehicle</namespace>
|
||||
* <className>org.jivesoftware.smackx.pubsub.CarExtensionProvider</className>
|
||||
* </extensionProvider>
|
||||
*/
|
||||
/*
|
||||
public void testSendAndReceiveCarPayload() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId = "TestNode" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, true);
|
||||
|
||||
BlockingQueue<ItemEventCoordinator<PayloadItem<CarExtension>>> queue = new ArrayBlockingQueue<ItemEventCoordinator<PayloadItem<CarExtension>>>(3);
|
||||
|
||||
// Setup event receiver
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
Node subNode = subMgr.getNode(nodeId);
|
||||
|
||||
ItemEventCoordinator<PayloadItem<CarExtension>> sub1Handler = new ItemEventCoordinator<PayloadItem<CarExtension>>(queue, "sub1");
|
||||
subNode.addItemEventListener(sub1Handler);
|
||||
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
// Send event
|
||||
String itemId = String.valueOf(System.currentTimeMillis());
|
||||
String payloadString = "<car xmlns='pubsub:test:vehicle'><paint color='green'/><tires num='4'/></car>";
|
||||
creatorNode.send(new PayloadItem(itemId, new SimplePayload("car", "pubsub:test:vehicle", payloadString)));
|
||||
|
||||
ItemEventCoordinator<PayloadItem<CarExtension>> coord = queue.take();
|
||||
assertEquals(1, coord.events.getItems().size());
|
||||
PayloadItem item = coord.events.getItems().get(0);
|
||||
assertEquals(itemId, item.getId());
|
||||
assertTrue(item.getPayload() instanceof CarExtension);
|
||||
|
||||
CarExtension car = (CarExtension)item.getPayload();
|
||||
assertEquals("green", car.getColor());
|
||||
assertEquals(4, car.getNumTires());
|
||||
}
|
||||
*/
|
||||
|
||||
public void testSendAndReceiveMultipleSubs() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId = "TestNode" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
|
||||
|
||||
BlockingQueue<ItemEventCoordinator<Item>> queue = new ArrayBlockingQueue<ItemEventCoordinator<Item>>(3);
|
||||
|
||||
// Setup event receiver
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
|
||||
|
||||
ItemEventCoordinator<Item> sub1Handler = new ItemEventCoordinator<Item>(queue, "sub1");
|
||||
subNode.addItemEventListener(sub1Handler);
|
||||
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
ItemEventCoordinator<Item> sub2Handler = new ItemEventCoordinator<Item>(queue, "sub2");
|
||||
subNode.addItemEventListener(sub2Handler);
|
||||
Subscription sub2 = subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
// Send event
|
||||
String itemId = String.valueOf(System.currentTimeMillis());
|
||||
creatorNode.send(new Item(itemId));
|
||||
|
||||
for(int i=0; i<2; i++)
|
||||
{
|
||||
ItemEventCoordinator<Item> coord = queue.poll(10, TimeUnit.SECONDS);
|
||||
|
||||
if (coord == null)
|
||||
fail();
|
||||
assertEquals(1, coord.events.getItems().size());
|
||||
assertEquals(itemId, coord.events.getItems().iterator().next().getId());
|
||||
|
||||
if (coord.id.equals("sub1") || coord.id.equals("sub2"))
|
||||
{
|
||||
assertEquals(2, coord.events.getSubscriptions().size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void testSendAndReceiveMultipleItems() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId = "TestNode" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
|
||||
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, true);
|
||||
|
||||
BlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>> queue = new ArrayBlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>>(3);
|
||||
ItemEventCoordinator<PayloadItem<SimplePayload>> creatorHandler = new ItemEventCoordinator<PayloadItem<SimplePayload>>(queue, "creator");
|
||||
creatorNode.addItemEventListener(creatorHandler);
|
||||
creatorNode.subscribe(getConnection(0).getUser());
|
||||
|
||||
// Setup event receiver
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
|
||||
|
||||
ItemEventCoordinator<PayloadItem<SimplePayload>> sub1Handler = new ItemEventCoordinator<PayloadItem<SimplePayload>>(queue, "sub1");
|
||||
subNode.addItemEventListener(sub1Handler);
|
||||
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
ItemEventCoordinator<PayloadItem<SimplePayload>> sub2Handler = new ItemEventCoordinator<PayloadItem<SimplePayload>>(queue, "sub2");
|
||||
subNode.addItemEventListener(sub2Handler);
|
||||
Subscription sub2 = subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
assertEquals(Subscription.State.subscribed, sub1.getState());
|
||||
assertEquals(Subscription.State.subscribed, sub2.getState());
|
||||
|
||||
// Send event
|
||||
String itemId = String.valueOf(System.currentTimeMillis());
|
||||
|
||||
Collection<PayloadItem<SimplePayload>> items = new ArrayList<PayloadItem<SimplePayload>>(3);
|
||||
String ids[] = {"First-" + itemId, "Second-" + itemId, "Third-" + itemId};
|
||||
items.add(new PayloadItem<SimplePayload>(ids[0], new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='1'/>")));
|
||||
items.add(new PayloadItem<SimplePayload>(ids[1], new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='1'/>")));
|
||||
items.add(new PayloadItem<SimplePayload>(ids[2], new SimplePayload("a", "pubsub:test", "<a xmlns='pubsub:test' href='1'/>")));
|
||||
creatorNode.send(items);
|
||||
|
||||
for(int i=0; i<3; i++)
|
||||
{
|
||||
ItemEventCoordinator<PayloadItem<SimplePayload>> coord = queue.poll(5, TimeUnit.SECONDS);
|
||||
if (coord == creatorHandler)
|
||||
assertEquals(1, coord.events.getSubscriptions().size());
|
||||
else
|
||||
assertEquals(2, coord.events.getSubscriptions().size());
|
||||
List<PayloadItem<SimplePayload>> itemResults = coord.events.getItems();
|
||||
assertEquals(3, itemResults.size());
|
||||
|
||||
// assertEquals(ids[0], itemResults.get(0).getId());
|
||||
// assertEquals("<a xmlns='pubsub:test' href='1'/>", itemResults.get(0).getPayload().toXML().replace('\"', '\''));
|
||||
// assertEquals(ids[1], itemResults.get(1).getId());
|
||||
// assertEquals("<a xmlns='pubsub:test' href='2'/>", itemResults.get(1).getPayload().toXML().replace('\"', '\''));
|
||||
// assertEquals(ids[21], itemResults.get(2).getId());
|
||||
// assertEquals("<a xmlns='pubsub:test' href='3'/>", itemResults.get(3).getPayload().toXML().replace('\"', '\''));
|
||||
}
|
||||
}
|
||||
|
||||
public void testSendAndReceiveDelayed() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId = "TestNode" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
|
||||
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
|
||||
|
||||
// Send event
|
||||
String itemId = String.valueOf("DelayId-" + System.currentTimeMillis());
|
||||
String payloadString = "<book xmlns='pubsub:test:book'><author>Sir Arthur Conan Doyle</author></book>";
|
||||
creatorNode.send(new PayloadItem<SimplePayload>(itemId, new SimplePayload("book", "pubsub:test:book", payloadString)));
|
||||
|
||||
Thread.sleep(1000);
|
||||
|
||||
BlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>> queue = new ArrayBlockingQueue<ItemEventCoordinator<PayloadItem<SimplePayload>>>(3);
|
||||
|
||||
// Setup event receiver
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
|
||||
|
||||
ItemEventCoordinator<PayloadItem<SimplePayload>> sub1Handler = new ItemEventCoordinator<PayloadItem<SimplePayload>>(queue, "sub1");
|
||||
subNode.addItemEventListener(sub1Handler);
|
||||
Subscription sub1 = subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
ItemEventCoordinator<PayloadItem<SimplePayload>> coord = queue.poll(5, TimeUnit.SECONDS);
|
||||
assertTrue(coord.events.isDelayed());
|
||||
assertNotNull(coord.events.getPublishedDate());
|
||||
}
|
||||
|
||||
public void testDeleteItemAndNotify() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId = "TestNode" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
|
||||
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
|
||||
|
||||
BlockingQueue<ItemDeleteCoordinator> queue = new ArrayBlockingQueue<ItemDeleteCoordinator>(3);
|
||||
|
||||
// Setup event receiver
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
|
||||
|
||||
ItemDeleteCoordinator sub1Handler = new ItemDeleteCoordinator(queue, "sub1");
|
||||
subNode.addItemDeleteListener(sub1Handler);
|
||||
subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
// Send event
|
||||
String itemId = String.valueOf(System.currentTimeMillis());
|
||||
|
||||
Collection<Item> items = new ArrayList<Item>(3);
|
||||
String id1 = "First-" + itemId;
|
||||
String id2 = "Second-" + itemId;
|
||||
String id3 = "Third-" + itemId;
|
||||
items.add(new Item(id1));
|
||||
items.add(new Item(id2));
|
||||
items.add(new Item(id3));
|
||||
creatorNode.send(items);
|
||||
|
||||
creatorNode.deleteItem(id1);
|
||||
|
||||
ItemDeleteCoordinator coord = queue.poll(5, TimeUnit.SECONDS);
|
||||
assertEquals(1, coord.event.getItemIds().size());
|
||||
assertEquals(id1, coord.event.getItemIds().get(0));
|
||||
|
||||
creatorNode.deleteItem(Arrays.asList(id2, id3));
|
||||
|
||||
coord = queue.poll(5, TimeUnit.SECONDS);
|
||||
assertEquals(2, coord.event.getItemIds().size());
|
||||
assertTrue(coord.event.getItemIds().contains(id2));
|
||||
assertTrue(coord.event.getItemIds().contains(id3));
|
||||
}
|
||||
|
||||
public void testPurgeAndNotify() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId = "TestNode" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
|
||||
LeafNode creatorNode = getPubnode(creatorMgr, nodeId, true, false);
|
||||
|
||||
BlockingQueue<ItemDeleteCoordinator> queue = new ArrayBlockingQueue<ItemDeleteCoordinator>(3);
|
||||
|
||||
// Setup event receiver
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode = (LeafNode)subMgr.getNode(nodeId);
|
||||
|
||||
ItemDeleteCoordinator sub1Handler = new ItemDeleteCoordinator(queue, "sub1");
|
||||
subNode.addItemDeleteListener(sub1Handler);
|
||||
subNode.subscribe(getConnection(1).getUser());
|
||||
|
||||
// Send event
|
||||
String itemId = String.valueOf(System.currentTimeMillis());
|
||||
|
||||
Collection<Item> items = new ArrayList<Item>(3);
|
||||
String id1 = "First-" + itemId;
|
||||
String id2 = "Second-" + itemId;
|
||||
String id3 = "Third-" + itemId;
|
||||
items.add(new Item(id1));
|
||||
items.add(new Item(id2));
|
||||
items.add(new Item(id3));
|
||||
creatorNode.send(items);
|
||||
|
||||
creatorNode.deleteAllItems();
|
||||
|
||||
ItemDeleteCoordinator coord = queue.poll(5, TimeUnit.SECONDS);
|
||||
assertNull(nodeId, coord.event);
|
||||
}
|
||||
|
||||
public void testListenerMultipleNodes() throws Exception
|
||||
{
|
||||
// Setup event source
|
||||
String nodeId1 = "Node-1-" + System.currentTimeMillis();
|
||||
PubSubManager creatorMgr = new PubSubManager(getConnection(0), getService());
|
||||
String nodeId2 = "Node-2-" + System.currentTimeMillis();
|
||||
|
||||
LeafNode creatorNode1 = getPubnode(creatorMgr, nodeId1, true, false);
|
||||
LeafNode creatorNode2 = getPubnode(creatorMgr, nodeId2, true, false);
|
||||
|
||||
BlockingQueue<ItemEventCoordinator<Item>> queue = new ArrayBlockingQueue<ItemEventCoordinator<Item>>(3);
|
||||
|
||||
PubSubManager subMgr = new PubSubManager(getConnection(1), getService());
|
||||
LeafNode subNode1 = (LeafNode)subMgr.getNode(nodeId1);
|
||||
LeafNode subNode2 = (LeafNode)subMgr.getNode(nodeId2);
|
||||
|
||||
subNode1.addItemEventListener(new ItemEventCoordinator<Item>(queue, "sub1"));
|
||||
subNode2.addItemEventListener(new ItemEventCoordinator<Item>(queue, "sub2"));
|
||||
|
||||
subNode1.subscribe(getConnection(1).getUser());
|
||||
subNode2.subscribe(getConnection(1).getUser());
|
||||
|
||||
creatorNode1.send(new Item("item1"));
|
||||
creatorNode2.send(new Item("item2"));
|
||||
boolean check1 = false;
|
||||
boolean check2 = false;
|
||||
|
||||
for (int i=0; i<2; i++)
|
||||
{
|
||||
ItemEventCoordinator<Item> event = queue.poll(5, TimeUnit.SECONDS);
|
||||
|
||||
if (event.id.equals("sub1"))
|
||||
{
|
||||
assertEquals(event.events.getNodeId(), nodeId1);
|
||||
check1 = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
assertEquals(event.events.getNodeId(), nodeId2);
|
||||
check2 = true;
|
||||
}
|
||||
}
|
||||
assertTrue(check1);
|
||||
assertTrue(check2);
|
||||
}
|
||||
|
||||
class ItemEventCoordinator <T extends Item> implements ItemEventListener<T>
|
||||
{
|
||||
private BlockingQueue<ItemEventCoordinator<T>> theQueue;
|
||||
private ItemPublishEvent<T> events;
|
||||
private String id;
|
||||
|
||||
ItemEventCoordinator(BlockingQueue<ItemEventCoordinator<T>> queue, String id)
|
||||
{
|
||||
theQueue = queue;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void handlePublishedItems(ItemPublishEvent<T> items)
|
||||
{
|
||||
events = items;
|
||||
theQueue.add(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return "ItemEventCoordinator: " + id;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class NodeConfigCoordinator implements NodeConfigListener
|
||||
{
|
||||
private BlockingQueue<NodeConfigCoordinator> theQueue;
|
||||
private String id;
|
||||
private ConfigurationEvent event;
|
||||
|
||||
NodeConfigCoordinator(BlockingQueue<NodeConfigCoordinator> queue, String id)
|
||||
{
|
||||
theQueue = queue;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void handleNodeConfiguration(ConfigurationEvent config)
|
||||
{
|
||||
event = config;
|
||||
theQueue.add(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return "NodeConfigCoordinator: " + id;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class ItemDeleteCoordinator implements ItemDeleteListener
|
||||
{
|
||||
private BlockingQueue<ItemDeleteCoordinator> theQueue;
|
||||
private String id;
|
||||
private ItemDeleteEvent event;
|
||||
|
||||
ItemDeleteCoordinator(BlockingQueue<ItemDeleteCoordinator> queue, String id)
|
||||
{
|
||||
theQueue = queue;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void handleDeletedItems(ItemDeleteEvent delEvent)
|
||||
{
|
||||
event = delEvent;
|
||||
theQueue.add(this);
|
||||
}
|
||||
|
||||
|
||||
public void handlePurge()
|
||||
{
|
||||
event = null;
|
||||
theQueue.add(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return "ItemDeleteCoordinator: " + id;
|
||||
}
|
||||
}
|
||||
|
||||
static private LeafNode getPubnode(PubSubManager manager, String id, boolean persistItems, boolean deliverPayload)
|
||||
throws XMPPException
|
||||
{
|
||||
ConfigureForm form = new ConfigureForm(FormType.submit);
|
||||
form.setPersistentItems(persistItems);
|
||||
form.setDeliverPayloads(deliverPayload);
|
||||
form.setAccessModel(AccessModel.open);
|
||||
return (LeafNode)manager.createNode(id, form);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class TestMessageContent extends TestCase
|
||||
{
|
||||
String payloadXmlWithNS = "<book xmlns='pubsub:test:book'><author name='Stephen King'/></book>";
|
||||
|
||||
public void testItemWithId()
|
||||
{
|
||||
Item item = new Item("123");
|
||||
assertEquals("<item id='123'/>", item.toXML());
|
||||
assertEquals("item", item.getElementName());
|
||||
assertNull(item.getNamespace());
|
||||
}
|
||||
|
||||
public void testItemWithNoId()
|
||||
{
|
||||
Item item = new Item();
|
||||
assertEquals("<item/>", item.toXML());
|
||||
|
||||
Item itemNull = new Item(null);
|
||||
assertEquals("<item/>", itemNull.toXML());
|
||||
}
|
||||
|
||||
public void testSimplePayload()
|
||||
{
|
||||
SimplePayload payloadNS = new SimplePayload("book", "pubsub:test:book", payloadXmlWithNS);
|
||||
|
||||
assertEquals(payloadXmlWithNS, payloadNS.toXML());
|
||||
|
||||
String payloadXmlWithNoNS = "<book><author name='Stephen King'/></book>";
|
||||
SimplePayload payloadNoNS = new SimplePayload("book", null, "<book><author name='Stephen King'/></book>");
|
||||
|
||||
assertEquals(payloadXmlWithNoNS, payloadNoNS.toXML());
|
||||
|
||||
}
|
||||
|
||||
public void testPayloadItemWithId()
|
||||
{
|
||||
SimplePayload payload = new SimplePayload("book", "pubsub:test:book", payloadXmlWithNS);
|
||||
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>("123", payload);
|
||||
|
||||
String xml = "<item id='123'>" + payloadXmlWithNS + "</item>";
|
||||
assertEquals(xml, item.toXML());
|
||||
assertEquals("item", item.getElementName());
|
||||
}
|
||||
|
||||
public void testPayloadItemWithNoId()
|
||||
{
|
||||
SimplePayload payload = new SimplePayload("book", "pubsub:test:book", payloadXmlWithNS);
|
||||
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>(null, payload);
|
||||
|
||||
String xml = "<item>" + payloadXmlWithNS + "</item>";
|
||||
assertEquals(xml, item.toXML());
|
||||
}
|
||||
|
||||
public void testPayloadItemWithIdNoPayload()
|
||||
{
|
||||
try
|
||||
{
|
||||
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>("123", null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException e)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public void testPayloadItemWithNoIdNoPayload()
|
||||
{
|
||||
try
|
||||
{
|
||||
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>(null, null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException e)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public void testRetractItem()
|
||||
{
|
||||
RetractItem item = new RetractItem("1234");
|
||||
|
||||
assertEquals("<retract id='1234'/>", item.toXML());
|
||||
assertEquals("retract", item.getElementName());
|
||||
|
||||
try
|
||||
{
|
||||
new RetractItem(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException e)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetItemsRequest()
|
||||
{
|
||||
GetItemsRequest request = new GetItemsRequest("testId");
|
||||
assertEquals("<items node='testId'/>", request.toXML());
|
||||
|
||||
request = new GetItemsRequest("testId", 5);
|
||||
assertEquals("<items node='testId' max_items='5'/>", request.toXML());
|
||||
|
||||
request = new GetItemsRequest("testId", "qwerty");
|
||||
assertEquals("<items node='testId' subid='qwerty'/>", request.toXML());
|
||||
|
||||
request = new GetItemsRequest("testId", "qwerty", 5);
|
||||
assertEquals("<items node='testId' subid='qwerty' max_items='5'/>", request.toXML());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub.test;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.test.SmackTestCase;
|
||||
import org.jivesoftware.smackx.pubsub.AccessModel;
|
||||
import org.jivesoftware.smackx.pubsub.ConfigureForm;
|
||||
import org.jivesoftware.smackx.pubsub.FormType;
|
||||
import org.jivesoftware.smackx.pubsub.LeafNode;
|
||||
import org.jivesoftware.smackx.pubsub.PubSubManager;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
abstract public class PubSubTestCase extends SmackTestCase
|
||||
{
|
||||
private PubSubManager[] manager;
|
||||
|
||||
public PubSubTestCase(String arg0)
|
||||
{
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
public PubSubTestCase()
|
||||
{
|
||||
super("PubSub Test Case");
|
||||
}
|
||||
|
||||
protected LeafNode getRandomPubnode(PubSubManager pubMgr, boolean persistItems, boolean deliverPayload) throws XMPPException
|
||||
{
|
||||
ConfigureForm form = new ConfigureForm(FormType.submit);
|
||||
form.setPersistentItems(persistItems);
|
||||
form.setDeliverPayloads(deliverPayload);
|
||||
form.setAccessModel(AccessModel.open);
|
||||
return (LeafNode)pubMgr.createNode("/test/Pubnode" + System.currentTimeMillis(), form);
|
||||
}
|
||||
|
||||
protected LeafNode getPubnode(PubSubManager pubMgr, boolean persistItems, boolean deliverPayload, String nodeId) throws XMPPException
|
||||
{
|
||||
LeafNode node = null;
|
||||
|
||||
try
|
||||
{
|
||||
node = (LeafNode)pubMgr.getNode(nodeId);
|
||||
}
|
||||
catch (XMPPException e)
|
||||
{
|
||||
ConfigureForm form = new ConfigureForm(FormType.submit);
|
||||
form.setPersistentItems(persistItems);
|
||||
form.setDeliverPayloads(deliverPayload);
|
||||
form.setAccessModel(AccessModel.open);
|
||||
node = (LeafNode)pubMgr.createNode(nodeId, form);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
protected PubSubManager getManager(int idx)
|
||||
{
|
||||
if (manager == null)
|
||||
{
|
||||
manager = new PubSubManager[getMaxConnections()];
|
||||
|
||||
for(int i=0; i<manager.length; i++)
|
||||
{
|
||||
manager[i] = new PubSubManager(getConnection(i), getService());
|
||||
}
|
||||
}
|
||||
return manager[idx];
|
||||
}
|
||||
|
||||
protected String getService()
|
||||
{
|
||||
return "pubsub." + getServiceName();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2009 Robin Collier
|
||||
*
|
||||
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smackx.pubsub.test;
|
||||
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smackx.pubsub.LeafNode;
|
||||
import org.jivesoftware.smackx.pubsub.PubSubManager;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class SingleUserTestCase extends PubSubTestCase
|
||||
{
|
||||
protected PubSubManager getManager()
|
||||
{
|
||||
return getManager(0);
|
||||
}
|
||||
|
||||
protected LeafNode getPubnode(boolean persistItems, boolean deliverPayload) throws XMPPException
|
||||
{
|
||||
return getRandomPubnode(getManager(), persistItems, deliverPayload);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getMaxConnections()
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue