1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2025-09-12 18:49:39 +02:00

Jingle Extension added to Smack Repository

git-svn-id: http://svn.igniterealtime.org/svn/repos/smack/trunk@6517 b35dd754-fafc-0310-a699-88a17e54d16e
This commit is contained in:
Thiago Camargo 2007-01-04 17:25:30 +00:00 committed by thiago
parent f1972c2571
commit 4b6de6647b
104 changed files with 16411 additions and 0 deletions

View file

@ -0,0 +1,13 @@
<?xml version="1.0"?>
<!-- Default configuration for Smack test cases. -->
<testcase>
<!-- Host and port of the XMPP server to use -->
<host>localhost</host>
<port>5222</port>
<!-- Chat and MUC domain names to use -->
<chat>chat</chat>
<muc>conference</muc>
</testcase>

View file

@ -0,0 +1,368 @@
/**
* $RCSfile$
* $Revision: 5367 $
* $Date: 2006-09-14 16:16:40 -0300 (qui, 14 set 2006) $
*
* Copyright 2003-2005 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.test;
import junit.framework.TestCase;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;
import javax.net.SocketFactory;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
/**
* Base class for all the test cases which provides a pre-configured execution context. This
* means that any test case that subclassifies this base class will have access to a pool of
* connections and to the user of each connection. The maximum number of connections in the pool
* can be controlled by the message {@link #getMaxConnections()} which every subclass must
* implement.<p>
*
* This base class defines a default execution context (i.e. host, port, chat domain and muc
* domain) which can be found in the file "config/test-case.xml". However, each subclass could
* redefine the default configuration by providing its own configuration file (if desired). The
* name of the configuration file must be of the form <test class name>.xml (e.g. RosterTest.xml).
* The file must be placed in the folder "config". This folder is where the default configuration
* file is being held.
*
* @author Gaston Dombiak
*/
public abstract class SmackTestCase extends TestCase {
private String host = "localhost";
private String serviceName = "localhost";
private int port = 5222;
private String chatDomain = "chat";
private String mucDomain = "conference";
private XMPPConnection[] connections = null;
/**
* Constructor for SmackTestCase.
* @param arg0
*/
public SmackTestCase(String arg0) {
super(arg0);
}
/**
* Returns the maximum number of connections to initialize for this test case. All the
* initialized connections will be connected to the server using a new test account for
* each conection.
*
* @return the maximum number of connections to initialize for this test case.
*/
protected abstract int getMaxConnections();
/**
* Returns a SocketFactory that will be used to create the socket to the XMPP server. By
* default no SocketFactory is used but subclasses my want to redefine this method.<p>
*
* A custom SocketFactory allows fine-grained control of the actual connection to the XMPP
* server. A typical use for a custom SocketFactory is when connecting through a SOCKS proxy.
*
* @return a SocketFactory that will be used to create the socket to the XMPP server.
*/
protected SocketFactory getSocketFactory() {
return null;
}
/**
* Returns the XMPPConnection located at the requested position. Each test case holds a
* pool of connections which is initialized while setting up the test case. The maximum
* number of connections is controlled by the message {@link #getMaxConnections()} which
* every subclass must implement.<p>
*
* If the requested position is greater than the connections size then an
* IllegalArgumentException will be thrown.
*
* @param index the position in the pool of the connection to look for.
* @return the XMPPConnection located at the requested position.
*/
protected XMPPConnection getConnection(int index) {
if (index > getMaxConnections()) {
throw new IllegalArgumentException("Index out of bounds");
}
return connections[index];
}
/**
* Returns the name of the user (e.g. johndoe) that is using the connection
* located at the requested position.
*
* @param index the position in the pool of the connection to look for.
* @return the user of the user (e.g. johndoe).
*/
protected String getUsername(int index) {
if (index > getMaxConnections()) {
throw new IllegalArgumentException("Index out of bounds");
}
return "user" + index;
}
/**
* Returns the bare XMPP address of the user (e.g. johndoe@jabber.org) that is
* using the connection located at the requested position.
*
* @param index the position in the pool of the connection to look for.
* @return the bare XMPP address of the user (e.g. johndoe@jabber.org).
*/
protected String getBareJID(int index) {
return getUsername(index) + "@" + getConnection(index).getServiceName();
}
/**
* Returns the full XMPP address of the user (e.g. johndoe@jabber.org/Smack) that is
* using the connection located at the requested position.
*
* @param index the position in the pool of the connection to look for.
* @return the full XMPP address of the user (e.g. johndoe@jabber.org/Smack).
*/
protected String getFullJID(int index) {
return getBareJID(index) + "/Smack";
}
protected String getHost() {
return host;
}
protected int getPort() {
return port;
}
protected String getServiceName() {
return serviceName;
}
/**
* Returns the default groupchat service domain.
*
* @return the default groupchat service domain.
*/
protected String getChatDomain() {
return chatDomain;
}
/**
* Returns the default MUC service domain.
*
* @return the default MUC service domain.
*/
protected String getMUCDomain() {
return mucDomain + "." + serviceName;
}
protected void setUp() throws Exception {
super.setUp();
init();
if (getMaxConnections() < 1) {
return;
}
connections = new XMPPConnection[getMaxConnections()];
try {
// Connect to the server
for (int i = 0; i < getMaxConnections(); i++) {
// Create the configuration for this new connection
ConnectionConfiguration config = new ConnectionConfiguration(host, port);
config.setTLSEnabled(true);
config.setCompressionEnabled(Boolean.getBoolean("test.compressionEnabled"));
config.setSASLAuthenticationEnabled(true);
if (getSocketFactory() == null) {
connections[i] = new XMPPConnection(config);
}
else {
connections[i] = new XMPPConnection(config, getSocketFactory());
}
connections[i].connect();
}
// Use the host name that the server reports. This is a good idea in most
// cases, but could fail if the user set a hostname in their XMPP server
// that will not resolve as a network connection.
host = connections[0].getHost();
serviceName = connections[0].getServiceName();
// Create the test accounts
if (!getConnection(0).getAccountManager().supportsAccountCreation())
fail("Server does not support account creation");
for (int i = 0; i < getMaxConnections(); i++) {
// Create the test account
try {
getConnection(i).getAccountManager().createAccount("user" + i, "user" + i);
} catch (XMPPException e) {
// Do nothing if the accout already exists
if (e.getXMPPError() == null || e.getXMPPError().getCode() != 409) {
throw e;
}
}
// Login with the new test account
getConnection(i).login("user" + i, "user" + i);
}
// Let the server process the available presences
Thread.sleep(150);
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
protected void tearDown() throws Exception {
super.tearDown();
for (int i = 0; i < getMaxConnections(); i++) {
if (getConnection(i).isConnected()) {
// Delete the created account for the test
getConnection(i).getAccountManager().deleteAccount();
// Close the connection
getConnection(i).disconnect();
}
}
}
/**
* Initializes the context of the test case. We will first try to load the configuration from
* a file whose name is conformed by the test case class name plus an .xml extension
* (e.g RosterTest.xml). If no file was found under that name then we will try to load the
* default configuration for all the test cases from the file "config/test-case.xml".
*
*/
private void init() {
try {
boolean found = false;
// Try to load the configutation from an XML file specific for this test case
Enumeration resources =
ClassLoader.getSystemClassLoader().getResources(getConfigurationFilename());
while (resources.hasMoreElements()) {
found = parseURL((URL) resources.nextElement());
}
// If none was found then try to load the configuration from the default configuration
// file (i.e. "config/test-case.xml")
if (!found) {
resources = ClassLoader.getSystemClassLoader().getResources("config/test-case.xml");
while (resources.hasMoreElements()) {
found = parseURL((URL) resources.nextElement());
}
}
if (!found) {
System.err.println("File config/test-case.xml not found. Using default config.");
}
}
catch (Exception e) {
}
}
/**
* Returns true if the given URL was found and parsed without problems. The file provided
* by the URL must contain information useful for the test case configuration, such us,
* host and port of the server.
*
* @param url the url of the file to parse.
* @return true if the given URL was found and parsed without problems.
*/
private boolean parseURL(URL url) {
boolean parsedOK = false;
InputStream systemStream = null;
try {
systemStream = url.openStream();
XmlPullParser parser = new MXParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
parser.setInput(systemStream, "UTF-8");
int eventType = parser.getEventType();
do {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("host")) {
host = parser.nextText();
}
else if (parser.getName().equals("port")) {
port = parseIntProperty(parser, port);
}
else if (parser.getName().equals("serviceName")) {
serviceName = parser.nextText();
}
else if (parser.getName().equals("chat")) {
chatDomain = parser.nextText();
}
else if (parser.getName().equals("muc")) {
mucDomain = parser.nextText();
}
}
eventType = parser.next();
}
while (eventType != XmlPullParser.END_DOCUMENT);
parsedOK = true;
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
systemStream.close();
}
catch (Exception e) {
}
}
return parsedOK;
}
private static int parseIntProperty(XmlPullParser parser, int defaultValue) throws Exception {
try {
return Integer.parseInt(parser.nextText());
}
catch (NumberFormatException nfe) {
nfe.printStackTrace();
return defaultValue;
}
}
/**
* Returns the name of the configuration file related to <b>this</b> test case. By default all
* the test cases will use the same configuration file. However, it's possible to override the
* default configuration by providing a file of the form <test case class name>.xml
* (e.g. RosterTest.xml).
*
* @return the name of the configuration file related to this test case.
*/
private String getConfigurationFilename() {
String fullClassName = this.getClass().getName();
int firstChar = fullClassName.lastIndexOf('.') + 1;
return "config/" + fullClassName.substring(firstChar) + ".xml";
}
/**
* Compares two contents of two byte arrays to make sure that they are equal
*
* @param message The message to show in the case of failure
* @param byteArray1 The first byte array.
* @param byteArray2 The second byte array.
*/
public static void assertEquals(String message, byte [] byteArray1, byte [] byteArray2) {
if(byteArray1.length != byteArray2.length) {
fail(message);
}
for(int i = 0; i < byteArray1.length; i++) {
assertEquals(message, byteArray1[i], byteArray2[i]);
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,51 @@
package org.jivesoftware.smackx.jingle;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.jingle.nat.BasicResolver;
public class JingleSessionTest extends SmackTestCase {
public JingleSessionTest(final String name) {
super(name);
}
public void testEqualsObject() {
JingleSession js1 = new OutgoingJingleSession(getConnection(0), "res1", null, new BasicResolver());
JingleSession js2 = new OutgoingJingleSession(getConnection(1), "res1", null, new BasicResolver());
JingleSession js3 = new OutgoingJingleSession(getConnection(2), "res2", null, new BasicResolver());
System.out.println(js1.getSid());
System.out.println(js2.getSid());
js1.setInitiator("js1");
js2.setInitiator("js1");
js1.setSid("10");
js2.setSid("10");
assertEquals(js1, js2);
assertEquals(js2, js1);
assertFalse(js1.equals(js3));
}
public void testGetInstanceFor() {
String ini1 = "initiator1";
String sid1 = "sid1";
String ini2 = "initiator2";
String sid2 = "sid2";
JingleSession js1 = new OutgoingJingleSession(getConnection(0), sid1, null, new BasicResolver());
JingleSession js2 = new OutgoingJingleSession(getConnection(1), sid2, null, new BasicResolver());
// For a packet, we should be able to get a session that handles that...
assertNotNull(JingleSession.getInstanceFor(getConnection(0)));
assertNotNull(JingleSession.getInstanceFor(getConnection(1)));
assertEquals(JingleSession.getInstanceFor(getConnection(0)), js1);
assertEquals(JingleSession.getInstanceFor(getConnection(1)), js2);
}
protected int getMaxConnections() {
return 3;
}
}

View file

@ -0,0 +1,74 @@
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2002-2006 Jive Software. All rights reserved.
* ====================================================================
* The Jive Software License (based on Apache Software License, Version 1.1)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by
* Jive Software (http://www.jivesoftware.com)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Smack" and "Jive Software" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please
* contact webmaster@jivesoftware.com.
*
* 5. Products derived from this software may not be called "Smack",
* nor may "Smack" appear in their name, without prior written
* permission of Jive Software.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL JIVE SOFTWARE OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*/
package org.jivesoftware.smackx.jingle;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* Test suite that runs all the Jingle support tests
*
* @author Alvaro Saurin
*/
public class JingleSupportTests {
public static Test suite() {
TestSuite suite = new TestSuite("High and low level API tests for Jingle support");
// $JUnit-BEGIN$
suite.addTest(new TestSuite(JingleManagerTest.class));
// $JUnit-END$
return suite;
}
}

View file

@ -0,0 +1,89 @@
package org.jivesoftware.smackx.jingle;
import java.util.ArrayList;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.jingle.media.PayloadType;
public class PayloadTypeTest extends SmackTestCase {
public PayloadTypeTest(final String arg0) {
super(arg0);
}
public void testEqualsObject() {
PayloadType p1 = new PayloadType(0, "pt1", 2);
PayloadType p2 = new PayloadType(0, "pt1", 2);
assertTrue(p1.equals(p2));
}
/**
* Test for the difference of payloads.
*/
public void testDifference() {
ArrayList set1 = new ArrayList();
ArrayList set2 = new ArrayList();
PayloadType.Audio common1 = new PayloadType.Audio(34, "supercodec-1", 2, 14000);
PayloadType.Audio common2 = new PayloadType.Audio(56, "supercodec-2", 1, 44000);
set1.add(common1);
set1.add(common2);
set1.add(new PayloadType.Audio(36, "supercodec-3", 2, 28000));
set1.add(new PayloadType.Audio(45, "supercodec-4", 1, 98000));
set2.add(new PayloadType.Audio(27, "supercodec-3", 2, 28000));
set2.add(common2);
set2.add(new PayloadType.Audio(32, "supercodec-4", 1, 98000));
set2.add(common1);
// Get the difference
ArrayList commonSet = new ArrayList();
commonSet.addAll(set1);
commonSet.retainAll(set2);
assertTrue(commonSet.size() == 2);
System.out.println("Codec " + ((PayloadType.Audio)commonSet.get(0)).getId());
System.out.println("Codec " + ((PayloadType.Audio)commonSet.get(1)).getId());
assertTrue(commonSet.contains(common1));
assertTrue(commonSet.contains(common2));
}
/**
* Test for the difference of payloads when we are handling the same sets.
*/
public void testDifferenceSameSet() {
ArrayList set1 = new ArrayList();
ArrayList set2 = new ArrayList();
PayloadType.Audio common1 = new PayloadType.Audio(34, "supercodec-1", 2, 14000);
PayloadType.Audio common2 = new PayloadType.Audio(56, "supercodec-2", 1, 44000);
PayloadType.Audio common3 = new PayloadType.Audio(0, "supercodec-3", 1, 44000);
PayloadType.Audio common4 = new PayloadType.Audio(120, "supercodec-4", 2, 66060);
set1.add(common1);
set1.add(common2);
set1.add(common3);
set1.add(common4);
set2.add(common1);
set2.add(common2);
set2.add(common3);
set2.add(common4);
// Get the difference
ArrayList commonSet = new ArrayList();
commonSet.addAll(set1);
commonSet.retainAll(set2);
assertTrue(commonSet.size() == 4);
assertTrue(commonSet.contains(common1));
assertTrue(commonSet.contains(common2));
}
protected int getMaxConnections() {
return 0;
}
}

View file

@ -0,0 +1,101 @@
package org.jivesoftware.smackx.jingle.nat;
import org.jivesoftware.smack.test.SmackTestCase;
public class BasicResolverTest extends SmackTestCase {
private int counter;
private final Object mutex = new Object();
public BasicResolverTest(String arg) {
super(arg);
}
// Counter management
private void resetCounter() {
synchronized (mutex) {
counter = 0;
}
}
private void incCounter() {
synchronized (mutex) {
counter++;
}
}
private int valCounter() {
int val;
synchronized (mutex) {
val = counter;
}
return val;
}
public void testCheckValidHostname() {
String validHostname = new String("slashdot.org");
BasicResolver br = new BasicResolver();
TransportCandidate tc = new TransportCandidate.Fixed(validHostname, 0);
resetCounter();
tc.addListener(new TransportResolverListener.Checker() {
public void candidateChecked(TransportCandidate cand, boolean result) {
if(result == true) {
System.out.println(cand.getIp() + " is reachable (as expected)");
incCounter();
}
}
public void candidateChecking(TransportCandidate cand) {
}
});
tc.check();
try {
Thread.sleep(TransportResolver.CHECK_TIMEOUT);
} catch (Exception e) {
}
assertTrue(valCounter() > 0);
}
public void testCheckInvalidHostname() {
String invalidHostname = new String("camupilosupino.org");
BasicResolver br = new BasicResolver();
TransportCandidate tc = new TransportCandidate.Fixed(invalidHostname, 0);
resetCounter();
tc.addListener(new TransportResolverListener.Checker() {
public void candidateChecked(TransportCandidate cand, boolean result) {
if(result == false) {
System.out.println(cand.getIp() + " is _not_ reachable (as expected)");
incCounter();
}
}
public void candidateChecking(TransportCandidate cand) {
}
});
tc.check();
try {
Thread.sleep(TransportResolver.CHECK_TIMEOUT);
} catch (Exception e) {
}
assertTrue(valCounter() > 0);
}
protected int getMaxConnections() {
return 0;
}
}

View file

@ -0,0 +1,172 @@
package org.jivesoftware.smackx.jingle.nat;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.jingle.IncomingJingleSession;
import org.jivesoftware.smackx.jingle.JingleManager;
import org.jivesoftware.smackx.jingle.JingleSessionRequest;
import org.jivesoftware.smackx.jingle.OutgoingJingleSession;
import org.jivesoftware.smackx.jingle.listeners.JingleSessionRequestListener;
import org.jivesoftware.smackx.jingle.media.JingleMediaManager;
import org.jivesoftware.smackx.jingle.media.JingleMediaSession;
import org.jivesoftware.smackx.jingle.media.PayloadType;
public class BridgedResolverTest extends SmackTestCase {
private int counter;
private final Object mutex = new Object();
public BridgedResolverTest(String arg) {
super(arg);
}
// Counter management
private void resetCounter() {
synchronized (mutex) {
counter = 0;
}
}
private void incCounter() {
synchronized (mutex) {
counter++;
}
}
private int valCounter() {
int val;
synchronized (mutex) {
val = counter;
}
return val;
}
public void testCheckService() {
assertTrue(RTPBridge.serviceAvailable(getConnection(0)));
}
public void testGetBridge() {
resetCounter();
RTPBridge rtpBridge = RTPBridge.getRTPBridge(getConnection(0), "001");
System.out.println(rtpBridge.getIp() + " portA:" + rtpBridge.getPortA() + " portB:" + rtpBridge.getPortB());
if (rtpBridge != null) {
if (rtpBridge.getIp() != null) incCounter();
if (rtpBridge.getPortA() != -1) incCounter();
if (rtpBridge.getPortB() != -1) incCounter();
}
assertTrue(valCounter() == 3);
}
public void testFullBridge() {
resetCounter();
try {
//XMPPConnection.DEBUG_ENABLED = true;
XMPPConnection x0 = new XMPPConnection("thiago");
XMPPConnection x1 = new XMPPConnection("thiago");
x0.connect();
x0.login("barata7", "barata7");
x1.connect();
x1.login("barata6", "barata6");
final JingleManager jm0 = new JingleManager(
x0, new BridgedResolver(x0));
final JingleManager jm1 = new JingleManager(
x1, new BridgedResolver(x1));
JingleMediaManager jingleMediaManager = new JingleMediaManager() {
// Media Session Implementation
public JingleMediaSession createMediaSession(final PayloadType payloadType, final TransportCandidate remote, final TransportCandidate local) {
return new JingleMediaSession(payloadType, remote, local) {
public void initialize() {
}
public void startTrasmit() {
incCounter();
System.out.print("IPs:");
System.out.println(local.getSymmetric().getIp());
System.out.println(local.getIp());
System.out.println("Transmit");
}
public void startReceive() {
incCounter();
System.out.println("Receive");
}
public void setTrasmit(boolean active) {
}
public void stopTrasmit() {
incCounter();
System.out.println("Stop Transmit");
}
public void stopReceive() {
incCounter();
System.out.println("Stop Receive");
}
};
}
};
jingleMediaManager.addPayloadType(new PayloadType.Audio(3, "GSM", 1, 16000));
jm0.setMediaManager(jingleMediaManager);
jm1.setMediaManager(jingleMediaManager);
jm1.addJingleSessionRequestListener(new JingleSessionRequestListener() {
public void sessionRequested(final JingleSessionRequest request) {
try {
IncomingJingleSession session = request.accept(jm1.getMediaManager().getPayloads());
session.start(request);
} catch (XMPPException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
OutgoingJingleSession js0 = jm0.createOutgoingJingleSession("barata6@thiago/Smack");
js0.start();
Thread.sleep(10000);
js0.terminate();
Thread.sleep(3000);
System.out.println(valCounter());
assertTrue(valCounter() == 8);
//Thread.sleep(15000);
} catch (Exception e) {
e.printStackTrace();
}
}
protected int getMaxConnections() {
return 1;
}
}

View file

@ -0,0 +1,342 @@
package org.jivesoftware.smackx.jingle.nat;
import de.javawi.jstun.test.demo.ice.Candidate;
import de.javawi.jstun.test.demo.ice.ICENegociator;
import de.javawi.jstun.util.UtilityException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.jingle.*;
import org.jivesoftware.smackx.jingle.listeners.JingleSessionListener;
import org.jivesoftware.smackx.jingle.listeners.JingleSessionRequestListener;
import org.jivesoftware.smackx.jingle.media.PayloadType;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Test the STUN IP resolver.
*
* @author alvaro
*/
public class STUNResolverTest extends SmackTestCase {
// Counter management
public STUNResolverTest(final String arg) {
super(arg);
}
private int counter;
private final Object mutex = new Object();
private void resetCounter() {
synchronized (mutex) {
counter = 0;
}
}
private void incCounter() {
synchronized (mutex) {
counter++;
}
}
private int valCounter() {
int val;
synchronized (mutex) {
val = counter;
}
return val;
}
/**
* Test for getPreferredCandidate()
*
* @throws Exception
*/
public void testGetPreferredCandidate() throws Exception {
int highestPref = 100;
TransportCandidate cand1 = new TransportCandidate.Ice("192.168.2.1", 3, 2,
"password", 3468, "username1", 1);
TransportCandidate cand2 = new TransportCandidate.Ice("192.168.5.1", 2, 10,
"password", 3469, "username2", 15);
TransportCandidate candH = new TransportCandidate.Ice("192.168.2.11", 1, 2,
"password", 3468, "usernameH", highestPref);
TransportCandidate cand3 = new TransportCandidate.Ice("192.168.2.10", 2, 10,
"password", 3469, "username3", 2);
TransportCandidate cand4 = new TransportCandidate.Ice("192.168.4.1", 3, 2,
"password", 3468, "username4", 78);
STUNResolver stunResolver = new STUNResolver() {
};
stunResolver.addCandidate(cand1);
stunResolver.addCandidate(cand2);
stunResolver.addCandidate(candH);
stunResolver.addCandidate(cand3);
stunResolver.addCandidate(cand4);
assertEquals(stunResolver.getPreferredCandidate(), candH);
}
/**
* Test for getPreferredCandidate()
*
* @throws Exception
*/
public void testGetPreferredCandidateICE() throws Exception {
int highestPref = 100;
TransportCandidate cand1 = new TransportCandidate.Ice("192.168.2.1", 3, 2,
"password", 3468, "username1", 1);
TransportCandidate cand2 = new TransportCandidate.Ice("192.168.5.1", 2, 10,
"password", 3469, "username2", 15);
TransportCandidate candH = new TransportCandidate.Ice("192.168.2.11", 1, 2,
"password", 3468, "usernameH", highestPref);
TransportCandidate cand3 = new TransportCandidate.Ice("192.168.2.10", 2, 10,
"password", 3469, "username3", 2);
TransportCandidate cand4 = new TransportCandidate.Ice("192.168.4.1", 3, 2,
"password", 3468, "username4", 78);
ICEResolver iceResolver = new ICEResolver() {
};
iceResolver.addCandidate(cand1);
iceResolver.addCandidate(cand2);
iceResolver.addCandidate(candH);
iceResolver.addCandidate(cand3);
iceResolver.addCandidate(cand4);
assertEquals(iceResolver.getPreferredCandidate(), candH);
}
/**
* Test priority generated by STUN lib
*
* @throws Exception
*/
public void testICEPriority() throws Exception {
String first = "";
for (int i = 0; i < 100; i++) {
ICENegociator cc = new ICENegociator((short) 1);
// gather candidates
cc.gatherCandidateAddresses();
// priorize candidates
cc.prioritizeCandidates();
// get SortedCandidates
//List<Candidate> sortedCandidates = cc.getSortedCandidates();
for (Candidate candidate : cc.getSortedCandidates())
try {
TransportCandidate transportCandidate = new TransportCandidate.Ice(candidate.getAddress().getInetAddress().getHostAddress(), 1, candidate.getNetwork(), "1", candidate.getPort(), "1", candidate.getPriority());
transportCandidate.setLocalIp(candidate.getBase().getAddress().getInetAddress().getHostAddress());
System.out.println("C: " + candidate.getAddress().getInetAddress() + "|" + candidate.getBase().getAddress().getInetAddress() + " p:" + candidate.getPriority());
} catch (UtilityException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Candidate candidate = cc.getSortedCandidates().get(0);
String temp = "C: " + candidate.getAddress().getInetAddress() + "|" + candidate.getBase().getAddress().getInetAddress() + " p:" + candidate.getPriority();
if (first.equals(""))
first = temp;
assertEquals(first, temp);
first = temp;
}
}
/**
* Test for loadSTUNServers()
*
* @throws Exception
*/
public void testLoadSTUNServers() throws Exception {
STUNResolver stunResolver = new STUNResolver() {
};
ArrayList stunServers = stunResolver.loadSTUNServers();
assertTrue(stunServers.size() > 0);
System.out.println(stunServers.size() + " servers loaded");
}
/**
* Test for resolve()
*
* @throws Exception
*/
public void testResolve() throws Exception {
final STUNResolver stunResolver = new STUNResolver() {
};
stunResolver.addListener(new TransportResolverListener.Resolver() {
public void candidateAdded(final TransportCandidate cand) {
incCounter();
String addr = cand.getIp();
int port = cand.getPort();
System.out.println("Addr: " + addr + " port:" + port);
}
public void init() {
System.out.println("Resolution started");
}
public void end() {
System.out.println("Resolution finished");
}
});
try {
stunResolver.initialize();
Thread.sleep(55000);
assertTrue(valCounter() > 0);
stunResolver.resolve();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate a list of payload types
*
* @return A testing list
*/
private ArrayList getTestPayloads1() {
ArrayList result = new ArrayList();
result.add(new PayloadType.Audio(34, "supercodec-1", 2, 14000));
result.add(new PayloadType.Audio(56, "supercodec-2", 1, 44000));
result.add(new PayloadType.Audio(36, "supercodec-3", 2, 28000));
result.add(new PayloadType.Audio(45, "supercodec-4", 1, 98000));
return result;
}
private ArrayList getTestPayloads2() {
ArrayList result = new ArrayList();
result.add(new PayloadType.Audio(27, "supercodec-3", 2, 28000));
result.add(new PayloadType.Audio(56, "supercodec-2", 1, 44000));
result.add(new PayloadType.Audio(32, "supercodec-4", 1, 98000));
result.add(new PayloadType.Audio(34, "supercodec-1", 2, 14000));
return result;
}
/**
* This is a simple test where the user_2 rejects the Jingle session.
*/
public void testSTUNJingleSession() {
resetCounter();
try {
TransportResolver tr1 = new STUNResolver() {
};
TransportResolver tr2 = new STUNResolver() {
};
// Explicit resolution
tr1.resolve();
tr2.resolve();
final JingleManager man0 = new JingleManager(getConnection(0), tr1);
final JingleManager man1 = new JingleManager(getConnection(1), tr2);
man1.addJingleSessionRequestListener(new JingleSessionRequestListener() {
/**
* Called when a new session request is detected
*/
public void sessionRequested(final JingleSessionRequest request) {
System.out.println("Session request detected, from "
+ request.getFrom() + ": accepting.");
// We accept the request
IncomingJingleSession session1;
try {
session1 = request.accept(getTestPayloads2());
session1.addListener(new JingleSessionListener() {
public void sessionClosed(String reason, JingleSession jingleSession) {
}
public void sessionClosedOnError(XMPPException e, JingleSession jingleSession) {
}
public void sessionDeclined(String reason, JingleSession jingleSession) {
}
public void sessionEstablished(PayloadType pt,
TransportCandidate rc, TransportCandidate lc, JingleSession jingleSession) {
incCounter();
System.out
.println("Responder: the session is fully established.");
System.out.println("+ Payload Type: " + pt.getId());
System.out.println("+ Local IP/port: " + lc.getIp() + ":"
+ lc.getPort());
System.out.println("+ Remote IP/port: " + rc.getIp() + ":"
+ rc.getPort());
}
public void sessionRedirected(String redirection, JingleSession jingleSession) {
}
});
session1.start(request);
} catch (XMPPException e) {
e.printStackTrace();
}
}
});
// Session 0 starts a request
System.out.println("Starting session request, to " + getFullJID(1) + "...");
OutgoingJingleSession session0 = man0.createOutgoingJingleSession(
getFullJID(1), getTestPayloads1());
session0.addListener(new JingleSessionListener() {
public void sessionClosed(String reason, JingleSession jingleSession) {
}
public void sessionClosedOnError(XMPPException e, JingleSession jingleSession) {
}
public void sessionDeclined(String reason, JingleSession jingleSession) {
}
public void sessionEstablished(PayloadType pt,
TransportCandidate rc, TransportCandidate lc, JingleSession jingleSession) {
incCounter();
System.out.println("Initiator: the session is fully established.");
System.out.println("+ Payload Type: " + pt.getId());
System.out.println("+ Local IP/port: " + lc.getIp() + ":"
+ lc.getPort());
System.out.println("+ Remote IP/port: " + rc.getIp() + ":"
+ rc.getPort());
}
public void sessionRedirected(String redirection, JingleSession jingleSession) {
}
});
session0.start(null);
Thread.sleep(60000);
assertTrue(valCounter() == 2);
} catch (Exception e) {
e.printStackTrace();
fail("An error occured with Jingle");
}
}
protected int getMaxConnections() {
return 2;
}
}

View file

@ -0,0 +1,59 @@
package org.jivesoftware.smackx.jingle.nat;
import java.util.ArrayList;
import java.util.Collections;
import org.jivesoftware.smack.test.SmackTestCase;
public class TransportCandidateTest extends SmackTestCase {
public TransportCandidateTest(final String arg0) {
super(arg0);
}
/**
* Test for equals()
*/
public void testEqualsObject() {
TransportCandidate cand1 = new TransportCandidate.Ice("192.168.2.1", 1, 2,
"password", 3468, "username", 25);
TransportCandidate cand2 = new TransportCandidate.Ice("192.168.2.1", 1, 2,
"password", 3468, "username", 25);
TransportCandidate cand3 = new TransportCandidate.Ice("192.168.2.1", 1, 2,
"password", 3469, "username", 25);
assertEquals(cand1, cand2);
assertFalse(cand1.equals(cand3));
}
/**
* Test for compareTo()
*/
public void testCompareTo() {
int highestPref = 100;
TransportCandidate cand1 = new TransportCandidate.Ice("192.168.2.1", 3, 2,
"password", 3468, "username", 1);
TransportCandidate cand2 = new TransportCandidate.Ice("192.168.5.1", 2, 10,
"password", 3469, "username", 15);
TransportCandidate candH = new TransportCandidate.Ice("192.168.2.1", 1, 2,
"password", 3468, "username", highestPref);
TransportCandidate cand3 = new TransportCandidate.Ice("192.168.2.10", 2, 10,
"password", 3469, "username", 2);
TransportCandidate cand4 = new TransportCandidate.Ice("192.168.4.1", 3, 2,
"password", 3468, "username", 78);
ArrayList candList = new ArrayList();
candList.add(cand1);
candList.add(cand2);
candList.add(candH);
candList.add(cand3);
candList.add(cand4);
Collections.sort(candList);
assertEquals(candList.get(candList.size() - 1), candH);
}
protected int getMaxConnections() {
return 0;
}
}

View file

@ -0,0 +1,50 @@
package org.jivesoftware.smackx.jingle.nat;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.test.SmackTestCase;
public class TransportResolverTest extends SmackTestCase {
public TransportResolverTest(final String arg) {
super(arg);
}
public void testIsResolving() {
final TransportResolver tr = new BasicResolver();
tr.addListener(
new TransportResolverListener.Resolver() {
public void candidateAdded(final TransportCandidate cand) {
System.out.println("candidateAdded() called.");
assertTrue(tr.isResolving() || (!tr.isResolving() && tr.isResolved()));
}
public void end() {
System.out.println("end() called.");
assertFalse(tr.isResolving());
assertTrue(tr.isResolved());
}
public void init() {
System.out.println("init() called.");
assertTrue(tr.isResolving());
assertFalse(tr.isResolved());
}
});
assertFalse(tr.isResolving());
assertFalse(tr.isResolved());
try {
tr.resolve();
} catch (XMPPException e) {
e.printStackTrace();
fail("Error resolving");
}
}
protected int getMaxConnections() {
return 0;
}
}

View file

@ -0,0 +1,112 @@
package org.jivesoftware.smackx.provider;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.provider.IQProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.packet.Jingle;
public class JingleProviderTest extends SmackTestCase {
public JingleProviderTest(final String name) {
super(name);
}
public void testProviderManager() {
IQProvider iqProv;
String elementNamee = Jingle.getElementName();
String nameSpace = Jingle.getNamespace();
System.out.println("Testing if the Jingle IQ provider is registered...");
// Verify that the Jingle IQProvider is registered.
iqProv = (IQProvider)ProviderManager.getInstance().getIQProvider(elementNamee, nameSpace);
assertNotNull(iqProv);
}
/**
* Test for parsing a Jingle
*/
public void testParseIQSimple() {
// Create a dummy packet for testing...
IQfake iqSent = new IQfake (
" <jingle xmlns='http://jabber.org/protocol/jingle'" +
" initiator=\"gorrino@viejo.com\"" +
" responder=\"colico@hepatico.com\"" +
" action=\"transport-info\" sid=\"\">" +
" <transport xmlns='http://jabber.org/protocol/jingle/transport/ice'>" +
" <candidate generation=\"1\"" +
" ip=\"192.168.1.1\"" +
" password=\"secret\"" +
" port=\"8080\"" +
" username=\"username\"" +
" preference=\"1\"/>" +
" </transport>" +
"</jingle>");
iqSent.setTo(getFullJID(0));
iqSent.setFrom(getFullJID(0));
iqSent.setType(IQ.Type.GET);
// Create a filter and a collector...
PacketFilter filter = new PacketTypeFilter(IQ.class);
PacketCollector collector = getConnection(0).createPacketCollector(filter);
System.out.println("Testing if a Jingle IQ can be sent and received...");
// Send the iq packet with an invalid namespace
getConnection(0).sendPacket(iqSent);
// Receive the packet
IQ iqReceived = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
collector.cancel();
if (iqReceived == null) {
fail("No response from server");
}
else if (iqReceived.getType() == IQ.Type.ERROR) {
fail("The server did reply with an error packet: " + iqReceived.getError().getCode());
}
else {
assertTrue(iqReceived instanceof Jingle);
Jingle jin = (Jingle) iqReceived;
System.out.println("Sent: " + iqSent.toXML());
System.out.println("Received: " + jin.toXML());
}
}
/**
* Simple class for testing an IQ...
* @author Alvaro Saurin
*/
private class IQfake extends IQ {
private String s;
public IQfake(final String s) {
super();
this.s = s;
}
public String getChildElementXML() {
StringBuffer buf = new StringBuffer();
buf.append(s);
return buf.toString();
}
}
protected int getMaxConnections() {
return 2;
}
}