mirror of
https://github.com/vanitasvitae/Smack.git
synced 2025-09-10 17:49:38 +02:00
Prefix subprojects with 'smack-'
instead of using the old baseName=smack appendix=project.name approach, we are now going convention over configuration and renaming the subprojects directories to the proper name. Having a prefix is actually very helpful, because the resulting libraries will be named like the subproject. And a core-4.0.0-rc1.jar is not as explicit about what it actually *is* as a smack-core-4.0.0-rc1.jar. SMACK-265
This commit is contained in:
parent
b6fb1f3743
commit
91fd15ad86
758 changed files with 42 additions and 42 deletions
|
@ -0,0 +1,445 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2010 Jive Software.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smack;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import org.jivesoftware.smack.ChatManager.MatchMode;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.packet.Message.Type;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ChatConnectionTest {
|
||||
|
||||
private DummyConnection connection;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
connection = getConnection();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
if (connection != null)
|
||||
connection.disconnect();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateDefaultSetNormalIncluded() {
|
||||
ChatManager.setDefaultIsNormalIncluded(false);
|
||||
assertFalse(ChatManager.getInstanceFor(getConnection()).isNormalIncluded());
|
||||
|
||||
ChatManager.setDefaultIsNormalIncluded(true);
|
||||
assertTrue(ChatManager.getInstanceFor(getConnection()).isNormalIncluded());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateDefaultSetMatchMode() {
|
||||
ChatManager.setDefaultMatchMode(MatchMode.NONE);
|
||||
assertEquals(MatchMode.NONE, ChatManager.getInstanceFor(getConnection()).getMatchMode());
|
||||
|
||||
ChatManager.setDefaultMatchMode(MatchMode.BARE_JID);
|
||||
assertEquals(MatchMode.BARE_JID, ChatManager.getInstanceFor(getConnection()).getMatchMode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateMessageTypeWithDefaults() {
|
||||
DummyConnection dc = getConnection();
|
||||
ChatManager cm = ChatManager.getInstanceFor(dc);
|
||||
TestChatManagerListener listener = new TestChatManagerListener();
|
||||
cm.addChatListener(listener);
|
||||
Message incomingChat = createChatPacket("134", true);
|
||||
incomingChat.setType(Type.chat);
|
||||
processServerMessage(incomingChat, dc);
|
||||
assertNotNull(listener.getNewChat());
|
||||
|
||||
dc = getConnection();
|
||||
cm = ChatManager.getInstanceFor(dc);
|
||||
listener = new TestChatManagerListener();
|
||||
cm.addChatListener(listener);
|
||||
incomingChat = createChatPacket("134", true);
|
||||
incomingChat.setType(Type.normal);
|
||||
processServerMessage(incomingChat, dc);
|
||||
assertNotNull(listener.getNewChat());
|
||||
|
||||
dc = getConnection();
|
||||
cm = ChatManager.getInstanceFor(dc);
|
||||
listener = new TestChatManagerListener();
|
||||
cm.addChatListener(listener);
|
||||
incomingChat = createChatPacket("134", true);
|
||||
incomingChat.setType(Type.groupchat);
|
||||
processServerMessage(incomingChat, dc);
|
||||
assertNull(listener.getNewChat());
|
||||
|
||||
dc = getConnection();
|
||||
cm = ChatManager.getInstanceFor(dc);
|
||||
listener = new TestChatManagerListener();
|
||||
cm.addChatListener(listener);
|
||||
incomingChat = createChatPacket("134", true);
|
||||
incomingChat.setType(Type.headline);
|
||||
processServerMessage(incomingChat, dc);
|
||||
assertNull(listener.getNewChat());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateMessageTypeWithNoNormal() {
|
||||
DummyConnection dc = getConnection();
|
||||
ChatManager cm = ChatManager.getInstanceFor(dc);
|
||||
cm.setNormalIncluded(false);
|
||||
TestChatManagerListener listener = new TestChatManagerListener();
|
||||
cm.addChatListener(listener);
|
||||
Message incomingChat = createChatPacket("134", true);
|
||||
incomingChat.setType(Type.chat);
|
||||
processServerMessage(incomingChat, dc);
|
||||
assertNotNull(listener.getNewChat());
|
||||
|
||||
dc = getConnection();
|
||||
cm = ChatManager.getInstanceFor(dc);
|
||||
cm.setNormalIncluded(false);
|
||||
listener = new TestChatManagerListener();
|
||||
cm.addChatListener(listener);
|
||||
incomingChat = createChatPacket("134", true);
|
||||
incomingChat.setType(Type.normal);
|
||||
processServerMessage(incomingChat, dc);
|
||||
assertNull(listener.getNewChat());
|
||||
}
|
||||
|
||||
// No thread behaviour
|
||||
@Test
|
||||
public void chatMatchedOnJIDWhenNoThreadBareMode() {
|
||||
// MatchMode.BARE_JID is the default, so setting required.
|
||||
DummyConnection con = getConnection();
|
||||
TestMessageListener msgListener = new TestMessageListener();
|
||||
TestChatManagerListener listener = new TestChatManagerListener(msgListener);
|
||||
ChatManager cm = ChatManager.getInstanceFor(con);
|
||||
cm.addChatListener(listener);
|
||||
Packet incomingChat = createChatPacket(null, true);
|
||||
processServerMessage(incomingChat, con);
|
||||
Chat newChat = listener.getNewChat();
|
||||
assertNotNull(newChat);
|
||||
|
||||
// Should match on chat with full jid
|
||||
incomingChat = createChatPacket(null, true);
|
||||
processServerMessage(incomingChat, con);
|
||||
assertEquals(2, msgListener.getNumMessages());
|
||||
|
||||
// Should match on chat with bare jid
|
||||
incomingChat = createChatPacket(null, false);
|
||||
processServerMessage(incomingChat, con);
|
||||
assertEquals(3, msgListener.getNumMessages());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void chatMatchedOnJIDWhenNoThreadJidMode() {
|
||||
DummyConnection con = getConnection();
|
||||
TestMessageListener msgListener = new TestMessageListener();
|
||||
TestChatManagerListener listener = new TestChatManagerListener(msgListener);
|
||||
ChatManager cm = ChatManager.getInstanceFor(con);
|
||||
cm.setMatchMode(MatchMode.SUPPLIED_JID);
|
||||
cm.addChatListener(listener);
|
||||
Packet incomingChat = createChatPacket(null, true);
|
||||
processServerMessage(incomingChat, con);
|
||||
Chat newChat = listener.getNewChat();
|
||||
assertNotNull(newChat);
|
||||
cm.removeChatListener(listener);
|
||||
|
||||
// Should match on chat with full jid
|
||||
incomingChat = createChatPacket(null, true);
|
||||
processServerMessage(incomingChat, con);
|
||||
assertEquals(2, msgListener.getNumMessages());
|
||||
|
||||
// Should not match on chat with bare jid
|
||||
TestChatManagerListener listener2 = new TestChatManagerListener();
|
||||
cm.addChatListener(listener2);
|
||||
incomingChat = createChatPacket(null, false);
|
||||
processServerMessage(incomingChat, con);
|
||||
assertEquals(2, msgListener.getNumMessages());
|
||||
assertNotNull(listener2.getNewChat());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void chatMatchedOnJIDWhenNoThreadNoneMode() {
|
||||
DummyConnection con = getConnection();
|
||||
TestMessageListener msgListener = new TestMessageListener();
|
||||
TestChatManagerListener listener = new TestChatManagerListener(msgListener);
|
||||
ChatManager cm = ChatManager.getInstanceFor(con);
|
||||
cm.setMatchMode(MatchMode.NONE);
|
||||
cm.addChatListener(listener);
|
||||
Packet incomingChat = createChatPacket(null, true);
|
||||
processServerMessage(incomingChat, con);
|
||||
Chat newChat = listener.getNewChat();
|
||||
assertNotNull(newChat);
|
||||
assertEquals(1, msgListener.getNumMessages());
|
||||
cm.removeChatListener(listener);
|
||||
|
||||
// Should not match on chat with full jid
|
||||
TestChatManagerListener listener2 = new TestChatManagerListener();
|
||||
cm.addChatListener(listener2);
|
||||
incomingChat = createChatPacket(null, true);
|
||||
processServerMessage(incomingChat, con);
|
||||
assertEquals(1, msgListener.getNumMessages());
|
||||
assertNotNull(newChat);
|
||||
cm.removeChatListener(listener2);
|
||||
|
||||
// Should not match on chat with bare jid
|
||||
TestChatManagerListener listener3 = new TestChatManagerListener();
|
||||
cm.addChatListener(listener3);
|
||||
incomingChat = createChatPacket(null, false);
|
||||
processServerMessage(incomingChat, con);
|
||||
assertEquals(1, msgListener.getNumMessages());
|
||||
assertNotNull(listener3.getNewChat());
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm that an existing chat created with a base jid is matched to an incoming chat message that has no thread
|
||||
* id and the user is a full jid.
|
||||
*/
|
||||
@Test
|
||||
public void chatFoundWhenNoThreadFullJid() {
|
||||
TestChatManagerListener listener = new TestChatManagerListener();
|
||||
ChatManager cm = ChatManager.getInstanceFor(connection);
|
||||
cm.addChatListener(listener);
|
||||
Chat outgoing = cm.createChat("you@testserver", null);
|
||||
|
||||
Packet incomingChat = createChatPacket(null, true);
|
||||
processServerMessage(incomingChat);
|
||||
|
||||
Chat newChat = listener.getNewChat();
|
||||
assertNotNull(newChat);
|
||||
assertTrue(newChat == outgoing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm that an existing chat created with a base jid is matched to an incoming chat message that has no thread
|
||||
* id and the user is a base jid.
|
||||
*/
|
||||
@Test
|
||||
public void chatFoundWhenNoThreadBaseJid() {
|
||||
TestChatManagerListener listener = new TestChatManagerListener();
|
||||
ChatManager cm = ChatManager.getInstanceFor(connection);
|
||||
cm.addChatListener(listener);
|
||||
Chat outgoing = cm.createChat("you@testserver", null);
|
||||
|
||||
Packet incomingChat = createChatPacket(null, false);
|
||||
processServerMessage(incomingChat);
|
||||
|
||||
Chat newChat = listener.getNewChat();
|
||||
assertNotNull(newChat);
|
||||
assertTrue(newChat == outgoing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm that an existing chat created with a base jid is matched to an incoming chat message that has the same id
|
||||
* and the user is a full jid.
|
||||
*/
|
||||
@Test
|
||||
public void chatFoundWithSameThreadFullJid() {
|
||||
TestChatManagerListener listener = new TestChatManagerListener();
|
||||
ChatManager cm = ChatManager.getInstanceFor(connection);
|
||||
cm.addChatListener(listener);
|
||||
Chat outgoing = cm.createChat("you@testserver", null);
|
||||
|
||||
Packet incomingChat = createChatPacket(outgoing.getThreadID(), true);
|
||||
processServerMessage(incomingChat);
|
||||
|
||||
Chat newChat = listener.getNewChat();
|
||||
assertNotNull(newChat);
|
||||
assertTrue(newChat == outgoing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm that an existing chat created with a base jid is matched to an incoming chat message that has the same id
|
||||
* and the user is a base jid.
|
||||
*/
|
||||
@Test
|
||||
public void chatFoundWithSameThreadBaseJid() {
|
||||
TestChatManagerListener listener = new TestChatManagerListener();
|
||||
ChatManager cm = ChatManager.getInstanceFor(connection);
|
||||
cm.addChatListener(listener);
|
||||
Chat outgoing = cm.createChat("you@testserver", null);
|
||||
|
||||
Packet incomingChat = createChatPacket(outgoing.getThreadID(), false);
|
||||
processServerMessage(incomingChat);
|
||||
|
||||
Chat newChat = listener.getNewChat();
|
||||
assertNotNull(newChat);
|
||||
assertTrue(newChat == outgoing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm that an existing chat created with a base jid is not matched to an incoming chat message that has a
|
||||
* different id and the same user as a base jid.
|
||||
*/
|
||||
@Test
|
||||
public void chatNotFoundWithDiffThreadBaseJid() {
|
||||
TestChatManagerListener listener = new TestChatManagerListener();
|
||||
ChatManager cm = ChatManager.getInstanceFor(connection);
|
||||
cm.addChatListener(listener);
|
||||
Chat outgoing = cm.createChat("you@testserver", null);
|
||||
|
||||
Packet incomingChat = createChatPacket(outgoing.getThreadID() + "ff", false);
|
||||
processServerMessage(incomingChat);
|
||||
|
||||
Chat newChat = listener.getNewChat();
|
||||
assertNotNull(newChat);
|
||||
assertFalse(newChat == outgoing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm that an existing chat created with a base jid is not matched to an incoming chat message that has a
|
||||
* different id and the same base jid.
|
||||
*/
|
||||
@Test
|
||||
public void chatNotFoundWithDiffThreadFullJid() {
|
||||
TestChatManagerListener listener = new TestChatManagerListener();
|
||||
ChatManager cm = ChatManager.getInstanceFor(connection);
|
||||
cm.addChatListener(listener);
|
||||
Chat outgoing = cm.createChat("you@testserver", null);
|
||||
|
||||
Packet incomingChat = createChatPacket(outgoing.getThreadID() + "ff", true);
|
||||
processServerMessage(incomingChat);
|
||||
|
||||
Chat newChat = listener.getNewChat();
|
||||
assertNotNull(newChat);
|
||||
assertFalse(newChat == outgoing);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void chatNotMatchedWithTypeNormal() {
|
||||
TestChatManagerListener listener = new TestChatManagerListener();
|
||||
DummyConnection con = getConnection();
|
||||
ChatManager cm = ChatManager.getInstanceFor(con);
|
||||
cm.setNormalIncluded(false);
|
||||
cm.addChatListener(listener);
|
||||
|
||||
Message incomingChat = createChatPacket(null, false);
|
||||
incomingChat.setType(Type.normal);
|
||||
processServerMessage(incomingChat);
|
||||
|
||||
assertNull(listener.getNewChat());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private ChatManager getChatManager(boolean includeNormal, MatchMode mode) {
|
||||
ChatManager cm = ChatManager.getInstanceFor(getConnection());
|
||||
cm.setMatchMode(mode);
|
||||
cm.setNormalIncluded(includeNormal);
|
||||
return cm;
|
||||
}
|
||||
|
||||
private DummyConnection getConnection() {
|
||||
DummyConnection con = new DummyConnection();
|
||||
|
||||
try {
|
||||
con.connect();
|
||||
con.login("me", "secret");
|
||||
} catch (Exception e) {
|
||||
// No need for handling in a dummy connection.
|
||||
}
|
||||
return con;
|
||||
}
|
||||
private Message createChatPacket(final String threadId, final boolean isFullJid) {
|
||||
Message chatMsg = new Message("me@testserver", Message.Type.chat);
|
||||
chatMsg.setBody("the body message - " + System.currentTimeMillis());
|
||||
chatMsg.setFrom("you@testserver" + (isFullJid ? "/resource" : ""));
|
||||
|
||||
if (threadId != null)
|
||||
chatMsg.setThread(threadId);
|
||||
return chatMsg;
|
||||
}
|
||||
|
||||
private void processServerMessage(Packet incomingChat) {
|
||||
processServerMessage(incomingChat, connection);
|
||||
}
|
||||
|
||||
private void processServerMessage(Packet incomingChat, DummyConnection con) {
|
||||
TestChatServer chatServer = new TestChatServer(incomingChat, con);
|
||||
chatServer.start();
|
||||
try {
|
||||
chatServer.join();
|
||||
} catch (InterruptedException e) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
class TestChatManagerListener implements ChatManagerListener {
|
||||
private Chat newChat;
|
||||
private MessageListener listener;
|
||||
|
||||
public TestChatManagerListener(TestMessageListener msgListener) {
|
||||
listener = msgListener;
|
||||
}
|
||||
|
||||
public TestChatManagerListener() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void chatCreated(Chat chat, boolean createdLocally) {
|
||||
newChat = chat;
|
||||
|
||||
if (listener != null)
|
||||
newChat.addMessageListener(listener);
|
||||
}
|
||||
|
||||
public Chat getNewChat() {
|
||||
return newChat;
|
||||
}
|
||||
}
|
||||
|
||||
private class TestChatServer extends Thread {
|
||||
private Packet chatPacket;
|
||||
private DummyConnection con;
|
||||
|
||||
TestChatServer(Packet chatMsg, DummyConnection conect) {
|
||||
chatPacket = chatMsg;
|
||||
con = conect;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
con.processPacket(chatPacket);
|
||||
}
|
||||
}
|
||||
|
||||
private class TestMessageListener implements MessageListener {
|
||||
private Chat msgChat;
|
||||
private int counter = 0;
|
||||
|
||||
@Override
|
||||
public void processMessage(Chat chat, Message message) {
|
||||
msgChat = chat;
|
||||
counter++;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public Chat getChat() {
|
||||
return msgChat;
|
||||
}
|
||||
|
||||
public int getNumMessages() {
|
||||
return counter;
|
||||
}
|
||||
};
|
||||
}
|
|
@ -0,0 +1,224 @@
|
|||
/**
|
||||
*
|
||||
* Copyright the original author or authors
|
||||
*
|
||||
* 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 static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.jivesoftware.smack.packet.RosterPacket;
|
||||
import org.jivesoftware.smack.packet.RosterPacket.Item;
|
||||
import org.jivesoftware.smack.packet.RosterPacket.ItemStatus;
|
||||
import org.jivesoftware.smack.packet.RosterPacket.ItemType;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
/**
|
||||
* Tests the implementation of {@link DirectoryRosterStore}.
|
||||
*
|
||||
* @author Lars Noschinski
|
||||
*/
|
||||
public class DirectoryRosterStoreTest {
|
||||
|
||||
@Rule
|
||||
public TemporaryFolder tmpFolder = new TemporaryFolder();
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that opening an uninitialized directory fails.
|
||||
*/
|
||||
@Test
|
||||
public void testStoreUninitialized() throws IOException {
|
||||
File storeDir = tmpFolder.newFolder();
|
||||
assertNull(DirectoryRosterStore.open(storeDir));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that an initialized directory is empty.
|
||||
*/
|
||||
@Test
|
||||
public void testStoreInitializedEmpty() throws IOException {
|
||||
File storeDir = tmpFolder.newFolder();
|
||||
DirectoryRosterStore store = DirectoryRosterStore.init(storeDir);
|
||||
assertNotNull("Initialization returns store", store);
|
||||
assertEquals("Freshly initialized store must have empty version",
|
||||
"", store.getRosterVersion());
|
||||
assertEquals("Freshly initialized store must have no entries",
|
||||
0, store.getEntries().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests adding and removing entries
|
||||
*/
|
||||
@Test
|
||||
public void testStoreAddRemove() throws IOException {
|
||||
File storeDir = tmpFolder.newFolder();
|
||||
DirectoryRosterStore store = DirectoryRosterStore.init(storeDir);
|
||||
|
||||
assertEquals("Initial roster version", "", store.getRosterVersion());
|
||||
|
||||
String userName = "user@example.com";
|
||||
|
||||
final RosterPacket.Item item1 = new Item(userName, null);
|
||||
final String version1 = "1";
|
||||
store.addEntry(item1, version1);
|
||||
|
||||
assertEquals("Adding entry sets version correctly", version1, store.getRosterVersion());
|
||||
|
||||
RosterPacket.Item storedItem = store.getEntry(userName);
|
||||
assertNotNull("Added entry not found found", storedItem);
|
||||
assertEquals("User of added entry",
|
||||
item1.getUser(), storedItem.getUser());
|
||||
assertEquals("Name of added entry",
|
||||
item1.getName(), storedItem.getName());
|
||||
assertEquals("Groups", item1.getGroupNames(), storedItem.getGroupNames());
|
||||
assertEquals("ItemType of added entry",
|
||||
item1.getItemType(), storedItem.getItemType());
|
||||
assertEquals("ItemStatus of added entry",
|
||||
item1.getItemStatus(), storedItem.getItemStatus());
|
||||
|
||||
|
||||
final String version2 = "2";
|
||||
final RosterPacket.Item item2 = new Item(userName, "Ursula Example");
|
||||
item2.addGroupName("users");
|
||||
item2.addGroupName("examples");
|
||||
item2.setItemStatus(ItemStatus.subscribe);
|
||||
item2.setItemType(ItemType.none);
|
||||
store.addEntry(item2,version2);
|
||||
assertEquals("Updating entry sets version correctly", version2, store.getRosterVersion());
|
||||
storedItem = store.getEntry(userName);
|
||||
assertNotNull("Added entry not found", storedItem);
|
||||
assertEquals("User of added entry",
|
||||
item2.getUser(), storedItem.getUser());
|
||||
assertEquals("Name of added entry",
|
||||
item2.getName(), storedItem.getName());
|
||||
assertEquals("Groups", item2.getGroupNames(), storedItem.getGroupNames());
|
||||
assertEquals("ItemType of added entry",
|
||||
item2.getItemType(), storedItem.getItemType());
|
||||
assertEquals("ItemStatus of added entry",
|
||||
item2.getItemStatus(), storedItem.getItemStatus());
|
||||
|
||||
List<Item> entries = store.getEntries();
|
||||
assertEquals("Number of entries", 1, entries.size());
|
||||
|
||||
final RosterPacket.Item item3 = new Item("foobar@example.com", "Foo Bar");
|
||||
item3.addGroupName("The Foo Fighters");
|
||||
item3.addGroupName("Bar Friends");
|
||||
item3.setItemStatus(ItemStatus.unsubscribe);
|
||||
item3.setItemType(ItemType.both);
|
||||
|
||||
final RosterPacket.Item item4 = new Item("baz@example.com", "Baba Baz");
|
||||
item4.addGroupName("The Foo Fighters");
|
||||
item4.addGroupName("Bar Friends");
|
||||
item4.setItemStatus(ItemStatus.subscribe);
|
||||
item4.setItemType(ItemType.both);
|
||||
|
||||
ArrayList<Item> items34 = new ArrayList<RosterPacket.Item>();
|
||||
items34.add(item3);
|
||||
items34.add(item4);
|
||||
|
||||
String version3 = "3";
|
||||
store.resetEntries(items34, version3);
|
||||
|
||||
storedItem = store.getEntry("foobar@example.com");
|
||||
assertNotNull("Added entry not found", storedItem);
|
||||
assertEquals("User of added entry",
|
||||
item3.getUser(), storedItem.getUser());
|
||||
assertEquals("Name of added entry",
|
||||
item3.getName(), storedItem.getName());
|
||||
assertEquals("Groups", item3.getGroupNames(), storedItem.getGroupNames());
|
||||
assertEquals("ItemType of added entry",
|
||||
item3.getItemType(), storedItem.getItemType());
|
||||
assertEquals("ItemStatus of added entry",
|
||||
item3.getItemStatus(), storedItem.getItemStatus());
|
||||
|
||||
|
||||
storedItem = store.getEntry("baz@example.com");
|
||||
assertNotNull("Added entry not found", storedItem);
|
||||
assertEquals("User of added entry",
|
||||
item4.getUser(), storedItem.getUser());
|
||||
assertEquals("Name of added entry",
|
||||
item4.getName(), storedItem.getName());
|
||||
assertEquals("Groups", item4.getGroupNames(), storedItem.getGroupNames());
|
||||
assertEquals("ItemType of added entry",
|
||||
item4.getItemType(), storedItem.getItemType());
|
||||
assertEquals("ItemStatus of added entry",
|
||||
item4.getItemStatus(), storedItem.getItemStatus());
|
||||
|
||||
entries = store.getEntries();
|
||||
assertEquals("Number of entries", 2, entries.size());
|
||||
|
||||
String version4 = "4";
|
||||
store.removeEntry("baz@example.com", version4);
|
||||
assertEquals("Removing entry sets version correctly",
|
||||
version4, store.getRosterVersion());
|
||||
assertNull("Removed entry is gone", store.getEntry(userName));
|
||||
|
||||
entries = store.getEntries();
|
||||
assertEquals("Number of entries", 1, entries.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests adding entries with evil characters
|
||||
*/
|
||||
@Test
|
||||
public void testAddEvilChars() throws IOException {
|
||||
File storeDir = tmpFolder.newFolder();
|
||||
DirectoryRosterStore store = DirectoryRosterStore.init(storeDir);
|
||||
|
||||
String user = "../_#;\"'\\&@example.com";
|
||||
String name = "\n../_#\0\t;\"'&@\\";
|
||||
String group1 = "\t;\"'&@\\\n../_#\0";
|
||||
String group2 = "#\0\t;\"'&@\\\n../_";
|
||||
|
||||
Item item = new Item(user, name);
|
||||
item.setItemStatus(ItemStatus.unsubscribe);
|
||||
item.setItemType(ItemType.to);
|
||||
item.addGroupName(group1);
|
||||
item.addGroupName(group2);
|
||||
store.addEntry(item, "a-version");
|
||||
Item storedItem = store.getEntry(user);
|
||||
|
||||
assertNotNull("Added entry not found", storedItem);
|
||||
assertEquals("User of added entry",
|
||||
item.getUser(), storedItem.getUser());
|
||||
assertEquals("Name of added entry",
|
||||
item.getName(), storedItem.getName());
|
||||
assertEquals("Groups", item.getGroupNames(), storedItem.getGroupNames());
|
||||
assertEquals("ItemType of added entry",
|
||||
item.getItemType(), storedItem.getItemType());
|
||||
assertEquals("ItemStatus of added entry",
|
||||
item.getItemStatus(), storedItem.getItemStatus());
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,261 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2010 Jive Software.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smack;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.jivesoftware.smack.SmackException.NotConnectedException;
|
||||
import org.jivesoftware.smack.XMPPConnection;
|
||||
import org.jivesoftware.smack.ConnectionConfiguration;
|
||||
import org.jivesoftware.smack.ConnectionCreationListener;
|
||||
import org.jivesoftware.smack.ConnectionListener;
|
||||
import org.jivesoftware.smack.PacketCollector;
|
||||
import org.jivesoftware.smack.Roster;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.jivesoftware.smack.packet.Presence;
|
||||
|
||||
/**
|
||||
* A dummy implementation of {@link XMPPConnection}, intended to be used during
|
||||
* unit tests.
|
||||
*
|
||||
* Instances store any packets that are delivered to be send using the
|
||||
* {@link #sendPacket(Packet)} method in a blocking queue. The content of this queue
|
||||
* can be inspected using {@link #getSentPacket()}. Typically these queues are
|
||||
* used to retrieve a message that was generated by the client.
|
||||
*
|
||||
* Packets that should be processed by the client to simulate a received stanza
|
||||
* can be delivered using the {@linkplain #processPacket(Packet)} method.
|
||||
* It invokes the registered packet interceptors and listeners.
|
||||
*
|
||||
* @see XMPPConnection
|
||||
* @author Guenther Niess
|
||||
*/
|
||||
public class DummyConnection extends XMPPConnection {
|
||||
|
||||
private boolean authenticated = false;
|
||||
private boolean anonymous = false;
|
||||
private boolean reconnect = false;
|
||||
|
||||
private String user;
|
||||
private String connectionID;
|
||||
private Roster roster;
|
||||
|
||||
private final BlockingQueue<Packet> queue = new LinkedBlockingQueue<Packet>();
|
||||
|
||||
public DummyConnection() {
|
||||
this(new ConnectionConfiguration("example.com"));
|
||||
}
|
||||
|
||||
public DummyConnection(ConnectionConfiguration configuration) {
|
||||
super(configuration);
|
||||
|
||||
for (ConnectionCreationListener listener : getConnectionCreationListeners()) {
|
||||
listener.connectionCreated(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
void connectInternal() {
|
||||
connectionID = "dummy-" + new Random(new Date().getTime()).nextInt();
|
||||
|
||||
if (reconnect) {
|
||||
for (ConnectionListener listener : getConnectionListeners()) {
|
||||
listener.reconnectionSuccessful();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnect(Presence unavailablePresence) {
|
||||
user = null;
|
||||
connectionID = null;
|
||||
roster = null;
|
||||
authenticated = false;
|
||||
anonymous = false;
|
||||
|
||||
for (ConnectionListener listener : getConnectionListeners()) {
|
||||
listener.connectionClosed();
|
||||
}
|
||||
reconnect = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getConnectionID() {
|
||||
if (!isConnected()) {
|
||||
return null;
|
||||
}
|
||||
if (connectionID == null) {
|
||||
connectionID = "dummy-" + new Random(new Date().getTime()).nextInt();
|
||||
}
|
||||
return connectionID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Roster getRoster() {
|
||||
if (isAnonymous()) {
|
||||
return null;
|
||||
}
|
||||
if (roster == null) {
|
||||
roster = new Roster(this);
|
||||
}
|
||||
return roster;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUser() {
|
||||
if (user == null) {
|
||||
user = "dummy@" + config.getServiceName() + "/Test";
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAnonymous() {
|
||||
return anonymous;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAuthenticated() {
|
||||
return authenticated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConnected() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSecureConnection() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUsingCompression() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void login(String username, String password, String resource)
|
||||
throws XMPPException {
|
||||
if (!isConnected()) {
|
||||
throw new IllegalStateException("Not connected to server.");
|
||||
}
|
||||
if (isAuthenticated()) {
|
||||
throw new IllegalStateException("Already logged in to server.");
|
||||
}
|
||||
user = (username != null ? username : "dummy")
|
||||
+ "@"
|
||||
+ config.getServiceName()
|
||||
+ "/"
|
||||
+ (resource != null ? resource : "Test");
|
||||
roster = new Roster(this);
|
||||
anonymous = false;
|
||||
authenticated = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loginAnonymously() throws XMPPException {
|
||||
if (!isConnected()) {
|
||||
throw new IllegalStateException("Not connected to server.");
|
||||
}
|
||||
if (isAuthenticated()) {
|
||||
throw new IllegalStateException("Already logged in to server.");
|
||||
}
|
||||
anonymous = true;
|
||||
authenticated = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
void sendPacketInternal(Packet packet) {
|
||||
if (SmackConfiguration.DEBUG_ENABLED) {
|
||||
System.out.println("[SEND]: " + packet.toXML());
|
||||
}
|
||||
queue.add(packet);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of packets that's sent through {@link #sendPacket(Packet)} and
|
||||
* that has not been returned by {@link #getSentPacket()}.
|
||||
*
|
||||
* @return the number of packets which are in the queue.
|
||||
*/
|
||||
public int getNumberOfSentPackets() {
|
||||
return queue.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first packet that's sent through {@link #sendPacket(Packet)}
|
||||
* and that has not been returned by earlier calls to this method.
|
||||
*
|
||||
* @return a sent packet.
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
public Packet getSentPacket() throws InterruptedException {
|
||||
return queue.poll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first packet that's sent through {@link #sendPacket(Packet)}
|
||||
* and that has not been returned by earlier calls to this method. This
|
||||
* method will block for up to the specified number of seconds if no packets
|
||||
* have been sent yet.
|
||||
*
|
||||
* @return a sent packet.
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
public Packet getSentPacket(int wait) throws InterruptedException {
|
||||
return queue.poll(wait, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a packet through the installed packet collectors and listeners
|
||||
* and letting them examine the packet to see if they are a match with the
|
||||
* filter.
|
||||
*
|
||||
* @param packet the packet to process.
|
||||
*/
|
||||
public void processPacket(Packet packet) {
|
||||
if (packet == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Loop through all collectors and notify the appropriate ones.
|
||||
for (PacketCollector collector: getPacketCollectors()) {
|
||||
collector.processPacket(packet);
|
||||
}
|
||||
|
||||
if (SmackConfiguration.DEBUG_ENABLED) {
|
||||
System.out.println("[RECV]: " + packet.toXML());
|
||||
}
|
||||
|
||||
// Deliver the incoming packet to listeners.
|
||||
for (ListenerWrapper listenerWrapper : recvListeners.values()) {
|
||||
try {
|
||||
listenerWrapper.notifyListener(packet);
|
||||
}
|
||||
catch (NotConnectedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,215 @@
|
|||
/**
|
||||
*
|
||||
* Copyright the original author or authors
|
||||
*
|
||||
* 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 static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import org.jivesoftware.smack.filter.PacketFilter;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PacketCollectorTest
|
||||
{
|
||||
|
||||
@Test
|
||||
public void verifyRollover()
|
||||
{
|
||||
TestPacketCollector collector = new TestPacketCollector(null, new OKEverything(), 5);
|
||||
|
||||
for (int i=0; i<6; i++)
|
||||
{
|
||||
Packet testPacket = new TestPacket(i);
|
||||
collector.processPacket(testPacket);
|
||||
}
|
||||
|
||||
// Assert that '0' has rolled off
|
||||
assertEquals("1", collector.nextResultBlockForever().getPacketID());
|
||||
assertEquals("2", collector.nextResultBlockForever().getPacketID());
|
||||
assertEquals("3", collector.nextResultBlockForever().getPacketID());
|
||||
assertEquals("4", collector.nextResultBlockForever().getPacketID());
|
||||
assertEquals("5", collector.pollResult().getPacketID());
|
||||
assertNull(collector.pollResult());
|
||||
|
||||
for (int i=10; i<15; i++)
|
||||
{
|
||||
Packet testPacket = new TestPacket(i);
|
||||
collector.processPacket(testPacket);
|
||||
}
|
||||
|
||||
assertEquals("10", collector.nextResultBlockForever().getPacketID());
|
||||
assertEquals("11", collector.nextResultBlockForever().getPacketID());
|
||||
assertEquals("12", collector.nextResultBlockForever().getPacketID());
|
||||
assertEquals("13", collector.nextResultBlockForever().getPacketID());
|
||||
assertEquals("14", collector.pollResult().getPacketID());
|
||||
assertNull(collector.pollResult());
|
||||
|
||||
assertNull(collector.nextResult(1000));
|
||||
}
|
||||
|
||||
/**
|
||||
* Although this doesn't guarentee anything due to the nature of threading, it can
|
||||
* potentially catch problems.
|
||||
*/
|
||||
@Test
|
||||
public void verifyThreadSafety()
|
||||
{
|
||||
int insertCount = 500;
|
||||
final TestPacketCollector collector = new TestPacketCollector(null, new OKEverything(), insertCount);
|
||||
|
||||
Thread consumer1 = new Thread(new Runnable()
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.sleep(3);
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
}
|
||||
@SuppressWarnings("unused")
|
||||
Packet packet = collector.nextResultBlockForever();
|
||||
// System.out.println(Thread.currentThread().getName() + " packet: " + packet);
|
||||
}
|
||||
}
|
||||
catch (RuntimeException re)
|
||||
{
|
||||
if (re.getCause() instanceof InterruptedException)
|
||||
{
|
||||
// System.out.println(Thread.currentThread().getName() + " has been interupted");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
consumer1.setName("consumer 1");
|
||||
|
||||
Thread consumer2 = new Thread(new Runnable()
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
Packet p = null;
|
||||
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.sleep(3);
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
}
|
||||
p = collector.nextResult(1);
|
||||
// System.out.println(Thread.currentThread().getName() + " packet: " + p);
|
||||
}
|
||||
while (p != null);
|
||||
}
|
||||
});
|
||||
consumer2.setName("consumer 2");
|
||||
|
||||
Thread consumer3 = new Thread(new Runnable()
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
Packet p = null;
|
||||
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.sleep(3);
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
}
|
||||
p = collector.pollResult();
|
||||
// System.out.println(Thread.currentThread().getName() + " packet: " + p);
|
||||
}
|
||||
while (p != null);
|
||||
}
|
||||
});
|
||||
consumer3.setName("consumer 3");
|
||||
|
||||
consumer1.start();
|
||||
consumer2.start();
|
||||
consumer3.start();
|
||||
|
||||
for(int i=0; i<insertCount; i++)
|
||||
{
|
||||
collector.processPacket(new TestPacket(i));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Thread.sleep(5000);
|
||||
consumer3.join();
|
||||
consumer2.join();
|
||||
consumer1.interrupt();
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
}
|
||||
//We cannot guarantee that this is going to pass due to the possible issue of timing between consumer 1
|
||||
// and main, but the probability is extremely remote.
|
||||
assertNull(collector.pollResult());
|
||||
}
|
||||
|
||||
class OKEverything implements PacketFilter
|
||||
{
|
||||
@Override
|
||||
public boolean accept(Packet packet)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class TestPacketCollector extends PacketCollector
|
||||
{
|
||||
protected TestPacketCollector(XMPPConnection conection, PacketFilter packetFilter, int size)
|
||||
{
|
||||
super(conection, packetFilter, size);
|
||||
}
|
||||
}
|
||||
|
||||
class TestPacket extends Packet
|
||||
{
|
||||
public TestPacket(int i)
|
||||
{
|
||||
setPacketID(String.valueOf(i));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return toXML();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toXML()
|
||||
{
|
||||
return "<packetId>" + getPacketID() + "</packetId>";
|
||||
}
|
||||
}
|
||||
}
|
773
smack-core/src/test/java/org/jivesoftware/smack/RosterTest.java
Normal file
773
smack-core/src/test/java/org/jivesoftware/smack/RosterTest.java
Normal file
|
@ -0,0 +1,773 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2010 Jive Software.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smack;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.jivesoftware.smack.packet.IQ;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.jivesoftware.smack.packet.Presence;
|
||||
import org.jivesoftware.smack.packet.RosterPacket;
|
||||
import org.jivesoftware.smack.packet.IQ.Type;
|
||||
import org.jivesoftware.smack.packet.RosterPacket.Item;
|
||||
import org.jivesoftware.smack.packet.RosterPacket.ItemType;
|
||||
import org.jivesoftware.smack.util.PacketParserUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.xmlpull.v1.XmlPullParserFactory;
|
||||
import org.xmlpull.v1.XmlPullParser;
|
||||
|
||||
/**
|
||||
* Tests that verifies the correct behavior of the {@link Roster} implementation.
|
||||
*
|
||||
* @see Roster
|
||||
* @see <a href="http://xmpp.org/rfcs/rfc3921.html#roster">Roster Management</a>
|
||||
* @author Guenther Niess
|
||||
*/
|
||||
public class RosterTest {
|
||||
|
||||
private DummyConnection connection;
|
||||
private TestRosterListener rosterListener;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
// Uncomment this to enable debug output
|
||||
//XMPPConnection.DEBUG_ENABLED = true;
|
||||
|
||||
connection = new DummyConnection();
|
||||
connection.connect();
|
||||
connection.login("rostertest", "secret");
|
||||
rosterListener = new TestRosterListener();
|
||||
connection.getRoster().addRosterListener(rosterListener);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
if (connection != null) {
|
||||
if (rosterListener != null && connection.getRoster() != null) {
|
||||
connection.getRoster().removeRosterListener(rosterListener);
|
||||
rosterListener = null;
|
||||
}
|
||||
connection.disconnect();
|
||||
connection = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a simple roster initialization according to the example in
|
||||
* <a href="http://xmpp.org/rfcs/rfc3921.html#roster-login"
|
||||
* >RFC3921: Retrieving One's Roster on Login</a>.
|
||||
*/
|
||||
@Test(timeout=5000)
|
||||
public void testSimpleRosterInitialization() throws Exception {
|
||||
// Setup
|
||||
final Roster roster = connection.getRoster();
|
||||
assertNotNull("Can't get the roster from the provided connection!", roster);
|
||||
assertFalse("Roster shouldn't be already initialized!",
|
||||
roster.rosterInitialized);
|
||||
|
||||
// Perform roster initialization
|
||||
initRoster(connection, roster);
|
||||
|
||||
// Verify roster
|
||||
assertTrue("Roster can't be initialized!", roster.rosterInitialized);
|
||||
verifyRomeosEntry(roster.getEntry("romeo@example.net"));
|
||||
verifyMercutiosEntry(roster.getEntry("mercutio@example.com"));
|
||||
verifyBenvoliosEntry(roster.getEntry("benvolio@example.net"));
|
||||
assertSame("Wrong number of roster entries.", 3, roster.getEntries().size());
|
||||
|
||||
// Verify roster listener
|
||||
assertTrue("The roster listener wasn't invoked for Romeo.",
|
||||
rosterListener.getAddedAddresses().contains("romeo@example.net"));
|
||||
assertTrue("The roster listener wasn't invoked for Mercutio.",
|
||||
rosterListener.getAddedAddresses().contains("mercutio@example.com"));
|
||||
assertTrue("The roster listener wasn't invoked for Benvolio.",
|
||||
rosterListener.getAddedAddresses().contains("benvolio@example.net"));
|
||||
assertSame("RosterListeners implies that a item was deleted!",
|
||||
0,
|
||||
rosterListener.getDeletedAddresses().size());
|
||||
assertSame("RosterListeners implies that a item was updated!",
|
||||
0,
|
||||
rosterListener.getUpdatedAddresses().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test adding a roster item according to the example in
|
||||
* <a href="http://xmpp.org/rfcs/rfc3921.html#roster-add"
|
||||
* >RFC3921: Adding a Roster Item</a>.
|
||||
*/
|
||||
@Test(timeout=5000)
|
||||
public void testAddRosterItem() throws Throwable {
|
||||
// Constants for the new contact
|
||||
final String contactJID = "nurse@example.com";
|
||||
final String contactName = "Nurse";
|
||||
final String[] contactGroup = {"Servants"};
|
||||
|
||||
// Setup
|
||||
final Roster roster = connection.getRoster();
|
||||
assertNotNull("Can't get the roster from the provided connection!", roster);
|
||||
initRoster(connection, roster);
|
||||
rosterListener.reset();
|
||||
|
||||
// Adding the new roster item
|
||||
final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() {
|
||||
void verifyUpdateRequest(final RosterPacket updateRequest) {
|
||||
final Item item = updateRequest.getRosterItems().iterator().next();
|
||||
assertSame("The provided JID doesn't match the requested!",
|
||||
contactJID,
|
||||
item.getUser());
|
||||
assertSame("The provided name doesn't match the requested!",
|
||||
contactName,
|
||||
item.getName());
|
||||
assertSame("The provided group number doesn't match the requested!",
|
||||
contactGroup.length,
|
||||
item.getGroupNames().size());
|
||||
assertSame("The provided group doesn't match the requested!",
|
||||
contactGroup[0],
|
||||
item.getGroupNames().iterator().next());
|
||||
}
|
||||
};
|
||||
serverSimulator.start();
|
||||
roster.createEntry(contactJID, contactName, contactGroup);
|
||||
serverSimulator.join();
|
||||
|
||||
// Check if an error occurred within the simulator
|
||||
final Throwable exception = serverSimulator.getException();
|
||||
if (exception != null) {
|
||||
throw exception;
|
||||
}
|
||||
|
||||
// Verify the roster entry of the new contact
|
||||
final RosterEntry addedEntry = roster.getEntry(contactJID);
|
||||
assertNotNull("The new contact wasn't added to the roster!", addedEntry);
|
||||
assertTrue("The roster listener wasn't invoked for the new contact!",
|
||||
rosterListener.getAddedAddresses().contains(contactJID));
|
||||
assertSame("Setup wrong name for the new contact!",
|
||||
contactName,
|
||||
addedEntry.getName());
|
||||
assertSame("Setup wrong default subscription status!",
|
||||
ItemType.none,
|
||||
addedEntry.getType());
|
||||
assertSame("The new contact should be member of exactly one group!",
|
||||
1,
|
||||
addedEntry.getGroups().size());
|
||||
assertSame("Setup wrong group name for the added contact!",
|
||||
contactGroup[0],
|
||||
addedEntry.getGroups().iterator().next().getName());
|
||||
|
||||
// Verify the unchanged roster items
|
||||
verifyRomeosEntry(roster.getEntry("romeo@example.net"));
|
||||
verifyMercutiosEntry(roster.getEntry("mercutio@example.com"));
|
||||
verifyBenvoliosEntry(roster.getEntry("benvolio@example.net"));
|
||||
assertSame("Wrong number of roster entries.", 4, roster.getEntries().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test updating a roster item according to the example in
|
||||
* <a href="http://xmpp.org/rfcs/rfc3921.html#roster-update"
|
||||
* >RFC3921: Updating a Roster Item</a>.
|
||||
*/
|
||||
@Test(timeout=5000)
|
||||
public void testUpdateRosterItem() throws Throwable {
|
||||
// Constants for the updated contact
|
||||
final String contactJID = "romeo@example.net";
|
||||
final String contactName = "Romeo";
|
||||
final String[] contactGroups = {"Friends", "Lovers"};
|
||||
|
||||
// Setup
|
||||
final Roster roster = connection.getRoster();
|
||||
assertNotNull("Can't get the roster from the provided connection!", roster);
|
||||
initRoster(connection, roster);
|
||||
rosterListener.reset();
|
||||
|
||||
// Updating the roster item
|
||||
final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() {
|
||||
void verifyUpdateRequest(final RosterPacket updateRequest) {
|
||||
final Item item = updateRequest.getRosterItems().iterator().next();
|
||||
assertSame("The provided JID doesn't match the requested!",
|
||||
contactJID,
|
||||
item.getUser());
|
||||
assertSame("The provided name doesn't match the requested!",
|
||||
contactName,
|
||||
item.getName());
|
||||
assertTrue("The updated contact doesn't belong to the requested groups ("
|
||||
+ contactGroups[0] +")!",
|
||||
item.getGroupNames().contains(contactGroups[0]));
|
||||
assertTrue("The updated contact doesn't belong to the requested groups ("
|
||||
+ contactGroups[1] +")!",
|
||||
item.getGroupNames().contains(contactGroups[1]));
|
||||
assertSame("The provided group number doesn't match the requested!",
|
||||
contactGroups.length,
|
||||
item.getGroupNames().size());
|
||||
}
|
||||
};
|
||||
serverSimulator.start();
|
||||
roster.createGroup(contactGroups[1]).addEntry(roster.getEntry(contactJID));
|
||||
serverSimulator.join();
|
||||
|
||||
// Check if an error occurred within the simulator
|
||||
final Throwable exception = serverSimulator.getException();
|
||||
if (exception != null) {
|
||||
throw exception;
|
||||
}
|
||||
|
||||
// Verify the roster entry of the updated contact
|
||||
final RosterEntry addedEntry = roster.getEntry(contactJID);
|
||||
assertNotNull("The contact was deleted from the roster!", addedEntry);
|
||||
assertTrue("The roster listener wasn't invoked for the updated contact!",
|
||||
rosterListener.getUpdatedAddresses().contains(contactJID));
|
||||
assertSame("Setup wrong name for the changed contact!",
|
||||
contactName,
|
||||
addedEntry.getName());
|
||||
assertTrue("The updated contact doesn't belong to the requested groups ("
|
||||
+ contactGroups[0] +")!",
|
||||
roster.getGroup(contactGroups[0]).contains(addedEntry));
|
||||
assertTrue("The updated contact doesn't belong to the requested groups ("
|
||||
+ contactGroups[1] +")!",
|
||||
roster.getGroup(contactGroups[1]).contains(addedEntry));
|
||||
assertSame("The updated contact should be member of two groups!",
|
||||
contactGroups.length,
|
||||
addedEntry.getGroups().size());
|
||||
|
||||
// Verify the unchanged roster items
|
||||
verifyMercutiosEntry(roster.getEntry("mercutio@example.com"));
|
||||
verifyBenvoliosEntry(roster.getEntry("benvolio@example.net"));
|
||||
assertSame("Wrong number of roster entries (" + roster.getEntries() + ").",
|
||||
3,
|
||||
roster.getEntries().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test deleting a roster item according to the example in
|
||||
* <a href="http://xmpp.org/rfcs/rfc3921.html#roster-delete"
|
||||
* >RFC3921: Deleting a Roster Item</a>.
|
||||
*/
|
||||
@Test(timeout=5000)
|
||||
public void testDeleteRosterItem() throws Throwable {
|
||||
// The contact which should be deleted
|
||||
final String contactJID = "romeo@example.net";
|
||||
|
||||
// Setup
|
||||
final Roster roster = connection.getRoster();
|
||||
assertNotNull("Can't get the roster from the provided connection!", roster);
|
||||
initRoster(connection, roster);
|
||||
rosterListener.reset();
|
||||
|
||||
// Delete a roster item
|
||||
final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() {
|
||||
void verifyUpdateRequest(final RosterPacket updateRequest) {
|
||||
final Item item = updateRequest.getRosterItems().iterator().next();
|
||||
assertSame("The provided JID doesn't match the requested!",
|
||||
contactJID,
|
||||
item.getUser());
|
||||
}
|
||||
};
|
||||
serverSimulator.start();
|
||||
roster.removeEntry(roster.getEntry(contactJID));
|
||||
serverSimulator.join();
|
||||
|
||||
// Check if an error occurred within the simulator
|
||||
final Throwable exception = serverSimulator.getException();
|
||||
if (exception != null) {
|
||||
throw exception;
|
||||
}
|
||||
|
||||
// Verify
|
||||
final RosterEntry deletedEntry = roster.getEntry(contactJID);
|
||||
assertNull("The contact wasn't deleted from the roster!", deletedEntry);
|
||||
assertTrue("The roster listener wasn't invoked for the deleted contact!",
|
||||
rosterListener.getDeletedAddresses().contains(contactJID));
|
||||
verifyMercutiosEntry(roster.getEntry("mercutio@example.com"));
|
||||
verifyBenvoliosEntry(roster.getEntry("benvolio@example.net"));
|
||||
assertSame("Wrong number of roster entries (" + roster.getEntries() + ").",
|
||||
2,
|
||||
roster.getEntries().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a simple roster push according to the example in
|
||||
* <a href="http://xmpp.org/internet-drafts/draft-ietf-xmpp-3921bis-03.html#roster-syntax-actions-push"
|
||||
* >RFC3921bis-03: Roster Push</a>.
|
||||
*/
|
||||
@Test(timeout=5000)
|
||||
public void testSimpleRosterPush() throws Throwable {
|
||||
final String contactJID = "nurse@example.com";
|
||||
final Roster roster = connection.getRoster();
|
||||
assertNotNull("Can't get the roster from the provided connection!", roster);
|
||||
final XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
|
||||
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
sb.append("<iq id=\"rostertest1\" type=\"set\" ")
|
||||
.append("to=\"").append(connection.getUser()).append("\">")
|
||||
.append("<query xmlns=\"jabber:iq:roster\">")
|
||||
.append("<item jid=\"").append(contactJID).append("\"/>")
|
||||
.append("</query>")
|
||||
.append("</iq>");
|
||||
parser.setInput(new StringReader(sb.toString()));
|
||||
parser.next();
|
||||
final IQ rosterPush = PacketParserUtils.parseIQ(parser, connection);
|
||||
initRoster(connection, roster);
|
||||
rosterListener.reset();
|
||||
|
||||
// Simulate receiving the roster push
|
||||
connection.processPacket(rosterPush);
|
||||
|
||||
// Verify the roster entry of the new contact
|
||||
final RosterEntry addedEntry = roster.getEntry(contactJID);
|
||||
assertNotNull("The new contact wasn't added to the roster!", addedEntry);
|
||||
assertTrue("The roster listener wasn't invoked for the new contact!",
|
||||
rosterListener.getAddedAddresses().contains(contactJID));
|
||||
assertSame("Setup wrong default subscription status!",
|
||||
ItemType.none,
|
||||
addedEntry.getType());
|
||||
assertSame("The new contact shouldn't be member of any group!",
|
||||
0,
|
||||
addedEntry.getGroups().size());
|
||||
|
||||
// Verify the unchanged roster items
|
||||
verifyRomeosEntry(roster.getEntry("romeo@example.net"));
|
||||
verifyMercutiosEntry(roster.getEntry("mercutio@example.com"));
|
||||
verifyBenvoliosEntry(roster.getEntry("benvolio@example.net"));
|
||||
assertSame("Wrong number of roster entries.", 4, roster.getEntries().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that roster pushes with invalid from are ignored.
|
||||
*
|
||||
* @see <a href="http://xmpp.org/rfcs/rfc6121.html#roster-syntax-actions-push">RFC 6121, Section 2.1.6</a>
|
||||
*/
|
||||
@Test(timeout=5000)
|
||||
public void testIgnoreInvalidFrom() {
|
||||
RosterPacket packet = new RosterPacket();
|
||||
packet.setType(Type.SET);
|
||||
packet.setTo(connection.getUser());
|
||||
packet.setFrom("mallory@example.com");
|
||||
packet.addRosterItem(new Item("spam@example.com", "Cool products!"));
|
||||
|
||||
// Simulate receiving the roster push
|
||||
connection.processPacket(packet);
|
||||
|
||||
assertNull("Contact was added to roster", connection.getRoster().getEntry("spam@example.com"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if adding an user with an empty group is equivalent with providing
|
||||
* no group.
|
||||
*
|
||||
* @see <a href="http://www.igniterealtime.org/issues/browse/SMACK-294">SMACK-294</a>
|
||||
*/
|
||||
@Test(timeout=5000)
|
||||
public void testAddEmptyGroupEntry() throws Throwable {
|
||||
// Constants for the new contact
|
||||
final String contactJID = "nurse@example.com";
|
||||
final String contactName = "Nurse";
|
||||
final String[] contactGroup = {""};
|
||||
|
||||
// Setup
|
||||
final Roster roster = connection.getRoster();
|
||||
assertNotNull("Can't get the roster from the provided connection!", roster);
|
||||
initRoster(connection, roster);
|
||||
rosterListener.reset();
|
||||
|
||||
// Adding the new roster item
|
||||
final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() {
|
||||
void verifyUpdateRequest(final RosterPacket updateRequest) {
|
||||
final Item item = updateRequest.getRosterItems().iterator().next();
|
||||
assertSame("The provided JID doesn't match the requested!",
|
||||
contactJID,
|
||||
item.getUser());
|
||||
assertSame("The provided name doesn't match the requested!",
|
||||
contactName,
|
||||
item.getName());
|
||||
assertSame("Shouldn't provide an empty group element!",
|
||||
0,
|
||||
item.getGroupNames().size());
|
||||
|
||||
}
|
||||
};
|
||||
serverSimulator.start();
|
||||
roster.createEntry(contactJID, contactName, contactGroup);
|
||||
serverSimulator.join();
|
||||
|
||||
// Check if an error occurred within the simulator
|
||||
final Throwable exception = serverSimulator.getException();
|
||||
if (exception != null) {
|
||||
throw exception;
|
||||
}
|
||||
|
||||
// Verify the roster entry of the new contact
|
||||
final RosterEntry addedEntry = roster.getEntry(contactJID);
|
||||
assertNotNull("The new contact wasn't added to the roster!", addedEntry);
|
||||
assertTrue("The roster listener wasn't invoked for the new contact!",
|
||||
rosterListener.getAddedAddresses().contains(contactJID));
|
||||
assertSame("Setup wrong name for the new contact!",
|
||||
contactName,
|
||||
addedEntry.getName());
|
||||
assertSame("Setup wrong default subscription status!",
|
||||
ItemType.none,
|
||||
addedEntry.getType());
|
||||
assertSame("The new contact shouldn't be member of any group!",
|
||||
0,
|
||||
addedEntry.getGroups().size());
|
||||
|
||||
// Verify the unchanged roster items
|
||||
verifyRomeosEntry(roster.getEntry("romeo@example.net"));
|
||||
verifyMercutiosEntry(roster.getEntry("mercutio@example.com"));
|
||||
verifyBenvoliosEntry(roster.getEntry("benvolio@example.net"));
|
||||
assertSame("Wrong number of roster entries.", 4, roster.getEntries().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test processing a roster push with an empty group is equivalent with providing
|
||||
* no group.
|
||||
*
|
||||
* @see <a href="http://www.igniterealtime.org/issues/browse/SMACK-294">SMACK-294</a>
|
||||
*/
|
||||
@Test(timeout=5000)
|
||||
public void testEmptyGroupRosterPush() throws Throwable {
|
||||
final String contactJID = "nurse@example.com";
|
||||
final Roster roster = connection.getRoster();
|
||||
assertNotNull("Can't get the roster from the provided connection!", roster);
|
||||
final XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
|
||||
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
sb.append("<iq id=\"rostertest2\" type=\"set\" ")
|
||||
.append("to=\"").append(connection.getUser()).append("\">")
|
||||
.append("<query xmlns=\"jabber:iq:roster\">")
|
||||
.append("<item jid=\"").append(contactJID).append("\">")
|
||||
.append("<group></group>")
|
||||
.append("</item>")
|
||||
.append("</query>")
|
||||
.append("</iq>");
|
||||
parser.setInput(new StringReader(sb.toString()));
|
||||
parser.next();
|
||||
final IQ rosterPush = PacketParserUtils.parseIQ(parser, connection);
|
||||
initRoster(connection, roster);
|
||||
rosterListener.reset();
|
||||
|
||||
// Simulate receiving the roster push
|
||||
connection.processPacket(rosterPush);
|
||||
|
||||
// Verify the roster entry of the new contact
|
||||
final RosterEntry addedEntry = roster.getEntry(contactJID);
|
||||
assertNotNull("The new contact wasn't added to the roster!", addedEntry);
|
||||
assertTrue("The roster listener wasn't invoked for the new contact!",
|
||||
rosterListener.getAddedAddresses().contains(contactJID));
|
||||
assertSame("Setup wrong default subscription status!",
|
||||
ItemType.none,
|
||||
addedEntry.getType());
|
||||
assertSame("The new contact shouldn't be member of any group!",
|
||||
0,
|
||||
addedEntry.getGroups().size());
|
||||
|
||||
// Verify the unchanged roster items
|
||||
verifyRomeosEntry(roster.getEntry("romeo@example.net"));
|
||||
verifyMercutiosEntry(roster.getEntry("mercutio@example.com"));
|
||||
verifyBenvoliosEntry(roster.getEntry("benvolio@example.net"));
|
||||
assertSame("Wrong number of roster entries.", 4, roster.getEntries().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all roster entries by iterating trough {@link Roster#getEntries()}
|
||||
* and simulating receiving roster pushes from the server.
|
||||
*
|
||||
* @param connection the dummy connection of which the provided roster belongs to.
|
||||
* @param roster the roster (or buddy list) which should be initialized.
|
||||
*/
|
||||
public static void removeAllRosterEntries(DummyConnection connection, Roster roster)
|
||||
throws InterruptedException, XMPPException {
|
||||
for(RosterEntry entry : roster.getEntries()) {
|
||||
// prepare the roster push packet
|
||||
final RosterPacket rosterPush= new RosterPacket();
|
||||
rosterPush.setType(Type.SET);
|
||||
rosterPush.setTo(connection.getUser());
|
||||
|
||||
// prepare the buddy's item entry which should be removed
|
||||
final RosterPacket.Item item = new RosterPacket.Item(entry.getUser(), entry.getName());
|
||||
item.setItemType(ItemType.remove);
|
||||
rosterPush.addRosterItem(item);
|
||||
|
||||
// simulate receiving the roster push
|
||||
connection.processPacket(rosterPush);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the roster according to the example in
|
||||
* <a href="http://xmpp.org/rfcs/rfc3921.html#roster-login"
|
||||
* >RFC3921: Retrieving One's Roster on Login</a>.
|
||||
*
|
||||
* @param connection the dummy connection of which the provided roster belongs to.
|
||||
* @param roster the roster (or buddy list) which should be initialized.
|
||||
* @throws SmackException
|
||||
*/
|
||||
public static void initRoster(DummyConnection connection, Roster roster) throws InterruptedException, XMPPException, SmackException {
|
||||
roster.reload();
|
||||
while (true) {
|
||||
final Packet sentPacket = connection.getSentPacket();
|
||||
if (sentPacket instanceof RosterPacket && ((IQ) sentPacket).getType() == Type.GET) {
|
||||
// setup the roster get request
|
||||
final RosterPacket rosterRequest = (RosterPacket) sentPacket;
|
||||
assertSame("The <query/> element MUST NOT contain any <item/> child elements!",
|
||||
0,
|
||||
rosterRequest.getRosterItemCount());
|
||||
|
||||
// prepare the roster result
|
||||
final RosterPacket rosterResult = new RosterPacket();
|
||||
rosterResult.setTo(connection.getUser());
|
||||
rosterResult.setType(Type.RESULT);
|
||||
rosterResult.setPacketID(rosterRequest.getPacketID());
|
||||
|
||||
// prepare romeo's roster entry
|
||||
final Item romeo = new Item("romeo@example.net", "Romeo");
|
||||
romeo.addGroupName("Friends");
|
||||
romeo.setItemType(ItemType.both);
|
||||
rosterResult.addRosterItem(romeo);
|
||||
|
||||
// prepare mercutio's roster entry
|
||||
final Item mercutio = new Item("mercutio@example.com", "Mercutio");
|
||||
mercutio.setItemType(ItemType.from);
|
||||
rosterResult.addRosterItem(mercutio);
|
||||
|
||||
// prepare benvolio's roster entry
|
||||
final Item benvolio = new Item("benvolio@example.net", "Benvolio");
|
||||
benvolio.setItemType(ItemType.both);
|
||||
rosterResult.addRosterItem(benvolio);
|
||||
|
||||
// simulate receiving the roster result and exit the loop
|
||||
connection.processPacket(rosterResult);
|
||||
break;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check Romeo's roster entry according to the example in
|
||||
* <a href="http://xmpp.org/rfcs/rfc3921.html#roster-login"
|
||||
* >RFC3921: Retrieving One's Roster on Login</a>.
|
||||
*
|
||||
* @param romeo the roster entry which should be verified.
|
||||
*/
|
||||
public static void verifyRomeosEntry(final RosterEntry romeo) {
|
||||
assertNotNull("Can't get Romeo's roster entry!", romeo);
|
||||
assertSame("Setup wrong name for Romeo!",
|
||||
"Romeo",
|
||||
romeo.getName());
|
||||
assertSame("Setup wrong subscription status for Romeo!",
|
||||
ItemType.both,
|
||||
romeo.getType());
|
||||
assertSame("Romeo should be member of exactly one group!",
|
||||
1,
|
||||
romeo.getGroups().size());
|
||||
assertSame("Setup wrong group name for Romeo!",
|
||||
"Friends",
|
||||
romeo.getGroups().iterator().next().getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check Mercutio's roster entry according to the example in
|
||||
* <a href="http://xmpp.org/rfcs/rfc3921.html#roster-login"
|
||||
* >RFC3921: Retrieving One's Roster on Login</a>.
|
||||
*
|
||||
* @param mercutio the roster entry which should be verified.
|
||||
*/
|
||||
public static void verifyMercutiosEntry(final RosterEntry mercutio) {
|
||||
assertNotNull("Can't get Mercutio's roster entry!", mercutio);
|
||||
assertSame("Setup wrong name for Mercutio!",
|
||||
"Mercutio",
|
||||
mercutio.getName());
|
||||
assertSame("Setup wrong subscription status for Mercutio!",
|
||||
ItemType.from,
|
||||
mercutio.getType());
|
||||
assertTrue("Mercutio shouldn't be a member of any group!",
|
||||
mercutio.getGroups().isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check Benvolio's roster entry according to the example in
|
||||
* <a href="http://xmpp.org/rfcs/rfc3921.html#roster-login"
|
||||
* >RFC3921: Retrieving One's Roster on Login</a>.
|
||||
*
|
||||
* @param benvolio the roster entry which should be verified.
|
||||
*/
|
||||
public static void verifyBenvoliosEntry(final RosterEntry benvolio) {
|
||||
assertNotNull("Can't get Benvolio's roster entry!", benvolio);
|
||||
assertSame("Setup wrong name for Benvolio!",
|
||||
"Benvolio",
|
||||
benvolio.getName());
|
||||
assertSame("Setup wrong subscription status for Benvolio!",
|
||||
ItemType.both,
|
||||
benvolio.getType());
|
||||
assertTrue("Benvolio shouldn't be a member of any group!",
|
||||
benvolio.getGroups().isEmpty());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This class can be used to simulate the server response for
|
||||
* a roster update request.
|
||||
*/
|
||||
private abstract class RosterUpdateResponder extends Thread {
|
||||
private Throwable exception = null;
|
||||
|
||||
/**
|
||||
* Overwrite this method to check if the received update request is valid.
|
||||
*
|
||||
* @param updateRequest the request which would be sent to the server.
|
||||
*/
|
||||
abstract void verifyUpdateRequest(final RosterPacket updateRequest);
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
final Packet packet = connection.getSentPacket();
|
||||
if (packet instanceof RosterPacket && ((IQ) packet).getType() == Type.SET) {
|
||||
final RosterPacket rosterRequest = (RosterPacket) packet;
|
||||
|
||||
// Prepare and process the roster push
|
||||
final RosterPacket rosterPush = new RosterPacket();
|
||||
final Item item = rosterRequest.getRosterItems().iterator().next();
|
||||
if (item.getItemType() != ItemType.remove) {
|
||||
item.setItemType(ItemType.none);
|
||||
}
|
||||
rosterPush.setType(Type.SET);
|
||||
rosterPush.setTo(connection.getUser());
|
||||
rosterPush.addRosterItem(item);
|
||||
connection.processPacket(rosterPush);
|
||||
|
||||
// Create and process the IQ response
|
||||
final IQ response = new IQ() {
|
||||
public String getChildElementXML() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
response.setPacketID(rosterRequest.getPacketID());
|
||||
response.setType(Type.RESULT);
|
||||
response.setTo(connection.getUser());
|
||||
connection.processPacket(response);
|
||||
|
||||
// Verify the roster update request
|
||||
assertSame("A roster set MUST contain one and only one <item/> element.",
|
||||
1,
|
||||
rosterRequest.getRosterItemCount());
|
||||
verifyUpdateRequest(rosterRequest);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Throwable e) {
|
||||
exception = e;
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the exception or error if something went wrong.
|
||||
*
|
||||
* @return the Throwable exception or error that occurred.
|
||||
*/
|
||||
public Throwable getException() {
|
||||
return exception;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This class can be used to check if the RosterListener was invoked.
|
||||
*/
|
||||
public static class TestRosterListener implements RosterListener {
|
||||
private CopyOnWriteArrayList<String> addressesAdded = new CopyOnWriteArrayList<String>();
|
||||
private CopyOnWriteArrayList<String> addressesDeleted = new CopyOnWriteArrayList<String>();
|
||||
private CopyOnWriteArrayList<String> addressesUpdated = new CopyOnWriteArrayList<String>();
|
||||
|
||||
public synchronized void entriesAdded(Collection<String> addresses) {
|
||||
addressesAdded.addAll(addresses);
|
||||
if (SmackConfiguration.DEBUG_ENABLED) {
|
||||
for (String address : addresses) {
|
||||
System.out.println("Roster entry for " + address + " added.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void entriesDeleted(Collection<String> addresses) {
|
||||
addressesDeleted.addAll(addresses);
|
||||
if (SmackConfiguration.DEBUG_ENABLED) {
|
||||
for (String address : addresses) {
|
||||
System.out.println("Roster entry for " + address + " deleted.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void entriesUpdated(Collection<String> addresses) {
|
||||
addressesUpdated.addAll(addresses);
|
||||
if (SmackConfiguration.DEBUG_ENABLED) {
|
||||
for (String address : addresses) {
|
||||
System.out.println("Roster entry for " + address + " updated.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void presenceChanged(Presence presence) {
|
||||
if (SmackConfiguration.DEBUG_ENABLED) {
|
||||
System.out.println("Roster presence changed: " + presence.toXML());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a collection of JIDs of the added roster items.
|
||||
*
|
||||
* @return the collection of addresses which were added.
|
||||
*/
|
||||
public Collection<String> getAddedAddresses() {
|
||||
return Collections.unmodifiableCollection(addressesAdded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a collection of JIDs of the deleted roster items.
|
||||
*
|
||||
* @return the collection of addresses which were deleted.
|
||||
*/
|
||||
public Collection<String> getDeletedAddresses() {
|
||||
return Collections.unmodifiableCollection(addressesDeleted);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a collection of JIDs of the updated roster items.
|
||||
*
|
||||
* @return the collection of addresses which were updated.
|
||||
*/
|
||||
public Collection<String> getUpdatedAddresses() {
|
||||
return Collections.unmodifiableCollection(addressesUpdated);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the lists of added, deleted or updated items.
|
||||
*/
|
||||
public synchronized void reset() {
|
||||
addressesAdded.clear();
|
||||
addressesDeleted.clear();
|
||||
addressesUpdated.clear();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,248 @@
|
|||
/**
|
||||
*
|
||||
* Copyright the original author or authors
|
||||
*
|
||||
* 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 static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
|
||||
import org.jivesoftware.smack.packet.IQ;
|
||||
import org.jivesoftware.smack.packet.IQ.Type;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.jivesoftware.smack.packet.RosterPacket;
|
||||
import org.jivesoftware.smack.packet.RosterPacket.Item;
|
||||
import org.jivesoftware.smack.packet.RosterPacket.ItemType;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
/**
|
||||
* Tests that verify the correct behavior of the {@link Roster} implementation
|
||||
* with regard to roster versioning
|
||||
*
|
||||
* @see Roster
|
||||
* @see <a href="http://xmpp.org/rfcs/rfc6121.html#roster">Managing the Roster</a>
|
||||
* @author Fabian Schuetz
|
||||
* @author Lars Noschinski
|
||||
*/
|
||||
public class RosterVersioningTest {
|
||||
|
||||
private DummyConnection connection;
|
||||
|
||||
@Rule
|
||||
public TemporaryFolder tmpFolder = new TemporaryFolder();
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
// Uncomment this to enable debug output
|
||||
//XMPPConnection.DEBUG_ENABLED = true;
|
||||
|
||||
DirectoryRosterStore store = DirectoryRosterStore.init(tmpFolder.newFolder("store"));
|
||||
populateStore(store);
|
||||
|
||||
ConnectionConfiguration conf = new ConnectionConfiguration("dummy");
|
||||
conf.setRosterStore(store);
|
||||
connection = new DummyConnection(conf);
|
||||
connection.connect();
|
||||
|
||||
connection.setRosterVersioningSupported();
|
||||
|
||||
connection.login("rostertest", "secret");
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
if (connection != null) {
|
||||
connection.disconnect();
|
||||
connection = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that receiving an empty roster result causes the roster to be populated
|
||||
* by all entries of the roster store.
|
||||
* @throws SmackException
|
||||
* @throws XMPPException
|
||||
*/
|
||||
@Test(timeout = 5000)
|
||||
public void testEqualVersionStored() throws InterruptedException, IOException, XMPPException, SmackException {
|
||||
connection.getRoster().reload();
|
||||
answerWithEmptyRosterResult();
|
||||
|
||||
Roster roster = connection.getRoster();
|
||||
Collection<RosterEntry> entries = roster.getEntries();
|
||||
assertSame("Size of the roster", 3, entries.size());
|
||||
|
||||
HashSet<Item> items = new HashSet<Item>();
|
||||
for (RosterEntry entry : entries) {
|
||||
items.add(RosterEntry.toRosterItem(entry));
|
||||
}
|
||||
RosterStore store = DirectoryRosterStore.init(tmpFolder.newFolder());
|
||||
populateStore(store);
|
||||
assertEquals("Elements of the roster", new HashSet<Item>(store.getEntries()), items);
|
||||
|
||||
for (RosterEntry entry : entries) {
|
||||
assertTrue("joe stevens".equals(entry.getName()) || "geoff hurley".equals(entry.getName())
|
||||
|| "higgins mcmann".equals(entry.getName()));
|
||||
}
|
||||
Collection<RosterGroup> groups = roster.getGroups();
|
||||
assertSame(3, groups.size());
|
||||
|
||||
for (RosterGroup group : groups) {
|
||||
assertTrue("all".equals(group.getName()) || "friends".equals(group.getName())
|
||||
|| "partners".equals(group.getName()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that a non-empty roster result empties the store.
|
||||
* @throws SmackException
|
||||
* @throws XMPPException
|
||||
*/
|
||||
@Test(timeout = 5000)
|
||||
public void testOtherVersionStored() throws InterruptedException, XMPPException, SmackException {
|
||||
connection.getRoster().reload();
|
||||
|
||||
Item vaglafItem = vaglafItem();
|
||||
|
||||
// We expect that the roster request is the only packet sent. This is not part of the specification,
|
||||
// but a shortcut in the test implementation.
|
||||
Packet sentPacket = connection.getSentPacket();
|
||||
if (sentPacket instanceof RosterPacket) {
|
||||
RosterPacket sentRP = (RosterPacket)sentPacket;
|
||||
RosterPacket answer = new RosterPacket();
|
||||
answer.setPacketID(sentRP.getPacketID());
|
||||
answer.setType(Type.RESULT);
|
||||
answer.setTo(sentRP.getFrom());
|
||||
|
||||
answer.setVersion("newVersion");
|
||||
answer.addRosterItem(vaglafItem);
|
||||
|
||||
connection.processPacket(answer);
|
||||
} else {
|
||||
assertTrue("Expected to get a RosterPacket ", false);
|
||||
}
|
||||
|
||||
Roster roster = connection.getRoster();
|
||||
assertEquals("Size of roster", 1, roster.getEntries().size());
|
||||
RosterEntry entry = roster.getEntry(vaglafItem.getUser());
|
||||
assertNotNull("Roster contains vaglaf entry", entry);
|
||||
assertEquals("vaglaf entry in roster equals the sent entry", vaglafItem, RosterEntry.toRosterItem(entry));
|
||||
|
||||
RosterStore store = connection.getConfiguration().getRosterStore();
|
||||
assertEquals("Size of store", 1, store.getEntries().size());
|
||||
Item item = store.getEntry(vaglafItem.getUser());
|
||||
assertNotNull("Store contains vaglaf entry");
|
||||
assertEquals("vaglaf entry in store equals the sent entry", vaglafItem, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test roster versioning with roster pushes
|
||||
*/
|
||||
@Test(timeout = 5000)
|
||||
public void testRosterVersioningWithCachedRosterAndPushes() throws Throwable {
|
||||
connection.getRoster().reload();
|
||||
answerWithEmptyRosterResult();
|
||||
|
||||
RosterStore store = connection.getConfiguration().getRosterStore();
|
||||
Roster roster = connection.getRoster();
|
||||
|
||||
// Simulate a roster push adding vaglaf
|
||||
{
|
||||
RosterPacket rosterPush = new RosterPacket();
|
||||
rosterPush.setTo("rostertest@example.com/home");
|
||||
rosterPush.setType(Type.SET);
|
||||
rosterPush.setVersion("v97");
|
||||
|
||||
Item pushedItem = vaglafItem();
|
||||
rosterPush.addRosterItem(pushedItem);
|
||||
connection.processPacket(rosterPush);
|
||||
|
||||
assertEquals("Expect store version after push", "v97", store.getRosterVersion());
|
||||
|
||||
Item storedItem = store.getEntry("vaglaf@example.com");
|
||||
assertNotNull("Expect vaglaf to be added", storedItem);
|
||||
assertEquals("Expect vaglaf to be equal to pushed item", pushedItem, storedItem);
|
||||
|
||||
Collection<Item> rosterItems = new HashSet<Item>();
|
||||
for (RosterEntry entry : roster.getEntries()) {
|
||||
rosterItems.add(RosterEntry.toRosterItem(entry));
|
||||
}
|
||||
assertEquals(rosterItems, new HashSet<Item>(store.getEntries()));
|
||||
}
|
||||
|
||||
// Simulate a roster push removing vaglaf
|
||||
{
|
||||
RosterPacket rosterPush = new RosterPacket();
|
||||
rosterPush.setTo("rostertest@example.com/home");
|
||||
rosterPush.setType(Type.SET);
|
||||
rosterPush.setVersion("v98");
|
||||
|
||||
Item item = new Item("vaglaf@example.com", "vaglaf the only");
|
||||
item.setItemType(ItemType.remove);
|
||||
rosterPush.addRosterItem(item);
|
||||
connection.processPacket(rosterPush);
|
||||
|
||||
assertNull("Store doses not contain vaglaf", store.getEntry("vaglaf@example.com"));
|
||||
assertEquals("Expect store version after push", "v98", store.getRosterVersion());
|
||||
}
|
||||
}
|
||||
|
||||
private Item vaglafItem() {
|
||||
Item item = new Item("vaglaf@example.com", "vaglaf the only");
|
||||
item.setItemType(ItemType.both);
|
||||
item.addGroupName("all");
|
||||
item.addGroupName("friends");
|
||||
item.addGroupName("partners");
|
||||
return item;
|
||||
}
|
||||
|
||||
private void populateStore(RosterStore store) throws IOException {
|
||||
store.addEntry(new RosterPacket.Item("geoff@example.com", "geoff hurley"), "");
|
||||
|
||||
RosterPacket.Item item = new RosterPacket.Item("joe@example.com", "joe stevens");
|
||||
item.addGroupName("friends");
|
||||
item.addGroupName("partners");
|
||||
store.addEntry(item, "");
|
||||
|
||||
item = new RosterPacket.Item("higgins@example.com", "higgins mcmann");
|
||||
item.addGroupName("all");
|
||||
item.addGroupName("friends");
|
||||
store.addEntry(item, "v96");
|
||||
}
|
||||
|
||||
private void answerWithEmptyRosterResult() throws InterruptedException {
|
||||
// We expect that the roster request is the only packet sent. This is not part of the specification,
|
||||
// but a shortcut in the test implementation.
|
||||
Packet sentPacket = connection.getSentPacket();
|
||||
if (sentPacket instanceof RosterPacket) {
|
||||
final IQ emptyIQ = IQ.createResultIQ((RosterPacket)sentPacket);
|
||||
connection.processPacket(emptyIQ);
|
||||
} else {
|
||||
assertTrue("Expected to get a RosterPacket ", false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
/**
|
||||
*
|
||||
* Copyright the original author or authors
|
||||
*
|
||||
* 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 static org.junit.Assert.fail;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class SmackConfigurationTest {
|
||||
|
||||
@Test
|
||||
public void testSmackConfiguration() {
|
||||
try {
|
||||
SmackConfiguration.getDefaultPacketReplyTimeout();
|
||||
} catch (Throwable t) {
|
||||
fail("SmackConfiguration threw Throwable");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,109 @@
|
|||
/**
|
||||
*
|
||||
* Copyright the original author or authors
|
||||
*
|
||||
* 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.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
|
||||
import org.jivesoftware.smack.SmackException.NotConnectedException;
|
||||
import org.jivesoftware.smack.packet.IQ;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.jivesoftware.smack.packet.IQ.Type;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class ThreadedDummyConnection extends DummyConnection {
|
||||
private BlockingQueue<IQ> replyQ = new ArrayBlockingQueue<IQ>(1);
|
||||
private BlockingQueue<Packet> messageQ = new LinkedBlockingQueue<Packet>(5);
|
||||
private volatile boolean timeout = false;
|
||||
|
||||
@Override
|
||||
public void sendPacket(Packet packet) {
|
||||
try {
|
||||
super.sendPacket(packet);
|
||||
}
|
||||
catch (NotConnectedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (packet instanceof IQ && !timeout) {
|
||||
timeout = false;
|
||||
// Set reply packet to match one being sent. We haven't started the
|
||||
// other thread yet so this is still safe.
|
||||
IQ replyPacket = replyQ.peek();
|
||||
|
||||
// If no reply has been set via addIQReply, then we create a simple reply
|
||||
if (replyPacket == null) {
|
||||
replyPacket = IQ.createResultIQ((IQ) packet);
|
||||
replyQ.add(replyPacket);
|
||||
}
|
||||
replyPacket.setPacketID(packet.getPacketID());
|
||||
replyPacket.setFrom(packet.getTo());
|
||||
replyPacket.setTo(packet.getFrom());
|
||||
replyPacket.setType(Type.RESULT);
|
||||
|
||||
new ProcessQueue(replyQ).start();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calling this method will cause the next sendPacket call with an IQ packet to timeout.
|
||||
* This is accomplished by simply stopping the auto creating of the reply packet
|
||||
* or processing one that was entered via {@link #processPacket(Packet)}.
|
||||
*/
|
||||
public void setTimeout() {
|
||||
timeout = true;
|
||||
}
|
||||
|
||||
public void addMessage(Message msgToProcess) {
|
||||
messageQ.add(msgToProcess);
|
||||
}
|
||||
|
||||
public void addIQReply(IQ reply) {
|
||||
replyQ.add(reply);
|
||||
}
|
||||
|
||||
public void processMessages() {
|
||||
if (!messageQ.isEmpty())
|
||||
new ProcessQueue(messageQ).start();
|
||||
else
|
||||
System.out.println("No messages to process");
|
||||
}
|
||||
|
||||
class ProcessQueue extends Thread {
|
||||
private BlockingQueue<? extends Packet> processQ;
|
||||
|
||||
ProcessQueue(BlockingQueue<? extends Packet> queue) {
|
||||
processQ = queue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
processPacket(processQ.take());
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
}
|
|
@ -0,0 +1,286 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2011 Robin Collier
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smack.filters;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import org.jivesoftware.smack.filter.FromMatchesFilter;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Robin Collier
|
||||
*
|
||||
*/
|
||||
public class FromMatchesFilterTest {
|
||||
private static final String BASE_JID1 = "ss@muc.myserver.com";
|
||||
private static final String FULL_JID1_R1 = BASE_JID1 + "/resource";
|
||||
private static final String FULL_JID1_R2 = BASE_JID1 + "/resource2";
|
||||
private static final String BASE_JID2 = "sss@muc.myserver.com";
|
||||
private static final String FULL_JID2 = BASE_JID2 + "/resource";
|
||||
|
||||
private static final String BASE_JID3 = "ss@muc.myserver.comm.net";
|
||||
|
||||
private static final String SERVICE_JID1 = "muc.myserver.com";
|
||||
private static final String SERVICE_JID2 = "pubsub.myserver.com";
|
||||
|
||||
@Test
|
||||
public void autoCompareMatchingFullJid()
|
||||
{
|
||||
FromMatchesFilter filter = FromMatchesFilter.create(FULL_JID1_R1);
|
||||
Packet packet = new Packet() {
|
||||
@Override
|
||||
public String toXML() { return null; }
|
||||
};
|
||||
|
||||
packet.setFrom(FULL_JID1_R1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID1);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID3);
|
||||
assertFalse(filter.accept(packet));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoCompareMatchingBaseJid()
|
||||
{
|
||||
FromMatchesFilter filter = FromMatchesFilter.create(BASE_JID1);
|
||||
Packet packet = new Packet() {
|
||||
@Override
|
||||
public String toXML() { return null; }
|
||||
};
|
||||
|
||||
packet.setFrom(BASE_JID1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R2);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID3);
|
||||
assertFalse(filter.accept(packet));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoCompareMatchingServiceJid()
|
||||
{
|
||||
FromMatchesFilter filter = FromMatchesFilter.create(SERVICE_JID1);
|
||||
Packet packet = new Packet() {
|
||||
@Override
|
||||
public String toXML() { return null; }
|
||||
};
|
||||
|
||||
packet.setFrom(SERVICE_JID1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(SERVICE_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID1);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R1);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID3);
|
||||
assertFalse(filter.accept(packet));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bareCompareMatchingFullJid()
|
||||
{
|
||||
FromMatchesFilter filter = FromMatchesFilter.createBare(FULL_JID1_R1);
|
||||
Packet packet = new Packet() {
|
||||
@Override
|
||||
public String toXML() { return null; }
|
||||
};
|
||||
|
||||
packet.setFrom(BASE_JID1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R2);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID3);
|
||||
assertFalse(filter.accept(packet));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bareCompareMatchingBaseJid()
|
||||
{
|
||||
FromMatchesFilter filter = FromMatchesFilter.createBare(BASE_JID1);
|
||||
Packet packet = new Packet() {
|
||||
@Override
|
||||
public String toXML() { return null; }
|
||||
};
|
||||
|
||||
packet.setFrom(BASE_JID1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R2);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID3);
|
||||
assertFalse(filter.accept(packet));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bareCompareMatchingServiceJid()
|
||||
{
|
||||
FromMatchesFilter filter = FromMatchesFilter.createBare(SERVICE_JID1);
|
||||
Packet packet = new Packet() {
|
||||
@Override
|
||||
public String toXML() { return null; }
|
||||
};
|
||||
|
||||
packet.setFrom(SERVICE_JID1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(SERVICE_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID1);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R1);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID3);
|
||||
assertFalse(filter.accept(packet));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fullCompareMatchingFullJid()
|
||||
{
|
||||
FromMatchesFilter filter = FromMatchesFilter.createFull(FULL_JID1_R1);
|
||||
Packet packet = new Packet() {
|
||||
@Override
|
||||
public String toXML() { return null; }
|
||||
};
|
||||
|
||||
packet.setFrom(FULL_JID1_R1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID1);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID3);
|
||||
assertFalse(filter.accept(packet));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fullCompareMatchingBaseJid()
|
||||
{
|
||||
FromMatchesFilter filter = FromMatchesFilter.createFull(BASE_JID1);
|
||||
Packet packet = new Packet() {
|
||||
@Override
|
||||
public String toXML() { return null; }
|
||||
};
|
||||
|
||||
packet.setFrom(BASE_JID1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R1);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID3);
|
||||
assertFalse(filter.accept(packet));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fullCompareMatchingServiceJid()
|
||||
{
|
||||
FromMatchesFilter filter = FromMatchesFilter.createFull(SERVICE_JID1);
|
||||
Packet packet = new Packet() {
|
||||
@Override
|
||||
public String toXML() { return null; }
|
||||
};
|
||||
|
||||
packet.setFrom(SERVICE_JID1);
|
||||
assertTrue(filter.accept(packet));
|
||||
|
||||
packet.setFrom(SERVICE_JID2);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID1);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(FULL_JID1_R1);
|
||||
assertFalse(filter.accept(packet));
|
||||
|
||||
packet.setFrom(BASE_JID3);
|
||||
assertFalse(filter.accept(packet));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,136 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2010 Jive Software.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smack.packet;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Tests that verifies the correct behavior of creating result and error IQ packets.
|
||||
*
|
||||
* @see <a href="http://xmpp.org/rfcs/rfc3920.html#stanzas-semantics-iq">IQ Semantics</a>
|
||||
* @author Guenther Niess
|
||||
*/
|
||||
public class IQResponseTest {
|
||||
|
||||
final static private String childElement = "<child xmlns=\"http://igniterealtime.org/protocol/test\"/>";
|
||||
|
||||
/**
|
||||
* Test creating a simple and empty IQ response.
|
||||
*/
|
||||
@Test
|
||||
public void testGeneratingSimpleResponse() {
|
||||
final IQ request = new IQ() {
|
||||
public String getChildElementXML() {
|
||||
return childElement;
|
||||
}
|
||||
};
|
||||
request.setFrom("sender@test/Smack");
|
||||
request.setTo("receiver@test/Smack");
|
||||
|
||||
final IQ result = IQ.createResultIQ(request);
|
||||
|
||||
assertEquals(IQ.Type.RESULT, result.getType());
|
||||
assertNotNull(result.getPacketID());
|
||||
assertEquals(request.getPacketID(), result.getPacketID());
|
||||
assertEquals(request.getFrom(), result.getTo());
|
||||
assertEquals(request.getTo(), result.getFrom());
|
||||
assertNull(result.getChildElementXML());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test creating a error response based on an IQ request.
|
||||
*/
|
||||
@Test
|
||||
public void testGeneratingValidErrorResponse() {
|
||||
final XMPPError error = new XMPPError(XMPPError.Condition.bad_request);
|
||||
final IQ request = new IQ() {
|
||||
public String getChildElementXML() {
|
||||
return childElement;
|
||||
}
|
||||
};
|
||||
request.setType(IQ.Type.SET);
|
||||
request.setFrom("sender@test/Smack");
|
||||
request.setTo("receiver@test/Smack");
|
||||
|
||||
final IQ result = IQ.createErrorResponse(request, error);
|
||||
|
||||
assertEquals(IQ.Type.ERROR, result.getType());
|
||||
assertNotNull(result.getPacketID());
|
||||
assertEquals(request.getPacketID(), result.getPacketID());
|
||||
assertEquals(request.getFrom(), result.getTo());
|
||||
assertEquals(error, result.getError());
|
||||
assertEquals(childElement, result.getChildElementXML());
|
||||
}
|
||||
|
||||
/**
|
||||
* According to <a href="http://xmpp.org/rfcs/rfc3920.html#stanzas-semantics-iq"
|
||||
* >RFC3920: IQ Semantics</a> we shouldn't respond to an IQ of type result.
|
||||
*/
|
||||
@Test
|
||||
public void testGeneratingResponseBasedOnResult() {
|
||||
final IQ request = new IQ() {
|
||||
public String getChildElementXML() {
|
||||
return childElement;
|
||||
}
|
||||
};
|
||||
request.setType(IQ.Type.RESULT);
|
||||
request.setFrom("sender@test/Smack");
|
||||
request.setTo("receiver@test/Smack");
|
||||
|
||||
try {
|
||||
IQ.createResultIQ(request);
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
return;
|
||||
}
|
||||
|
||||
fail("It shouldn't be possible to generate a response for a result IQ!");
|
||||
}
|
||||
|
||||
/**
|
||||
* According to <a href="http://xmpp.org/rfcs/rfc3920.html#stanzas-semantics-iq"
|
||||
* >RFC3920: IQ Semantics</a> we shouldn't respond to an IQ of type error.
|
||||
*/
|
||||
@Test
|
||||
public void testGeneratingErrorBasedOnError() {
|
||||
final XMPPError error = new XMPPError(XMPPError.Condition.bad_request);
|
||||
final IQ request = new IQ() {
|
||||
public String getChildElementXML() {
|
||||
return childElement;
|
||||
}
|
||||
};
|
||||
request.setType(IQ.Type.ERROR);
|
||||
request.setFrom("sender@test/Smack");
|
||||
request.setTo("receiver@test/Smack");
|
||||
request.setError(error);
|
||||
|
||||
try {
|
||||
IQ.createErrorResponse(request, error);
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
return;
|
||||
}
|
||||
|
||||
fail("It shouldn't be possible to generate a response for a error IQ!");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,263 @@
|
|||
/**
|
||||
*
|
||||
* Copyright (C) 2007 Jive Software.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smack.packet;
|
||||
|
||||
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.custommonkey.xmlunit.Diff;
|
||||
import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
|
||||
import org.junit.Test;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class MessageTest {
|
||||
|
||||
@Test
|
||||
public void setMessageTypeTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
Message.Type type = Message.Type.chat;
|
||||
Message.Type type2 = Message.Type.headline;
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<message")
|
||||
.append(" type=\"")
|
||||
.append(type)
|
||||
.append("\">")
|
||||
.append("</message>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Message messageTypeInConstructor = new Message(null, Message.Type.chat);
|
||||
messageTypeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE);
|
||||
assertEquals(type, messageTypeInConstructor.getType());
|
||||
assertXMLEqual(control, messageTypeInConstructor.toXML().toString());
|
||||
|
||||
controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<message")
|
||||
.append(" type=\"")
|
||||
.append(type2)
|
||||
.append("\">")
|
||||
.append("</message>");
|
||||
control = controlBuilder.toString();
|
||||
|
||||
Message messageTypeSet = getNewMessage();
|
||||
messageTypeSet.setType(type2);
|
||||
assertEquals(type2, messageTypeSet.getType());
|
||||
assertXMLEqual(control, messageTypeSet.toXML().toString());
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void setMessageTypeNullTest() {
|
||||
Message message = getNewMessage();
|
||||
message.setType(null);
|
||||
}
|
||||
|
||||
@Test(expected=NullPointerException.class)
|
||||
public void setNullMessageBodyTest() {
|
||||
Message message = getNewMessage();
|
||||
message.addBody(null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setMessageSubjectTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
final String messageSubject = "This is a test of the emergency broadcast system.";
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<message>")
|
||||
.append("<subject>")
|
||||
.append(messageSubject)
|
||||
.append("</subject>")
|
||||
.append("</message>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Message message = getNewMessage();
|
||||
message.setSubject(messageSubject);
|
||||
|
||||
assertEquals(messageSubject, message.getSubject());
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oneMessageBodyTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
final String messageBody = "This is a test of the emergency broadcast system.";
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<message>")
|
||||
.append("<body>")
|
||||
.append(messageBody)
|
||||
.append("</body>")
|
||||
.append("</message>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Message message = getNewMessage();
|
||||
message.setBody(messageBody);
|
||||
|
||||
assertEquals(messageBody, message.getBody());
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void multipleMessageBodiesTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
final String messageBody1 = "This is a test of the emergency broadcast system, 1.";
|
||||
final String lang2 = "ru";
|
||||
final String messageBody2 = "This is a test of the emergency broadcast system, 2.";
|
||||
final String lang3 = "sp";
|
||||
final String messageBody3 = "This is a test of the emergency broadcast system, 3.";
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<message>")
|
||||
.append("<body>")
|
||||
.append(messageBody1)
|
||||
.append("</body>")
|
||||
.append("<body xml:lang=\"")
|
||||
.append(lang2)
|
||||
.append("\">")
|
||||
.append(messageBody2)
|
||||
.append("</body>")
|
||||
.append("<body xml:lang=\"")
|
||||
.append(lang3)
|
||||
.append("\">")
|
||||
.append(messageBody3)
|
||||
.append("</body>")
|
||||
.append("</message>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Message message = getNewMessage();
|
||||
message.addBody(null, messageBody1);
|
||||
message.addBody(lang2, messageBody2);
|
||||
message.addBody(lang3, messageBody3);
|
||||
Diff xmlDiff = new Diff(control, message.toXML().toString());
|
||||
xmlDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
|
||||
assertTrue(xmlDiff.similar());
|
||||
|
||||
Collection<String> languages = message.getBodyLanguages();
|
||||
List<String> controlLanguages = new ArrayList<String>();
|
||||
controlLanguages.add(lang2);
|
||||
controlLanguages.add(lang3);
|
||||
controlLanguages.removeAll(languages);
|
||||
assertTrue(controlLanguages.size() == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removeMessageBodyTest() {
|
||||
Message message = getNewMessage();
|
||||
message.setBody("test");
|
||||
assertTrue(message.getBodies().size() == 1);
|
||||
|
||||
message.setBody(null);
|
||||
assertTrue(message.getBodies().size() == 0);
|
||||
|
||||
assertFalse(message.removeBody("sp"));
|
||||
|
||||
Message.Body body = message.addBody("es", "test");
|
||||
assertTrue(message.getBodies().size() == 1);
|
||||
|
||||
message.removeBody(body);
|
||||
assertTrue(message.getBodies().size() == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setMessageThreadTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
final String messageThread = "1234";
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<message>")
|
||||
.append("<thread>")
|
||||
.append(messageThread)
|
||||
.append("</thread>")
|
||||
.append("</message>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Message message = getNewMessage();
|
||||
message.setThread(messageThread);
|
||||
|
||||
assertEquals(messageThread, message.getThread());
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void messageXmlLangTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
final String lang = "sp";
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<message")
|
||||
.append(" xml:lang=\"")
|
||||
.append(lang)
|
||||
.append("\">")
|
||||
.append("</message>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Message message = getNewMessage();
|
||||
message.setLanguage(lang);
|
||||
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void messageEqualityTest() {
|
||||
Message message = getNewMessage();
|
||||
assertTrue(message.equals(message));
|
||||
//noinspection ObjectEqualsNull
|
||||
assertFalse(message.equals(null));
|
||||
assertFalse(message.equals("test"));
|
||||
Message message2 = getNewMessage();
|
||||
|
||||
assertTrue(message.equals(message2));
|
||||
|
||||
message.setTo("joe@shmoe.com");
|
||||
assertFalse(message.equals(message2));
|
||||
message2.setTo("joe@shmoe.com");
|
||||
|
||||
message.setSubject("subject");
|
||||
assertFalse(message.equals(message2));
|
||||
message2.setSubject("subject");
|
||||
|
||||
message.setThread("thread");
|
||||
assertFalse(message.equals(message2));
|
||||
message2.setThread("thread");
|
||||
|
||||
message.setBody("body1");
|
||||
assertFalse(message.equals(message2));
|
||||
message2.setBody("body1");
|
||||
|
||||
message.setLanguage("language");
|
||||
assertFalse(message.equals(message2));
|
||||
message2.setLanguage("language");
|
||||
|
||||
message.setType(Message.Type.chat);
|
||||
assertFalse(message.equals(message2));
|
||||
message2.setType(Message.Type.chat);
|
||||
|
||||
assertTrue(message.equals(message2));
|
||||
}
|
||||
|
||||
private static Message getNewMessage() {
|
||||
Message message = new Message();
|
||||
message.setPacketID(Packet.ID_NOT_AVAILABLE);
|
||||
return message;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,200 @@
|
|||
/**
|
||||
*
|
||||
* Copyright (C) 2007 Jive Software.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smack.packet;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class PresenceTest {
|
||||
@Test
|
||||
public void setPresenceTypeTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
Presence.Type type = Presence.Type.unavailable;
|
||||
Presence.Type type2 = Presence.Type.subscribe;
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<presence")
|
||||
.append(" type=\"")
|
||||
.append(type)
|
||||
.append("\">")
|
||||
.append("</presence>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Presence presenceTypeInConstructor = new Presence(type);
|
||||
presenceTypeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE);
|
||||
assertEquals(type, presenceTypeInConstructor.getType());
|
||||
assertXMLEqual(control, presenceTypeInConstructor.toXML().toString());
|
||||
|
||||
controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<presence")
|
||||
.append(" type=\"")
|
||||
.append(type2)
|
||||
.append("\">")
|
||||
.append("</presence>");
|
||||
control = controlBuilder.toString();
|
||||
|
||||
Presence presenceTypeSet = getNewPresence();
|
||||
presenceTypeSet.setType(type2);
|
||||
assertEquals(type2, presenceTypeSet.getType());
|
||||
assertXMLEqual(control, presenceTypeSet.toXML().toString());
|
||||
}
|
||||
|
||||
@Test(expected=NullPointerException.class)
|
||||
public void setNullPresenceTypeTest() {
|
||||
getNewPresence().setType(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isPresenceAvailableTest() {
|
||||
Presence presence = getNewPresence();
|
||||
presence.setType(Presence.Type.available);
|
||||
assertTrue(presence.isAvailable());
|
||||
|
||||
presence.setType(Presence.Type.unavailable);
|
||||
assertFalse(presence.isAvailable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setPresenceStatusTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
final String status = "This is a test of the emergency broadcast system.";
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<presence>")
|
||||
.append("<status>")
|
||||
.append(status)
|
||||
.append("</status>")
|
||||
.append("</presence>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Presence presence = getNewPresence();
|
||||
presence.setStatus(status);
|
||||
|
||||
assertEquals(status, presence.getStatus());
|
||||
assertXMLEqual(control, presence.toXML().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setPresencePriorityTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
final int priority = 10;
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<presence>")
|
||||
.append("<priority>")
|
||||
.append(priority)
|
||||
.append("</priority>")
|
||||
.append("</presence>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Presence presence = getNewPresence();
|
||||
presence.setPriority(priority);
|
||||
|
||||
assertEquals(priority, presence.getPriority());
|
||||
assertXMLEqual(control, presence.toXML().toString());
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void setIllegalPriorityTest() {
|
||||
getNewPresence().setPriority(Integer.MIN_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setPresenceModeTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
Presence.Mode mode1 = Presence.Mode.dnd;
|
||||
final int priority = 10;
|
||||
final String status = "This is a test of the emergency broadcast system.";
|
||||
Presence.Mode mode2 = Presence.Mode.chat;
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<presence>")
|
||||
.append("<status>")
|
||||
.append(status)
|
||||
.append("</status>")
|
||||
.append("<priority>")
|
||||
.append(priority)
|
||||
.append("</priority>")
|
||||
.append("<show>")
|
||||
.append(mode1)
|
||||
.append("</show>")
|
||||
.append("</presence>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Presence presenceModeInConstructor = new Presence(Presence.Type.available, status, priority,
|
||||
mode1);
|
||||
presenceModeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE);
|
||||
assertEquals(mode1, presenceModeInConstructor.getMode());
|
||||
assertXMLEqual(control, presenceModeInConstructor.toXML().toString());
|
||||
|
||||
controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<presence>")
|
||||
.append("<show>")
|
||||
.append(mode2)
|
||||
.append("</show>")
|
||||
.append("</presence>");
|
||||
control = controlBuilder.toString();
|
||||
|
||||
Presence presenceModeSet = getNewPresence();
|
||||
presenceModeSet.setMode(mode2);
|
||||
assertEquals(mode2, presenceModeSet.getMode());
|
||||
assertXMLEqual(control, presenceModeSet.toXML().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isModeAwayTest() {
|
||||
Presence presence = getNewPresence();
|
||||
presence.setMode(Presence.Mode.away);
|
||||
assertTrue(presence.isAway());
|
||||
|
||||
presence.setMode(Presence.Mode.chat);
|
||||
assertFalse(presence.isAway());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void presenceXmlLangTest() throws IOException, SAXException, ParserConfigurationException {
|
||||
final String lang = "sp";
|
||||
|
||||
StringBuilder controlBuilder = new StringBuilder();
|
||||
controlBuilder.append("<presence")
|
||||
.append(" xml:lang=\"")
|
||||
.append(lang)
|
||||
.append("\">")
|
||||
.append("</presence>");
|
||||
String control = controlBuilder.toString();
|
||||
|
||||
Presence presence = getNewPresence();
|
||||
presence.setLanguage(lang);
|
||||
|
||||
assertXMLEqual(control, presence.toXML().toString());
|
||||
}
|
||||
|
||||
private static Presence getNewPresence() {
|
||||
Presence presence = new Presence(Presence.Type.available);
|
||||
presence.setPacketID(Packet.ID_NOT_AVAILABLE);
|
||||
return presence;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,105 @@
|
|||
/**
|
||||
*
|
||||
* Copyright the original author or authors
|
||||
*
|
||||
* 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 static org.junit.Assert.*;
|
||||
|
||||
import org.jivesoftware.smack.packet.StreamError;
|
||||
import org.jivesoftware.smack.test.util.TestUtils;
|
||||
import org.jivesoftware.smack.util.PacketParserUtils;
|
||||
import org.junit.Test;
|
||||
import org.xmlpull.v1.XmlPullParser;
|
||||
|
||||
public class StreamErrorTest {
|
||||
|
||||
@Test
|
||||
public void testParsingOfSimpleStreamError() {
|
||||
StreamError error = null;
|
||||
final String xml =
|
||||
// Usually the stream:stream element has more attributes (to, version, ...)
|
||||
// We omit those, since they are not relevant for testing
|
||||
"<stream:stream from='im.example.com' id='++TR84Sm6A3hnt3Q065SnAbbk3Y=' xmlns:stream='http://etherx.jabber.org/streams'>" +
|
||||
"<stream:error>" +
|
||||
"<conflict xmlns='urn:ietf:params:xml:ns:xmpp-streams' /> +" +
|
||||
"</stream:error>" +
|
||||
"</stream:stream>";
|
||||
try {
|
||||
XmlPullParser parser = TestUtils.getParser(xml, "error");
|
||||
error = PacketParserUtils.parseStreamError(parser);
|
||||
} catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
assertNotNull(error);
|
||||
assertEquals("conflict", error.getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParsingOfStreamErrorWithText() {
|
||||
StreamError error = null;
|
||||
final String xml =
|
||||
// Usually the stream:stream element has more attributes (to, version, ...)
|
||||
// We omit those, since they are not relevant for testing
|
||||
"<stream:stream from='im.example.com' id='++TR84Sm6A3hnt3Q065SnAbbk3Y=' xmlns:stream='http://etherx.jabber.org/streams'>" +
|
||||
"<stream:error>" +
|
||||
"<conflict xmlns='urn:ietf:params:xml:ns:xmpp-streams' />" +
|
||||
"<text xml:lang='' xmlns='urn:ietf:params:xml:ns:xmpp-streams'>" +
|
||||
"Replaced by new connection" +
|
||||
"</text>" +
|
||||
"</stream:error>" +
|
||||
"</stream:stream>";
|
||||
try {
|
||||
XmlPullParser parser = TestUtils.getParser(xml, "error");
|
||||
error = PacketParserUtils.parseStreamError(parser);
|
||||
} catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
assertNotNull(error);
|
||||
assertEquals("conflict", error.getCode());
|
||||
assertEquals("Replaced by new connection", error.getText());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParsingOfStreamErrorWithTextAndOptionalElement() {
|
||||
StreamError error = null;
|
||||
final String xml =
|
||||
// Usually the stream:stream element has more attributes (to, version, ...)
|
||||
// We omit those, since they are not relevant for testing
|
||||
"<stream:stream from='im.example.com' id='++TR84Sm6A3hnt3Q065SnAbbk3Y=' xmlns:stream='http://etherx.jabber.org/streams'>" +
|
||||
"<stream:error>" +
|
||||
"<conflict xmlns='urn:ietf:params:xml:ns:xmpp-streams' />" +
|
||||
"<text xml:lang='' xmlns='urn:ietf:params:xml:ns:xmpp-streams'>" +
|
||||
"Replaced by new connection" +
|
||||
"</text>" +
|
||||
"<appSpecificElement>" +
|
||||
"Text contents of application-specific condition element: Foo Bar" +
|
||||
"</appSpecificElement>" +
|
||||
"</stream:error>" +
|
||||
"</stream:stream>";
|
||||
try {
|
||||
XmlPullParser parser = TestUtils.getParser(xml, "error");
|
||||
error = PacketParserUtils.parseStreamError(parser);
|
||||
} catch (Exception e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
assertNotNull(error);
|
||||
assertEquals("conflict", error.getCode());
|
||||
assertEquals("Replaced by new connection", error.getText());
|
||||
// As of now, Smack ignores application-specific condition elements, so we don't
|
||||
// test them.
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
/**
|
||||
*
|
||||
* Copyright the original author or authors
|
||||
*
|
||||
* 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.parsing;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.jivesoftware.smack.SmackException;
|
||||
import org.jivesoftware.smack.packet.PacketExtension;
|
||||
import org.jivesoftware.smack.provider.PacketExtensionProvider;
|
||||
import org.jivesoftware.smack.provider.ProviderManager;
|
||||
import org.jivesoftware.smack.test.util.TestUtils;
|
||||
import org.jivesoftware.smack.util.PacketParserUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.xmlpull.v1.XmlPullParser;
|
||||
|
||||
public class ParsingExceptionTest {
|
||||
private final static ProviderManager PM = ProviderManager.getInstance();
|
||||
|
||||
private final static String EXTENSION2 =
|
||||
"<extension2 xmlns='namespace'>" +
|
||||
"<bar node='testNode'>" +
|
||||
"<i id='testid1' >" +
|
||||
"</i>" +
|
||||
"</bar>" +
|
||||
"</extension2>";
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
PM.addExtensionProvider(ThrowException.ELEMENT, ThrowException.NAMESPACE, new ThrowException());
|
||||
}
|
||||
|
||||
@After
|
||||
public void tini() {
|
||||
PM.removeExtensionProvider(ThrowException.ELEMENT, ThrowException.NAMESPACE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void consumeUnparsedInput() throws Exception {
|
||||
XmlPullParser parser = TestUtils.getMessageParser(
|
||||
"<message from='user@server.example' to='francisco@denmark.lit' id='foo'>" +
|
||||
"<" + ThrowException.ELEMENT + " xmlns='" + ThrowException.NAMESPACE + "'>" +
|
||||
"<nothingInHere>" +
|
||||
"</nothingInHere>" +
|
||||
"</" + ThrowException.ELEMENT + ">" +
|
||||
EXTENSION2 +
|
||||
"</message>");
|
||||
int parserDepth = parser.getDepth();
|
||||
String content = null;
|
||||
try {
|
||||
PacketParserUtils.parseMessage(parser);
|
||||
} catch (Exception e) {
|
||||
content = PacketParserUtils.parseContentDepth(parser, parserDepth);
|
||||
}
|
||||
assertNotNull(content);
|
||||
assertEquals(content, "<nothingInHere></nothingInHere>" + "</" + ThrowException.ELEMENT + ">" + EXTENSION2);
|
||||
|
||||
}
|
||||
|
||||
static class ThrowException implements PacketExtensionProvider {
|
||||
public static final String ELEMENT = "exception";
|
||||
public static final String NAMESPACE = "http://smack.jivesoftware.org/exception";
|
||||
|
||||
@Override
|
||||
public PacketExtension parseExtension(XmlPullParser parser) throws Exception {
|
||||
throw new SmackException("Test Exception");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
/**
|
||||
*
|
||||
* Copyright the original author or authors
|
||||
*
|
||||
* 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.provider;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.junit.Assert;
|
||||
|
||||
import org.jivesoftware.smack.packet.IQ;
|
||||
import org.jivesoftware.smack.provider.ExtensionProviderInfo;
|
||||
import org.jivesoftware.smack.provider.IQProvider;
|
||||
import org.jivesoftware.smack.provider.IQProviderInfo;
|
||||
import org.jivesoftware.smack.provider.ProviderFileLoader;
|
||||
import org.jivesoftware.smack.provider.ProviderLoader;
|
||||
import org.jivesoftware.smack.provider.ProviderManager;
|
||||
import org.jivesoftware.smack.util.FileUtils;
|
||||
import org.junit.Test;
|
||||
import org.xmlpull.v1.XmlPullParser;
|
||||
|
||||
public class ProviderConfigTest {
|
||||
|
||||
@Test
|
||||
public void addGenericLoaderProvider() {
|
||||
ProviderManager.getInstance().addLoader(new ProviderLoader() {
|
||||
|
||||
@Override
|
||||
public Collection<IQProviderInfo> getIQProviderInfo() {
|
||||
ArrayList<IQProviderInfo> l = new ArrayList<IQProviderInfo>(1);
|
||||
l.add(new IQProviderInfo("provider", "test:provider", new TestIQProvider()));
|
||||
return l;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<ExtensionProviderInfo> getExtensionProviderInfo() {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
Assert.assertNotNull(ProviderManager.getInstance().getIQProvider("provider", "test:provider"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addClasspathFileLoaderProvider() throws Exception{
|
||||
ProviderManager.getInstance().addLoader(new ProviderFileLoader(FileUtils.getStreamForUrl("classpath:test.providers", null)));
|
||||
Assert.assertNotNull(ProviderManager.getInstance().getIQProvider("provider", "test:file_provider"));
|
||||
}
|
||||
|
||||
public static class TestIQProvider implements IQProvider {
|
||||
|
||||
@Override
|
||||
public IQ parseIQ(XmlPullParser parser) throws Exception {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2013 Robin Collier
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smack.test.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
|
||||
import org.xmlpull.v1.XmlPullParserFactory;
|
||||
import org.xmlpull.v1.XmlPullParser;
|
||||
import org.xmlpull.v1.XmlPullParserException;
|
||||
|
||||
final public class TestUtils {
|
||||
private TestUtils() {
|
||||
}
|
||||
|
||||
public static XmlPullParser getIQParser(String stanza) {
|
||||
return getParser(stanza, "iq");
|
||||
}
|
||||
|
||||
public static XmlPullParser getMessageParser(String stanza) {
|
||||
return getParser(stanza, "message");
|
||||
}
|
||||
|
||||
public static XmlPullParser getPresenceParser(String stanza) {
|
||||
return getParser(stanza, "presence");
|
||||
}
|
||||
|
||||
public static XmlPullParser getParser(String stanza, String startTag) {
|
||||
XmlPullParser parser;
|
||||
try {
|
||||
parser = XmlPullParserFactory.newInstance().newPullParser();
|
||||
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
|
||||
parser.setInput(new StringReader(stanza));
|
||||
boolean found = false;
|
||||
|
||||
while (!found) {
|
||||
if ((parser.next() == XmlPullParser.START_TAG) && parser.getName().equals(startTag))
|
||||
found = true;
|
||||
}
|
||||
|
||||
if (!found)
|
||||
throw new IllegalArgumentException("Cannot parse start tag [" + startTag + "] from stanza [" + stanza
|
||||
+ "]");
|
||||
} catch (XmlPullParserException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return parser;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,804 @@
|
|||
/**
|
||||
*
|
||||
* Copyright (C) 2007 Jive Software.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smack.util;
|
||||
|
||||
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
|
||||
import static org.custommonkey.xmlunit.XMLAssert.assertXMLNotEqual;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.custommonkey.xmlunit.DetailedDiff;
|
||||
import org.custommonkey.xmlunit.Diff;
|
||||
import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.jivesoftware.smack.packet.Presence;
|
||||
import org.jivesoftware.smack.test.util.TestUtils;
|
||||
import org.junit.Test;
|
||||
import org.xmlpull.v1.XmlPullParserException;
|
||||
|
||||
import com.jamesmurty.utils.XMLBuilder;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class PacketParserUtilsTest {
|
||||
|
||||
private static Properties outputProperties = new Properties();
|
||||
{
|
||||
outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singleMessageBodyTest() throws Exception {
|
||||
String defaultLanguage = Packet.getDefaultLanguage();
|
||||
String otherLanguage = determineNonDefaultLanguage();
|
||||
|
||||
String control;
|
||||
|
||||
// message has default language, body has no language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.e("body")
|
||||
.t(defaultLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
Message message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getBody());
|
||||
assertTrue(message.getBodyLanguages().isEmpty());
|
||||
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
|
||||
assertNull(message.getBody(otherLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has non-default language, body has no language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.e("body")
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(otherLanguage, message.getBody());
|
||||
assertTrue(message.getBodyLanguages().isEmpty());
|
||||
assertEquals(otherLanguage, message.getBody(otherLanguage));
|
||||
assertNull(message.getBody(defaultLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, body has no language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("body")
|
||||
.t(defaultLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getBody());
|
||||
assertTrue(message.getBodyLanguages().isEmpty());
|
||||
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
|
||||
assertNull(message.getBody(otherLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, body has default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("body")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.t(defaultLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getBody());
|
||||
assertTrue(message.getBodyLanguages().isEmpty());
|
||||
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
|
||||
assertNull(message.getBody(otherLanguage));
|
||||
|
||||
// body attribute xml:lang is unnecessary
|
||||
assertXMLNotEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, body has non-default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("body")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertNull(message.getBody());
|
||||
assertFalse(message.getBodyLanguages().isEmpty());
|
||||
assertTrue(message.getBodyLanguages().contains(otherLanguage));
|
||||
assertEquals(otherLanguage, message.getBody(otherLanguage));
|
||||
assertNull(message.getBody(defaultLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has default language, body has non-default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.e("body")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertNull(message.getBody());
|
||||
assertFalse(message.getBodyLanguages().isEmpty());
|
||||
assertTrue(message.getBodyLanguages().contains(otherLanguage));
|
||||
assertEquals(otherLanguage, message.getBody(otherLanguage));
|
||||
assertNull(message.getBody(defaultLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has non-default language, body has default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.e("body")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.t(defaultLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertNull(message.getBody());
|
||||
assertFalse(message.getBodyLanguages().isEmpty());
|
||||
assertTrue(message.getBodyLanguages().contains(defaultLanguage));
|
||||
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
|
||||
assertNull(message.getBody(otherLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singleMessageSubjectTest() throws Exception {
|
||||
String defaultLanguage = Packet.getDefaultLanguage();
|
||||
String otherLanguage = determineNonDefaultLanguage();
|
||||
|
||||
String control;
|
||||
|
||||
// message has default language, subject has no language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.e("subject")
|
||||
.t(defaultLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
Message message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getSubject());
|
||||
assertTrue(message.getSubjectLanguages().isEmpty());
|
||||
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
|
||||
assertNull(message.getSubject(otherLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has non-default language, subject has no language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.e("subject")
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(otherLanguage, message.getSubject());
|
||||
assertTrue(message.getSubjectLanguages().isEmpty());
|
||||
assertEquals(otherLanguage, message.getSubject(otherLanguage));
|
||||
assertNull(message.getSubject(defaultLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, subject has no language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("subject")
|
||||
.t(defaultLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getSubject());
|
||||
assertTrue(message.getSubjectLanguages().isEmpty());
|
||||
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
|
||||
assertNull(message.getSubject(otherLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, subject has default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("subject")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.t(defaultLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getSubject());
|
||||
assertTrue(message.getSubjectLanguages().isEmpty());
|
||||
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
|
||||
assertNull(message.getSubject(otherLanguage));
|
||||
|
||||
// subject attribute xml:lang is unnecessary
|
||||
assertXMLNotEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, subject has non-default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("subject")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertNull(message.getSubject());
|
||||
assertFalse(message.getSubjectLanguages().isEmpty());
|
||||
assertTrue(message.getSubjectLanguages().contains(otherLanguage));
|
||||
assertEquals(otherLanguage, message.getSubject(otherLanguage));
|
||||
assertNull(message.getSubject(defaultLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has default language, subject has non-default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.e("subject")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertNull(message.getSubject());
|
||||
assertFalse(message.getSubjectLanguages().isEmpty());
|
||||
assertTrue(message.getSubjectLanguages().contains(otherLanguage));
|
||||
assertEquals(otherLanguage, message.getSubject(otherLanguage));
|
||||
assertNull(message.getSubject(defaultLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has non-default language, subject has default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.e("subject")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.t(defaultLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertNull(message.getSubject());
|
||||
assertFalse(message.getSubjectLanguages().isEmpty());
|
||||
assertTrue(message.getSubjectLanguages().contains(defaultLanguage));
|
||||
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
|
||||
assertNull(message.getSubject(otherLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void multipleMessageBodiesTest() throws Exception {
|
||||
String defaultLanguage = Packet.getDefaultLanguage();
|
||||
String otherLanguage = determineNonDefaultLanguage();
|
||||
|
||||
String control;
|
||||
Message message;
|
||||
|
||||
// message has default language, first body no language, second body other language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.e("body")
|
||||
.t(defaultLanguage)
|
||||
.up()
|
||||
.e("body")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getBody());
|
||||
assertEquals(otherLanguage, message.getBody(otherLanguage));
|
||||
assertEquals(2, message.getBodies().size());
|
||||
assertEquals(1, message.getBodyLanguages().size());
|
||||
assertTrue(message.getBodyLanguages().contains(otherLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has default language, first body no language, second body default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.e("body")
|
||||
.t(defaultLanguage)
|
||||
.up()
|
||||
.e("body")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.t(defaultLanguage + "2")
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getBody());
|
||||
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
|
||||
assertEquals(1, message.getBodies().size());
|
||||
assertEquals(0, message.getBodyLanguages().size());
|
||||
assertXMLNotEqual(control, message.toXML().toString());
|
||||
|
||||
// message has non-default language, first body no language, second body default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.e("body")
|
||||
.t(otherLanguage)
|
||||
.up()
|
||||
.e("body")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.t(defaultLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(otherLanguage, message.getBody());
|
||||
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
|
||||
assertEquals(2, message.getBodies().size());
|
||||
assertEquals(1, message.getBodyLanguages().size());
|
||||
assertTrue(message.getBodyLanguages().contains(defaultLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, first body no language, second body default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("body")
|
||||
.t(defaultLanguage)
|
||||
.up()
|
||||
.e("body")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.t(defaultLanguage + "2")
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getBody());
|
||||
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
|
||||
assertEquals(1, message.getBodies().size());
|
||||
assertEquals(0, message.getBodyLanguages().size());
|
||||
assertXMLNotEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, first body no language, second body other language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("body")
|
||||
.t(defaultLanguage)
|
||||
.up()
|
||||
.e("body")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getBody());
|
||||
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
|
||||
assertEquals(otherLanguage, message.getBody(otherLanguage));
|
||||
assertEquals(2, message.getBodies().size());
|
||||
assertEquals(1, message.getBodyLanguages().size());
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, first body no language, second body no language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("body")
|
||||
.t(defaultLanguage)
|
||||
.up()
|
||||
.e("body")
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getBody());
|
||||
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
|
||||
assertEquals(1, message.getBodies().size());
|
||||
assertEquals(0, message.getBodyLanguages().size());
|
||||
assertXMLNotEqual(control, message.toXML().toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void multipleMessageSubjectsTest() throws Exception {
|
||||
String defaultLanguage = Packet.getDefaultLanguage();
|
||||
String otherLanguage = determineNonDefaultLanguage();
|
||||
|
||||
String control;
|
||||
Message message;
|
||||
|
||||
// message has default language, first subject no language, second subject other language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.e("subject")
|
||||
.t(defaultLanguage)
|
||||
.up()
|
||||
.e("subject")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getSubject());
|
||||
assertEquals(otherLanguage, message.getSubject(otherLanguage));
|
||||
assertEquals(2, message.getSubjects().size());
|
||||
assertEquals(1, message.getSubjectLanguages().size());
|
||||
assertTrue(message.getSubjectLanguages().contains(otherLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has default language, first subject no language, second subject default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.e("subject")
|
||||
.t(defaultLanguage)
|
||||
.up()
|
||||
.e("subject")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.t(defaultLanguage + "2")
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getSubject());
|
||||
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
|
||||
assertEquals(1, message.getSubjects().size());
|
||||
assertEquals(0, message.getSubjectLanguages().size());
|
||||
assertXMLNotEqual(control, message.toXML().toString());
|
||||
|
||||
// message has non-default language, first subject no language, second subject default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.e("subject")
|
||||
.t(otherLanguage)
|
||||
.up()
|
||||
.e("subject")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.t(defaultLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(otherLanguage, message.getSubject());
|
||||
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
|
||||
assertEquals(2, message.getSubjects().size());
|
||||
assertEquals(1, message.getSubjectLanguages().size());
|
||||
assertTrue(message.getSubjectLanguages().contains(defaultLanguage));
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, first subject no language, second subject default language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("subject")
|
||||
.t(defaultLanguage)
|
||||
.up()
|
||||
.e("subject")
|
||||
.a("xml:lang", defaultLanguage)
|
||||
.t(defaultLanguage + "2")
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getSubject());
|
||||
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
|
||||
assertEquals(1, message.getSubjects().size());
|
||||
assertEquals(0, message.getSubjectLanguages().size());
|
||||
assertXMLNotEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, first subject no language, second subject other language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("subject")
|
||||
.t(defaultLanguage)
|
||||
.up()
|
||||
.e("subject")
|
||||
.a("xml:lang", otherLanguage)
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getSubject());
|
||||
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
|
||||
assertEquals(otherLanguage, message.getSubject(otherLanguage));
|
||||
assertEquals(2, message.getSubjects().size());
|
||||
assertEquals(1, message.getSubjectLanguages().size());
|
||||
assertXMLEqual(control, message.toXML().toString());
|
||||
|
||||
// message has no language, first subject no language, second subject no language
|
||||
control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.e("subject")
|
||||
.t(defaultLanguage)
|
||||
.up()
|
||||
.e("subject")
|
||||
.t(otherLanguage)
|
||||
.asString(outputProperties);
|
||||
|
||||
message = (Message) PacketParserUtils
|
||||
.parseMessage(TestUtils.getMessageParser(control));
|
||||
|
||||
assertEquals(defaultLanguage, message.getSubject());
|
||||
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
|
||||
assertEquals(1, message.getSubjects().size());
|
||||
assertEquals(0, message.getSubjectLanguages().size());
|
||||
assertXMLNotEqual(control, message.toXML().toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidMessageBodyContainingTagTest() throws Exception {
|
||||
String control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", "en")
|
||||
.e("body")
|
||||
.a("xmlns", "http://www.w3.org/1999/xhtml")
|
||||
.e("span")
|
||||
.a("style", "font-weight: bold;")
|
||||
.t("Bad Message Body")
|
||||
.asString(outputProperties);
|
||||
|
||||
try {
|
||||
Message message = (Message) PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
String body = "<span style=\"font-weight: bold;\">"
|
||||
+ "Bad Message Body</span>";
|
||||
assertEquals(body, message.getBody());
|
||||
|
||||
assertXMLNotEqual(control, message.toXML().toString());
|
||||
|
||||
DetailedDiff diffs = new DetailedDiff(new Diff(control, message.toXML().toString()));
|
||||
|
||||
// body has no namespace URI, span is escaped
|
||||
assertEquals(6, diffs.getAllDifferences().size());
|
||||
} catch(XmlPullParserException e) {
|
||||
fail("No parser exception should be thrown" + e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidXMLInMessageBody() throws Exception {
|
||||
String validControl = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", "en")
|
||||
.e("body")
|
||||
.t("Good Message Body")
|
||||
.asString(outputProperties);
|
||||
|
||||
String invalidControl = validControl.replace("Good Message Body", "Bad </span> Body");
|
||||
|
||||
try {
|
||||
PacketParserUtils.parseMessage(TestUtils.getMessageParser(invalidControl));
|
||||
fail("Exception should be thrown");
|
||||
} catch(XmlPullParserException e) {
|
||||
assertTrue(e.getMessage().contains("end tag name </span>"));
|
||||
}
|
||||
|
||||
invalidControl = validControl.replace("Good Message Body", "Bad </body> Body");
|
||||
|
||||
try {
|
||||
PacketParserUtils.parseMessage(TestUtils.getMessageParser(invalidControl));
|
||||
fail("Exception should be thrown");
|
||||
} catch(XmlPullParserException e) {
|
||||
assertTrue(e.getMessage().contains("end tag name </body>"));
|
||||
}
|
||||
|
||||
invalidControl = validControl.replace("Good Message Body", "Bad </message> Body");
|
||||
|
||||
try {
|
||||
PacketParserUtils.parseMessage(TestUtils.getMessageParser(invalidControl));
|
||||
fail("Exception should be thrown");
|
||||
} catch(XmlPullParserException e) {
|
||||
assertTrue(e.getMessage().contains("end tag name </message>"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void multipleMessageBodiesParsingTest() throws Exception {
|
||||
String control = XMLBuilder.create("message")
|
||||
.a("from", "romeo@montague.lit/orchard")
|
||||
.a("to", "juliet@capulet.lit/balcony")
|
||||
.a("id", "zid615d9")
|
||||
.a("type", "chat")
|
||||
.a("xml:lang", "en")
|
||||
.e("body")
|
||||
.t("This is a test of the emergency broadcast system, 1.")
|
||||
.up()
|
||||
.e("body")
|
||||
.a("xml:lang", "ru")
|
||||
.t("This is a test of the emergency broadcast system, 2.")
|
||||
.up()
|
||||
.e("body")
|
||||
.a("xml:lang", "sp")
|
||||
.t("This is a test of the emergency broadcast system, 3.")
|
||||
.asString(outputProperties);
|
||||
|
||||
Packet message = PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
|
||||
Diff xmlDiff = new Diff(control, message.toXML().toString());
|
||||
xmlDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
|
||||
assertTrue(xmlDiff.similar());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateSimplePresence() throws Exception {
|
||||
String stanza = "<presence from='juliet@example.com/balcony' to='romeo@example.net'/>";
|
||||
|
||||
Presence presence = PacketParserUtils.parsePresence(TestUtils.getPresenceParser(stanza));
|
||||
|
||||
assertXMLEqual(stanza, presence.toXML().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validatePresenceProbe() throws Exception {
|
||||
String stanza = "<presence from='mercutio@example.com' id='xv291f38' to='juliet@example.com' type='unsubscribed'/>";
|
||||
|
||||
Presence presence = PacketParserUtils.parsePresence(TestUtils.getPresenceParser(stanza));
|
||||
|
||||
assertXMLEqual(stanza, presence.toXML().toString());
|
||||
assertEquals(Presence.Type.unsubscribed, presence.getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validatePresenceOptionalElements() throws Exception {
|
||||
String stanza = "<presence xml:lang='en' type='unsubscribed'>"
|
||||
+ "<show>dnd</show>"
|
||||
+ "<status>Wooing Juliet</status>"
|
||||
+ "<priority>1</priority>"
|
||||
+ "</presence>";
|
||||
|
||||
Presence presence = PacketParserUtils.parsePresence(TestUtils.getPresenceParser(stanza));
|
||||
assertXMLEqual(stanza, presence.toXML().toString());
|
||||
assertEquals(Presence.Type.unsubscribed, presence.getType());
|
||||
assertEquals("dnd", presence.getMode().name());
|
||||
assertEquals("en", presence.getLanguage());
|
||||
assertEquals("Wooing Juliet", presence.getStatus());
|
||||
assertEquals(1, presence.getPriority());
|
||||
}
|
||||
|
||||
private String determineNonDefaultLanguage() {
|
||||
String otherLanguage = "jp";
|
||||
Locale[] availableLocales = Locale.getAvailableLocales();
|
||||
for (int i = 0; i < availableLocales.length; i++) {
|
||||
if (availableLocales[i] != Locale.getDefault()) {
|
||||
otherLanguage = availableLocales[i].getLanguage().toLowerCase(Locale.US);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return otherLanguage;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,218 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jivesoftware.smack.util;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* A test case for the StringUtils class.
|
||||
*/
|
||||
public class StringUtilsTest {
|
||||
@Test
|
||||
public void testEscapeForXML() {
|
||||
String input = null;
|
||||
|
||||
assertNull(StringUtils.escapeForXML(null));
|
||||
|
||||
input = "<b>";
|
||||
assertCharSequenceEquals("<b>", StringUtils.escapeForXML(input));
|
||||
|
||||
input = "\"";
|
||||
assertCharSequenceEquals(""", StringUtils.escapeForXML(input));
|
||||
|
||||
input = "&";
|
||||
assertCharSequenceEquals("&", StringUtils.escapeForXML(input));
|
||||
|
||||
input = "<b>\n\t\r</b>";
|
||||
assertCharSequenceEquals("<b>\n\t\r</b>", StringUtils.escapeForXML(input));
|
||||
|
||||
input = " & ";
|
||||
assertCharSequenceEquals(" & ", StringUtils.escapeForXML(input));
|
||||
|
||||
input = " \" ";
|
||||
assertCharSequenceEquals(" " ", StringUtils.escapeForXML(input));
|
||||
|
||||
input = "> of me <";
|
||||
assertCharSequenceEquals("> of me <", StringUtils.escapeForXML(input));
|
||||
|
||||
input = "> of me & you<";
|
||||
assertCharSequenceEquals("> of me & you<", StringUtils.escapeForXML(input));
|
||||
|
||||
input = "& <";
|
||||
assertCharSequenceEquals("& <", StringUtils.escapeForXML(input));
|
||||
|
||||
input = "&";
|
||||
assertCharSequenceEquals("&", StringUtils.escapeForXML(input));
|
||||
|
||||
input = "It's a good day today";
|
||||
assertCharSequenceEquals("It's a good day today", StringUtils.escapeForXML(input));
|
||||
}
|
||||
|
||||
public static void assertCharSequenceEquals(CharSequence expected, CharSequence actual) {
|
||||
assertEquals(expected.toString(), actual.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHash() {
|
||||
// Test null
|
||||
// @TODO - should the StringUtils.hash(String) method be fixed to handle null input?
|
||||
try {
|
||||
StringUtils.hash(null);
|
||||
fail();
|
||||
}
|
||||
catch (NullPointerException npe) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
// Test empty String
|
||||
String result = StringUtils.hash("");
|
||||
assertEquals("da39a3ee5e6b4b0d3255bfef95601890afd80709", result);
|
||||
|
||||
// Test a known hash
|
||||
String adminInHash = "d033e22ae348aeb5660fc2140aec35850c4da997";
|
||||
result = StringUtils.hash("admin");
|
||||
assertEquals(adminInHash, result);
|
||||
|
||||
// Test a random String - make sure all resulting characters are valid hash characters
|
||||
// and that the returned string is 32 characters long.
|
||||
String random = "jive software blah and stuff this is pretty cool";
|
||||
result = StringUtils.hash(random);
|
||||
assertTrue(isValidHash(result));
|
||||
|
||||
// Test junk input:
|
||||
String junk = "\n\n\t\b\r!@(!)^(#)@+_-\u2031\u09291\u00A9\u00BD\u0394\u00F8";
|
||||
result = StringUtils.hash(junk);
|
||||
assertTrue(isValidHash(result));
|
||||
}
|
||||
|
||||
/* ----- Utility methods and vars ----- */
|
||||
|
||||
private final String HASH_CHARS = "0123456789abcdef";
|
||||
|
||||
/**
|
||||
* Returns true if the input string is valid md5 hash, false otherwise.
|
||||
*/
|
||||
private boolean isValidHash(String result) {
|
||||
boolean valid = true;
|
||||
for (int i=0; i<result.length(); i++) {
|
||||
char c = result.charAt(i);
|
||||
if (HASH_CHARS.indexOf(c) < 0) {
|
||||
valid = false;
|
||||
}
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncodeHex() {
|
||||
String input = "";
|
||||
String output = "";
|
||||
assertEquals(new String(StringUtils.encodeHex(input.getBytes())),
|
||||
new String(output.getBytes()));
|
||||
|
||||
input = "foo bar 123";
|
||||
output = "666f6f2062617220313233";
|
||||
assertEquals(new String(StringUtils.encodeHex(input.getBytes())),
|
||||
new String(output.getBytes()));
|
||||
}
|
||||
|
||||
/**
|
||||
* This method tests 2 StringUtil methods - encodeBase64(String) and encodeBase64(byte[]).
|
||||
*/
|
||||
@Test
|
||||
public void testEncodeBase64() {
|
||||
String input = "";
|
||||
String output = "";
|
||||
assertEquals(StringUtils.encodeBase64(input), output);
|
||||
|
||||
input = "foo bar 123";
|
||||
output = "Zm9vIGJhciAxMjM=";
|
||||
assertEquals(StringUtils.encodeBase64(input), output);
|
||||
|
||||
input = "=";
|
||||
output = "PQ==";
|
||||
assertEquals(StringUtils.encodeBase64(input), output);
|
||||
|
||||
input = "abcdefghijklmnopqrstuvwxyz0123456789\n\t\"?!.@{}[]();',./<>#$%^&*";
|
||||
output = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU2Nzg5CgkiPyEuQHt9W10oKTsnLC4vPD4jJCVeJio=";
|
||||
assertEquals(StringUtils.encodeBase64(input), output);
|
||||
}
|
||||
|
||||
/***
|
||||
* This method tests 2 StringUtil methods - decodeBase64(String) and decodeBase64(byte[]).
|
||||
*/
|
||||
/*
|
||||
public void testDecodeBase64() {
|
||||
String input = "";
|
||||
String output = "";
|
||||
assertEquals(StringUtils.decodeBase64(input), output);
|
||||
|
||||
input = "Zm9vIGJhciAxMjM=";
|
||||
output = "foo bar 123";
|
||||
assertEquals(StringUtils.decodeBase64(input), output);
|
||||
|
||||
input = "PQ==";
|
||||
output = "=";
|
||||
assertEquals(StringUtils.decodeBase64(input), output);
|
||||
|
||||
input = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU2Nzg5CgkiPyEuQHt9W10oKTsnLC4vPD4jJCVeJio=";
|
||||
output = "abcdefghijklmnopqrstuvwxyz0123456789\n\t\"?!.@{}[]();',./<>#$%^&*";
|
||||
assertEquals(StringUtils.decodeBase64(input), output);
|
||||
}
|
||||
*/
|
||||
|
||||
@Test
|
||||
public void testRandomString() {
|
||||
// Boundary test
|
||||
String result = StringUtils.randomString(-1);
|
||||
assertNull(result);
|
||||
|
||||
// Zero length string test
|
||||
result = StringUtils.randomString(0);
|
||||
assertNull(result);
|
||||
|
||||
// Test various lengths - make sure the same length is returned
|
||||
result = StringUtils.randomString(4);
|
||||
assertTrue(result.length() == 4);
|
||||
result = StringUtils.randomString(16);
|
||||
assertTrue(result.length() == 16);
|
||||
result = StringUtils.randomString(128);
|
||||
assertTrue(result.length() == 128);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParsing() {
|
||||
String error = "Error parsing node name";
|
||||
assertEquals(error, "", StringUtils.parseName("yahoo.myjabber.net"));
|
||||
assertEquals(error, "", StringUtils.parseName("yahoo.myjabber.net/registred"));
|
||||
assertEquals(error, "user", StringUtils.parseName("user@yahoo.myjabber.net/registred"));
|
||||
assertEquals(error, "user", StringUtils.parseName("user@yahoo.myjabber.net"));
|
||||
|
||||
error = "Error parsing server name";
|
||||
String result = "yahoo.myjabber.net";
|
||||
assertEquals(error, result, StringUtils.parseServer("yahoo.myjabber.net"));
|
||||
assertEquals(error, result, StringUtils.parseServer("yahoo.myjabber.net/registred"));
|
||||
assertEquals(error, result, StringUtils.parseServer("user@yahoo.myjabber.net/registred"));
|
||||
assertEquals(error, result, StringUtils.parseServer("user@yahoo.myjabber.net"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,232 @@
|
|||
/**
|
||||
*
|
||||
* Copyright 2003-2007 Jive Software.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.jivesoftware.smack.util;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class XmppDateTimeTest {
|
||||
@Test
|
||||
public void parseXep0082Date() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("1971-07-21");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(1971, cal.get(Calendar.YEAR));
|
||||
assertEquals(6, cal.get(Calendar.MONTH));
|
||||
assertEquals(21, cal.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0082Time() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("02:56:15");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(2, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(56, cal.get(Calendar.MINUTE));
|
||||
assertEquals(15, cal.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0082TimeUTC() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("02:56:15Z");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(2, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(56, cal.get(Calendar.MINUTE));
|
||||
assertEquals(15, cal.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0082TimeWithZone() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("04:40:15+02:30");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(2, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(10, cal.get(Calendar.MINUTE));
|
||||
assertEquals(15, cal.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0082TimeWithMillis() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("02:56:15.123");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(2, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(56, cal.get(Calendar.MINUTE));
|
||||
assertEquals(15, cal.get(Calendar.SECOND));
|
||||
assertEquals(123, cal.get(Calendar.MILLISECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0082TimeWithMillisUTC() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("02:56:15.123Z");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(2, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(56, cal.get(Calendar.MINUTE));
|
||||
assertEquals(15, cal.get(Calendar.SECOND));
|
||||
assertEquals(123, cal.get(Calendar.MILLISECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0082TimeWithMillisZone() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("02:56:15.123+01:00");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(1, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(56, cal.get(Calendar.MINUTE));
|
||||
assertEquals(15, cal.get(Calendar.SECOND));
|
||||
assertEquals(123, cal.get(Calendar.MILLISECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0082DateTimeUTC() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("1971-07-21T02:56:15Z");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(1971, cal.get(Calendar.YEAR));
|
||||
assertEquals(6, cal.get(Calendar.MONTH));
|
||||
assertEquals(21, cal.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(2, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(56, cal.get(Calendar.MINUTE));
|
||||
assertEquals(15, cal.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0082DateTimeZone() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("1971-07-21T02:56:15-01:00");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(1971, cal.get(Calendar.YEAR));
|
||||
assertEquals(6, cal.get(Calendar.MONTH));
|
||||
assertEquals(21, cal.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(3, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(56, cal.get(Calendar.MINUTE));
|
||||
assertEquals(15, cal.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0082DateTimeWithMillisUTC() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("1971-07-21T02:56:15.123Z");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(1971, cal.get(Calendar.YEAR));
|
||||
assertEquals(6, cal.get(Calendar.MONTH));
|
||||
assertEquals(21, cal.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(2, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(56, cal.get(Calendar.MINUTE));
|
||||
assertEquals(15, cal.get(Calendar.SECOND));
|
||||
assertEquals(123, cal.get(Calendar.MILLISECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0082DateTimeWithMillisZone() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("1971-07-21T02:56:15.123-01:00");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(1971, cal.get(Calendar.YEAR));
|
||||
assertEquals(6, cal.get(Calendar.MONTH));
|
||||
assertEquals(21, cal.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(3, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(56, cal.get(Calendar.MINUTE));
|
||||
assertEquals(15, cal.get(Calendar.SECOND));
|
||||
assertEquals(123, cal.get(Calendar.MILLISECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0091() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("20020910T23:08:25");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(2002, cal.get(Calendar.YEAR));
|
||||
assertEquals(8, cal.get(Calendar.MONTH));
|
||||
assertEquals(10, cal.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(8, cal.get(Calendar.MINUTE));
|
||||
assertEquals(25, cal.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0091NoLeading0() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("200291T23:08:25");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(2002, cal.get(Calendar.YEAR));
|
||||
assertEquals(8, cal.get(Calendar.MONTH));
|
||||
assertEquals(1, cal.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(8, cal.get(Calendar.MINUTE));
|
||||
assertEquals(25, cal.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0091AmbiguousMonthDay() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("2002101T23:08:25");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(2002, cal.get(Calendar.YEAR));
|
||||
assertEquals(9, cal.get(Calendar.MONTH));
|
||||
assertEquals(1, cal.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(8, cal.get(Calendar.MINUTE));
|
||||
assertEquals(25, cal.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseXep0091SingleDigitMonth() throws Exception {
|
||||
Date date = XmppDateTime.parseDate("2002130T23:08:25");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
assertEquals(2002, cal.get(Calendar.YEAR));
|
||||
assertEquals(0, cal.get(Calendar.MONTH));
|
||||
assertEquals(30, cal.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(8, cal.get(Calendar.MINUTE));
|
||||
assertEquals(25, cal.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test(expected = ParseException.class)
|
||||
public void parseNoMonthDay() throws Exception {
|
||||
XmppDateTime.parseDate("2002T23:08:25");
|
||||
}
|
||||
|
||||
@Test(expected = ParseException.class)
|
||||
public void parseNoYear() throws Exception {
|
||||
XmppDateTime.parseDate("130T23:08:25");
|
||||
}
|
||||
}
|
11
smack-core/src/test/resources/test.providers
Normal file
11
smack-core/src/test/resources/test.providers
Normal file
|
@ -0,0 +1,11 @@
|
|||
<?xml version="1.0"?>
|
||||
<!-- Providers file for default Smack extensions -->
|
||||
<smackProviders>
|
||||
|
||||
<iqProvider>
|
||||
<elementName>provider</elementName>
|
||||
<namespace>test:file_provider</namespace>
|
||||
<className>org.jivesoftware.smack.provider.ProviderConfigTest$TestIQProvider</className>
|
||||
</iqProvider>
|
||||
|
||||
</smackProviders>
|
Loading…
Add table
Add a link
Reference in a new issue