Initial sip-communicator-1.0 commit

cusax-fix
Emil Ivov 20 years ago
parent c82e7e1327
commit 17a21968ee

@ -0,0 +1,11 @@
Bundle-Name: The JUnit Framework
Bundle-Description: A bundle that exports junit packages
Bundle-Vendor: JUnit and sip-communicator.org
Bundle-Version: 0.0.1
Export-Package: junit,
junit.framework,
junit.swingui,
junit.textui,
junit.awtui,
junit.extensions,
junit.runner,

@ -0,0 +1,31 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.service.gui;
import junit.framework.*;
import net.java.sip.communicator.service.protocol.*;
/**
* Runs all PhoneUIService unit tests.
*
* @author Emil Ivov
*/
public class TestSuitePhoneUIService
extends TestCase
{
public TestSuitePhoneUIService(String s)
{
super(s);
}
public static Test suite()
{
TestSuite suite = new TestSuite();
return suite;
}
}

@ -0,0 +1,62 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.service.protocol;
import junit.framework.*;
/**
* Tests the call abstract class
*
* @author Emil Ivov
*/
public class TestCall extends TestCase
{
private Call call = null;
private String callID = "identifier0123456789";
// private class DummyCall extends Call
// {
// public DummyCall()
// {
// super(callID);
// }
// };
// protected void setUp() throws Exception
// {
// super.setUp();
// call = new DummyCall();
// }
//
protected void tearDown() throws Exception
{
call = null;
super.tearDown();
}
public void testEquals()
{
Object obj = null;
boolean expectedReturn = false;
boolean actualReturn = call.equals(obj);
assertEquals("return value", expectedReturn, actualReturn);
// obj = new DummyCall();
// expectedReturn = true;
// actualReturn = call.equals(obj);
// assertEquals("return value", expectedReturn, actualReturn);
}
public void testGetCallID()
{
String expectedReturn = callID;
String actualReturn = call.getCallID();
assertEquals("return value", expectedReturn, actualReturn);
}
}

@ -0,0 +1,78 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.service.protocol;
import junit.framework.*;
/**
* @author Emil Ivov
*/
public class TestCallParticipantState extends TestCase
{
private CallParticipantState callParticipantState = null;
protected void setUp() throws Exception
{
super.setUp();
}
protected void tearDown() throws Exception
{
super.tearDown();
}
public void testGetStateString()
{
String expectedReturn = CallParticipantState._BUSY;
String actualReturn = CallParticipantState.BUSY.getStateString();
assertEquals("the BUSY state has an invalid string repr."
,expectedReturn, actualReturn);
expectedReturn = CallParticipantState._INCOMING_CALL;
actualReturn = CallParticipantState.INCOMING_CALL.getStateString();
assertEquals("the CALLING state has an invalid string repr."
,expectedReturn, actualReturn);
expectedReturn = CallParticipantState._UNKNOWN;
actualReturn = CallParticipantState.UNKNOWN.getStateString();
assertEquals("the UNKNOWN state has an invalid string repr."
,expectedReturn, actualReturn);
expectedReturn = CallParticipantState._CONNECTED;
actualReturn = CallParticipantState.CONNECTED.getStateString();
assertEquals("the CONNECTED state has an invalid string repr."
,expectedReturn, actualReturn);
expectedReturn = CallParticipantState._CONNECTING;
actualReturn = CallParticipantState.CONNECTING.getStateString();
assertEquals("the CONNECTING state has an invalid string repr."
,expectedReturn, actualReturn);
expectedReturn = CallParticipantState._DISCONNECTED;
actualReturn = CallParticipantState.DISCONNECTED.getStateString();
assertEquals("the DISCONNECTED state has an invalid string repr."
,expectedReturn, actualReturn);
expectedReturn = CallParticipantState._FAILED;
actualReturn = CallParticipantState.FAILED.getStateString();
assertEquals("the FAILED state has an invalid string repr."
,expectedReturn, actualReturn);
expectedReturn = CallParticipantState._ALERTING_REMOTE_SIDE;
actualReturn = CallParticipantState.ALERTING_REMOTE_SIDE.getStateString();
assertEquals("the RINGING state has an invalid string repr."
,expectedReturn, actualReturn);
expectedReturn = CallParticipantState._ON_HOLD;
actualReturn = CallParticipantState.ON_HOLD.getStateString();
assertEquals("the ON_HOLD state has an invalid string repr."
,expectedReturn, actualReturn);
}
}

@ -0,0 +1,212 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.service.protocol;
import junit.framework.*;
import net.java.sip.communicator.service.gui.event.*;
import java.util.*;
import net.java.sip.communicator.service.protocol.event.*;
public class TestDefaultCallParticipant extends TestCase
{
private DefaultCallParticipant defaultCallParticipant = null;
private CallParticipantChangeEvent lastCpChangeEvent = null;
private class CpAdapter implements CallParticipantListener{
public void participantChange(CallParticipantChangeEvent evt){
lastCpChangeEvent = evt;
}
}
protected void setUp() throws Exception
{
super.setUp();
defaultCallParticipant = new DefaultCallParticipant();
}
protected void tearDown() throws Exception
{
defaultCallParticipant = null;
lastCpChangeEvent = null;
super.tearDown();
}
/**
* Test whether the call state is properly changed, the currentStateStartDate
* is properly updated, and the corresponding event properly dispatched.
*/
public void testEnterStateAndEventDispatch()
{
CallParticipantState oldState = defaultCallParticipant.getState();
CallParticipantState newState = CallParticipantState.CONNECTED;
CpAdapter adapter = new CpAdapter();
defaultCallParticipant.addCallParticipantListener(adapter);
long timeBeforeChange = System.currentTimeMillis();
defaultCallParticipant.enterState(newState);
long timeAfterChange = System.currentTimeMillis();
//check status change
assertEquals(newState, defaultCallParticipant.getState());
//check event dispatch
assertNotNull(lastCpChangeEvent);
assertEquals(lastCpChangeEvent.getOldValue(), oldState);
assertEquals(lastCpChangeEvent.getNewValue(), newState);
//check the date
long currentStateStartDate =
defaultCallParticipant.getCurrentStateStartDate().getTime();
assertTrue("currentStateStart date is not properly updated",
currentStateStartDate >= timeBeforeChange
&& currentStateStartDate <= timeAfterChange);
//remove the listener
defaultCallParticipant.removeCallParticipantListener(adapter);
lastCpChangeEvent = null;
defaultCallParticipant.enterState(CallParticipantState.DISCONNECTED);
assertNull("a listener was not properly removed", lastCpChangeEvent);
}
public void testSetAddress()
{
String expectedReturn = "sip:abc@def.ghi";
String secondChange = "sip:jkl@mno.pqr";
defaultCallParticipant.setAddress(expectedReturn);
defaultCallParticipant.addCallParticipantListener(new CpAdapter());
String actualReturn = defaultCallParticipant.getAddress();
assertEquals("address getter or setter fails", expectedReturn, actualReturn);
//check event dispatch
defaultCallParticipant.setAddress(secondChange);
assertNotNull("setAddress did not trigger an event", lastCpChangeEvent);
assertEquals("setAddress triggered an event with the wrong type",
lastCpChangeEvent.getEventType(),
CallParticipantChangeEvent.CALL_PARTICIPANT_ADDRESS_CHANGE
);
assertEquals("event triggerred by setAddress had a bad oldValue",
lastCpChangeEvent.getOldValue(),
expectedReturn
);
assertEquals("event triggerred by setAddress had a bad newValue",
lastCpChangeEvent.getNewValue(),
secondChange
);
}
public void testSetDisplayName()
{
String expectedReturn = "Rachel Weisz";
String secondChange = "Keanu Reeves";
defaultCallParticipant.setDisplayName(expectedReturn);
String actualReturn = defaultCallParticipant.getDisplayName();
assertEquals("DisplayName setter or getter failed", expectedReturn, actualReturn);
//check event dispatch
defaultCallParticipant.addCallParticipantListener(new CpAdapter());
defaultCallParticipant.setDisplayName(secondChange);
assertNotNull("setDisplayName did not trigger an event", lastCpChangeEvent);
assertEquals("setDisplayName triggered an event with the wrong type",
lastCpChangeEvent.getEventType(),
CallParticipantChangeEvent.CALL_PARTICIPANT_DISPLAY_NAME_CHANGE
);
assertEquals("event triggerred by setDisplayName had a bad oldValue",
lastCpChangeEvent.getOldValue(),
expectedReturn
);
assertEquals("event triggerred by setDisplayName had a bad newValue",
lastCpChangeEvent.getNewValue(),
secondChange
);
}
//
// private class DummyCall extends Call
// {
// public DummyCall()
// {
// super("identifier0123456789");
// }
// };
public void testSetCallID()
{
// Call expectedReturn = new DummyCall();
// defaultCallParticipant.setCall(expectedReturn);
// Call actualReturn = defaultCallParticipant.getCall();
// assertEquals("Call setter or getter (or Call.equals() method) failed",
// expectedReturn, actualReturn);
}
public void testSetImage()
{
byte[] expectedReturn = new byte[]{0, 1, 2, 3, 4, 5};
defaultCallParticipant.setImage(expectedReturn);
byte[] actualReturn = defaultCallParticipant.getImage();
assertEquals("image gettter or setter failed", expectedReturn, actualReturn);
//check event dispatch
defaultCallParticipant.addCallParticipantListener(new CpAdapter());
byte[] secondChange = new byte[]{5, 6, 7, 8, 9};
defaultCallParticipant.setImage(secondChange);
assertNotNull("setImage did not trigger an event", lastCpChangeEvent);
assertEquals("setImage triggered an event with the wrong type",
lastCpChangeEvent.getEventType(),
CallParticipantChangeEvent.CALL_PARTICIPANT_IMAGE_CHANGE
);
assertEquals("event triggerred by setImage had a bad oldValue",
lastCpChangeEvent.getOldValue(),
expectedReturn
);
assertEquals("event triggerred by setImage had a bad newValue",
lastCpChangeEvent.getNewValue(),
secondChange
);
}
public void testGetParticipantID()
{
String expectedReturn = "1234567890";
defaultCallParticipant.setParticipantID(expectedReturn);
String actualReturn = defaultCallParticipant.getParticipantID();
assertEquals("participantID getter or setter failed", expectedReturn, actualReturn);
}
public void testIsCaller()
{
boolean expectedReturn = true;
defaultCallParticipant.setIsCaller(expectedReturn);
boolean actualReturn = defaultCallParticipant.isCaller();
assertEquals("isCaller getter or setter failed", expectedReturn, actualReturn);
}
public void testToString()
{
String expectedReturn = "Emil Ivov <sip:emcho@sip.com>;status=Connected";
DefaultCallParticipant dcp = new DefaultCallParticipant();
dcp.setDisplayName("Emil Ivov");
dcp.setAddress("sip:emcho@sip.com");
dcp.enterState(CallParticipantState.CONNECTED);
assertEquals("toString failed", expectedReturn, dcp.toString());
}
}

@ -0,0 +1,55 @@
package net.java.sip.communicator.slick.configuration;
import org.osgi.framework.*;
import junit.framework.*;
import net.java.sip.communicator.service.configuration.*;
import java.util.*;
import net.java.sip.communicator.util.*;
/**
* @author Emil Ivov
*/
public class ConfigurationServiceLick
extends TestSuite
implements BundleActivator
{
private Logger logger = Logger.getLogger(getClass().getName());
protected static ConfigurationService configurationService = null;
protected static BundleContext bc = null;
public static TestCase tcase = new TestCase(){};
/**
* Start the Configuration Sevice Implementation Compatibility Kit.
*
* @param bundleContext BundleContext
* @throws Exception
*/
public void start(BundleContext bundleContext) throws Exception
{
ConfigurationServiceLick.bc = bundleContext;
setName("ConfigurationServiceLick");
Hashtable properties = new Hashtable();
properties.put("service.pid", getName());
addTestSuite(TestConfigurationService.class);
addTestSuite(TestConfigurationServicePersistency.class);
bundleContext.registerService(getClass().getName(), this, properties);
logger.debug("Successfully registered " + getClass().getName());
}
/**
* stop
*
* @param bundlecontext BundleContext
* @throws Exception
*/
public void stop(BundleContext bundlecontext) throws Exception
{
}
}

@ -0,0 +1,617 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.slick.configuration;
import junit.framework.*;
import net.java.sip.communicator.service.configuration.event.*;
import net.java.sip.communicator.service.configuration.*;
import org.osgi.framework.*;
import net.java.sip.communicator.impl.configuration.xml.*;
import net.java.sip.communicator.util.xml.*;
import net.java.sip.communicator.slick.slickless.*;
/**
* Tests basic ConfiguratioService behaviour.
*
* @author Emil Ivov
*/
public class TestConfigurationService extends TestCase
{
/**
* The ConfigurationService that we will be testing.
*/
private ConfigurationService configurationService = null;
/**
* The PropertyChangeEvent that our test listeners will capture for testing.
* Make sure we null that upon tear down
*/
private PropertyChangeEvent propertyChangeEvent = null;
/**
* The name of a property that we will be using for testing.
*/
private String propertyName = new String("my.test.property");
/**
* The name of a property that we will be using for testing custom event
* notification.
*/
private String listenedPropertyName = new String("a.property.i.listen.to");
/**
* The value of the property with name propertyName.
*/
private Integer propertyValue = new Integer(19200);
/**
* A new value for the property with name propertyName
*/
private Integer propertyNewValue = new Integer(19201);
/**
* A PropertyChange listener impl that registers the last received event.
*/
private PropertyChangeListener pListener = new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent event)
{
propertyChangeEvent = event;
}
};
/**
* A straightforward Vetoable change listener that throws an exception
* upon any change
*/
VetoableChangeListener rudeVetoListener = new VetoableChangeListener()
{
public void vetoableChange(PropertyChangeEvent event) throws
PropertyVetoException
{
throw new PropertyVetoException("Just for the fun of it", event);
}
};
/**
* A straightforward implementation of a vetoable change listener that that
* does not throw a veto exception and only stored the last received event.
*/
VetoableChangeListener gentleVetoListener = new VetoableChangeListener()
{
public void vetoableChange(PropertyChangeEvent event) throws
PropertyVetoException
{
propertyChangeEvent = event;
}
};
/**
* Generic JUnit Constructor.
* @param name the name of the test
*/
public TestConfigurationService(String name)
{
super(name);
BundleContext context = ConfigurationServiceLick.bc;
ServiceReference ref = context.getServiceReference(
ConfigurationService.class.getName());
configurationService = (ConfigurationService)context.getService(ref);
}
/**
* Generic JUnit setUp method.
* @throws Exception if anything goes wrong.
*/
protected void setUp() throws Exception
{
configurationService.setProperty(propertyName, null);
configurationService.setProperty(listenedPropertyName, null);
super.setUp();
}
/**
* Generic JUnit tearDown method.
* @throws Exception if anything goes wrong.
*/
protected void tearDown() throws Exception
{
//first remove any remaining listeners
configurationService.removePropertyChangeListener(pListener);
configurationService.removeVetoableChangeListener(rudeVetoListener);
configurationService.removeVetoableChangeListener(gentleVetoListener);
//clear used properties.
configurationService.setProperty(propertyName, null);
configurationService.setProperty(listenedPropertyName, null);
propertyChangeEvent = null;
super.tearDown();
}
/**
* Tests whether setting and getting properties works correctly.
* @throws PropertyVetoException in case someone wrongfully vetoes the
* property change.
*/
public void testSetGetProperty() throws PropertyVetoException
{
String propertyName = "my.test.property";
Object property = new String("my.test.property's value");
configurationService.setProperty(propertyName, property);
Object actualReturn = configurationService.getProperty(propertyName);
assertEquals("a property was not properly stored",
property, actualReturn);
}
/**
* Tests whether setting and getting works alright for properties declared
* as system and whether resolving and retrieving from the system property
* set are done right.
* @throws PropertyVetoException in case someone wrongfully vetoes the
* property change.
*/
public void testSystemPoperties() throws PropertyVetoException
{
//first simply store and retrieve a system property
String propertyName = "my.test.system.property";
Object property = new String("sys.value.1");
configurationService.setProperty(propertyName, property, true);
Object actualReturn = configurationService.getProperty(propertyName);
assertEquals("a sys property was not properly stored",
property, actualReturn);
//now check whether you can also retrieve it from the sys property set.
actualReturn = System.getProperty(propertyName);
assertEquals("a property was not properly stored", property, actualReturn);
//verify that modifying it in the sys property set would affect the
//value in the configuration service
property = new String("second.sys.value");
System.setProperty(propertyName, property.toString());
actualReturn = configurationService.getProperty(propertyName);
assertEquals("a property was not properly stored", property, actualReturn);
//now make sure that modifying it in the configurationService would
//result in the corresponding change in the system property set.
property = new String("third.sys.value");
configurationService.setProperty(propertyName, property.toString());
actualReturn = System.getProperty(propertyName);
assertEquals("a property was not properly stored", property, actualReturn);
}
/**
* Tests whether getString properly returns string values and that it
* correctly handles corner cases.
*/
public void testGetString() throws PropertyVetoException
{
//test a basic scenario
String propertyName = "my.test.property";
Object property = new String("my.test.property's value");
configurationService.setProperty(propertyName, property);
String actualReturn = configurationService.getString(propertyName);
assertEquals("getString failed to retrieve a property",
property.toString(), actualReturn);
//verify that setting a non string object would not mess things up
property = new Integer(7121979);
configurationService.setProperty(propertyName, property);
actualReturn = configurationService.getString(propertyName);
assertEquals("getString failed to retrieve a property",
property.toString(), actualReturn);
//verify that setting a whitespace only string would return null
property = new String("\t\n ");
configurationService.setProperty(propertyName, property);
actualReturn = configurationService.getString(propertyName);
assertNull("getString did not trim a white space only string",
actualReturn);
}
/**
* Tests event notification through multicast listeners (those that are
* registered for the whole configuration and not a single property only).
*/
public void testMulticastEventNotification()
{
propertyChangeEvent = null;
configurationService.addPropertyChangeListener(pListener);
// test the initial set of a property.
try
{
configurationService.setProperty(propertyName, propertyValue);
}
catch (PropertyVetoException ex)
{
fail("A PropertyVetoException came from nowhere. Exc="
+ ex.getMessage());
}
assertNotNull( "No PropertyChangeEvent was delivered upon setProperty",
propertyChangeEvent);
assertNull("oldValue must be null", propertyChangeEvent.getOldValue());
assertEquals( "newValue is not the value we just set!",
propertyValue,
propertyChangeEvent.getNewValue()
);
assertEquals( "propertyName is not the value we just set!",
propertyName,
propertyChangeEvent.getPropertyName()
);
//test setting a new value;
propertyChangeEvent = null;
try
{
configurationService.setProperty(propertyName, propertyNewValue);
}
catch (PropertyVetoException ex)
{
fail("A PropertyVetoException came from nowhere. Exc="
+ ex.getMessage());
}
assertNotNull( "No PropertyChangeEvent was delivered upon setProperty",
propertyChangeEvent);
assertEquals("incorrect oldValue",
propertyValue,
propertyChangeEvent.getOldValue());
assertEquals( "newValue is not the value we just set!",
propertyNewValue,
propertyChangeEvent.getNewValue());
//test remove
propertyChangeEvent = null;
configurationService.removePropertyChangeListener(pListener);
try
{
configurationService.setProperty(propertyName, propertyValue);
}
catch (PropertyVetoException ex)
{
fail("A PropertyVetoException came from nowhere. Exc="
+ ex.getMessage());
}
assertNull( "A PropertyChangeEvent after unregistering a listener.",
propertyChangeEvent);
}
/**
* Test event dispatch to vetoable listeners registered for the whole
* configuration.
*/
public void testMulticastEventNotificationToVetoableListeners()
{
Integer propertyValue = new Integer(19200);
Integer propertyNewValue = new Integer(19201);
propertyChangeEvent = null;
configurationService.addVetoableChangeListener(gentleVetoListener);
// test the initial set of a property.
try
{
configurationService.setProperty(propertyName, propertyValue);
}
catch (PropertyVetoException ex)
{
fail("A PropertyVetoException came from nowhere. Exc="
+ ex.getMessage());
}
assertNotNull( "No PropertyChangeEvent was delivered "
+"to VetoableListeners upon setProperty",
propertyChangeEvent);
assertNull("oldValue must be null", propertyChangeEvent.getOldValue());
assertEquals( "newValue is not the value we just set!",
propertyValue,
propertyChangeEvent.getNewValue());
assertEquals( "propertyName is not the value we just set!",
propertyName,
propertyChangeEvent.getPropertyName());
//test setting a new value;
propertyChangeEvent = null;
try
{
configurationService.setProperty(propertyName, propertyNewValue);
}
catch (PropertyVetoException ex)
{
fail("A PropertyVetoException came from nowhere. Exc="
+ ex.getMessage());
}
assertNotNull( "No PropertyChangeEvent was delivered to veto listener "
+"upon setProperty",
propertyChangeEvent);
assertEquals("incorrect oldValue",
propertyValue,
propertyChangeEvent.getOldValue());
assertEquals( "newValue is not the value we just set!",
propertyNewValue,
propertyChangeEvent.getNewValue());
//test remove
propertyChangeEvent = null;
configurationService.removeVetoableChangeListener(gentleVetoListener);
try
{
configurationService.setProperty(propertyName, propertyValue);
}
catch (PropertyVetoException ex)
{
fail("A PropertyVetoException came from nowhere. Exc="
+ ex.getMessage());
}
assertNull( "A PropertyChangeEvent after unregistering a listener.",
propertyChangeEvent);
}
/**
* Test whether vetoing changes works as it is supposed to.
*/
public void testVetos()
{
propertyChangeEvent = null;
configurationService.addVetoableChangeListener(rudeVetoListener);
configurationService.addPropertyChangeListener(pListener);
PropertyVetoException exception = null;
try
{
configurationService.setProperty(propertyName, propertyValue);
}
catch (PropertyVetoException ex)
{
exception = ex;
}
//make sure the exception was thrown
assertNotNull("A vetoable change event was not dispatched or an "
+"exception was not let through.",
exception);
//make sure no further event dispatching was done
assertNull("A property change event was delivered even after "+
"the property change was vetoed.",
propertyChangeEvent);
//make sure the property did not get modified after vetoing the change
assertNull( "A property was changed even avfter vetoing the change."
,configurationService.getProperty(propertyName));
// now let's make sure that we have the right order of event dispatching.
propertyChangeEvent = null;
configurationService.removeVetoableChangeListener(rudeVetoListener);
VetoableChangeListener vcListener = new VetoableChangeListener(){
public void vetoableChange(PropertyChangeEvent event)
{
assertNull("propertyChangeEvent was not null which means that it has "
+"bean delivered to the propertyChangeListener prior to "
+"being delivered to the vetoable change listener.",
propertyChangeEvent);
}
};
try
{
configurationService.setProperty(propertyName, propertyNewValue);
}
catch (PropertyVetoException ex1)
{
ex1.printStackTrace();
fail("unexpected veto exception. message:" + ex1.getMessage());
}
configurationService.removeVetoableChangeListener(vcListener);
}
/**
* Make sure that adding listeners for a single property name
* only gets us events for that listeners. Removing a listener for a
* specific property should also be proved to no obstruct event delivery to
* the same listener had it been registered for other properties.
*/
public void testSinglePropertyEventNotification()
throws PropertyVetoException
{
Double listenedPropertyValue = new Double(19.2598);
Double listenedPropertyNewValue = new Double(19.29581);
//test basic selective event dispatch
configurationService.addPropertyChangeListener(
listenedPropertyName, pListener);
propertyChangeEvent = null;
configurationService.setProperty(
propertyName, propertyValue);
assertNull("setting prop:"+propertyName + " caused an event notif. to "+
"listener registered for prop:" + listenedPropertyName,
propertyChangeEvent);
configurationService.setProperty(
listenedPropertyName, listenedPropertyValue);
assertNotNull("No event was dispatched upon modification of prop:"
+listenedPropertyName,
propertyChangeEvent );
assertNull("oldValue must be null", propertyChangeEvent.getOldValue());
assertEquals("wrong newValue",
listenedPropertyValue,
propertyChangeEvent.getNewValue());
//test that a generic remove only removes the generic listener
propertyChangeEvent = null;
configurationService.removePropertyChangeListener(pListener);
configurationService.setProperty(
listenedPropertyName, listenedPropertyNewValue);
assertNotNull("No event was dispatched upon modification of prop:"
+listenedPropertyName
+ ". The listener was wrongfully removed.",
propertyChangeEvent );
assertEquals("wrong oldValue",
listenedPropertyValue,
propertyChangeEvent.getOldValue());
assertEquals("wrong newValue",
listenedPropertyNewValue,
propertyChangeEvent.getNewValue());
//make sure that removing the listener properly - really removes it.
propertyChangeEvent = null;
configurationService.removePropertyChangeListener(
listenedPropertyName, pListener);
configurationService.setProperty(listenedPropertyName, propertyValue);
assertNull(
"An event was wrongfully dispatched after removing a listener",
propertyChangeEvent
);
}
/**
* Make sure that adding vetoable listeners for a single property name
* only gets us events for that listeners. Removing a listener for a
* specific property should also be proved to no obstruct event delivery to
* the same listener had it been registered for other properties.
*/
public void testSinglePropertyVetoEventNotification()
throws PropertyVetoException
{
Double listenedPropertyValue = new Double(19.2598);
Double listenedPropertyNewValue = new Double(19.29581);
VetoableChangeListener vetoListener = new VetoableChangeListener()
{
public void vetoableChange(PropertyChangeEvent event)
{
propertyChangeEvent = event;
}
};
//test basic selective event dispatch
configurationService.addVetoableChangeListener(
listenedPropertyName, vetoListener);
propertyChangeEvent = null;
configurationService.setProperty(
propertyName, propertyValue);
assertNull("setting prop:" + propertyName + " caused an event notif. to " +
"listener registered for prop:" + listenedPropertyName,
propertyChangeEvent);
configurationService.setProperty(
listenedPropertyName, listenedPropertyValue);
assertNotNull("No event was dispatched upon modification of prop:"
+ listenedPropertyName,
propertyChangeEvent);
assertNull("oldValue must be null", propertyChangeEvent.getOldValue());
assertEquals("wrong newValue",
listenedPropertyValue,
propertyChangeEvent.getNewValue());
//test that a generic remove only removes the generic listener
propertyChangeEvent = null;
configurationService.removeVetoableChangeListener(vetoListener);
configurationService.setProperty(
listenedPropertyName, listenedPropertyNewValue);
assertNotNull("No event was dispatched upon modification of prop:"
+ listenedPropertyName
+ ". The listener was wrongfully removed.",
propertyChangeEvent);
assertEquals("wrong oldValue",
listenedPropertyValue,
propertyChangeEvent.getOldValue());
assertEquals("wrong newValue",
listenedPropertyNewValue,
propertyChangeEvent.getNewValue());
//make sure that removing the listener properly - really removes it.
propertyChangeEvent = null;
configurationService.removeVetoableChangeListener(
listenedPropertyName, vetoListener);
configurationService.setProperty(
listenedPropertyName, listenedPropertyValue);
assertNull(
"An event was wrongfully dispatched after removing a listener",
propertyChangeEvent
);
//make sure that adding a generic listener, then adding a custom prop
//listener, then removing it - would not remove the generic listener.
propertyChangeEvent = null;
configurationService.addVetoableChangeListener(vetoListener);
configurationService.addVetoableChangeListener(
listenedPropertyName, vetoListener);
configurationService.removeVetoableChangeListener(
listenedPropertyName, vetoListener);
configurationService.setProperty(
listenedPropertyName, listenedPropertyNewValue);
assertNotNull("No event was dispatched upon modification of prop:"
+ listenedPropertyName
+ ". The global listener was wrongfully removed.",
propertyChangeEvent);
assertEquals("wrong propertyName",
listenedPropertyName,
propertyChangeEvent.getPropertyName());
assertEquals("wrong oldValue",
listenedPropertyValue,
propertyChangeEvent.getOldValue());
assertEquals("wrong newValue",
listenedPropertyNewValue,
propertyChangeEvent.getNewValue());
//fail("Testing failures! "
//+"Wanted to know whether cruisecontrol will notice the falure. emil.");
}
}

@ -0,0 +1,322 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.slick.configuration;
import junit.framework.*;
import net.java.sip.communicator.service.configuration.*;
import org.osgi.framework.*;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import net.java.sip.communicator.util.xml.*;
import net.java.sip.communicator.slick.slickless.*;
/**
* Tests ConfiguratioService persistency, which means that it makes the
* ConfigurationService store and load its properties from a file and checks
* whether everything is going well.
*
* @author Emil Ivov
*/
public class TestConfigurationServicePersistency extends TestCase
{
//property1 values
private static final String property1 = "p1";
private static final String property1Value = "p1.value";
private static final String property1Value2 = "p1.value.2";
private static final String property1Path = "parent.";
//property2 values
private static final String systemProperty = "SYSTEM_PROPERTY";
private static final String systemPropertyValue = "I AM the SyS guy";
private static final String systemPropertyValue2 = "sys guy's new face";
private static final String systemPropertyPath = "parent.";
//added_property values
private static final String addedProperty = "ADDED_PROPERTY";
private static final String addedPropertyValue = "added";
private static final String addedPropertyValue2 = "and then re-aded";
private static final String addedPropertyPath = "parent.";
//INNER_PROPERTY values
private static final String innerProperty = "INNER_PROPERTY";
private static final String innerPropertyValue = "I am an insider";
private static final String innerPropertyValue2 = "I am a modified inner";
private static final String innerPropertyPath = "parent.innerprops.";
/** the contents of our properties file.*/
private static final String confFileContent =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<sip-communicator>\n" +
" <parent>" +"\n"+
" <"+property1+" value=\""+property1Value+"\"/>" +"\n"+
" <"+systemProperty
+" value=\""+systemPropertyValue+"\" system=\"true\"/>" +"\n"+
" <innerprops>" +"\n"+
" <"+innerProperty+" value=\""+innerPropertyValue+"\"/>" +"\n"+
" </innerprops>" +"\n"+
" </parent>" +"\n"+
"</sip-communicator>\n";
/** the contents of our second properties file that we use to test reload.*/
private static final String confFileContent2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<sip-communicator>\n" +
" <parent>" +"\n"+
" <"+property1+" value=\""+property1Value2+"\"/>" +"\n"+
" <"+systemProperty
+" value=\""+systemPropertyValue2+"\" system=\"true\"/>" +"\n"+
" <innerprops>" +"\n"+
" <"+innerProperty+" value=\""+innerPropertyValue2+"\"/>" +"\n"+
" </innerprops>" +"\n"+
" </parent>" +"\n"+
"</sip-communicator>\n";
private static final String confFileName = "test.sip-communicator.xml";
/** the configuration file itself (created and deleted for every test)*/
private File confFile = null;
/**
* The ConfigurationService that we will be testing.
*/
private ConfigurationService configurationService = null;
/**
* Generic JUnit Constructor.
* @param name the name of the test
*/
public TestConfigurationServicePersistency(String name)
{
super(name);
BundleContext context = ConfigurationServiceLick.bc;
ServiceReference ref = context.getServiceReference(
ConfigurationService.class.getName());
configurationService = (ConfigurationService)context.getService(ref);
}
/**
* Generic JUnit setUp method.
* @throws Exception if anything goes wrong.
*/
protected void setUp() throws Exception
{
confFile = new File(confFileName);
System.setProperty("net.java.sip.communicator.PROPERTIES_FILE_NAME",
confFileName);
confFile.createNewFile();
FileOutputStream out = new FileOutputStream(confFile);
out.write(confFileContent.getBytes());
out.flush();
out.close();
configurationService.reloadConfiguration();
super.setUp();
}
/**
* Generic JUnit tearDown method.
* @throws Exception if anything goes wrong.
*/
protected void tearDown() throws Exception
{
//delete the temp conf file
confFile.delete();
//reset the fileNameProperty
System.setProperty("net.java.sip.communicator.PROPERTIES_FILE_NAME",
"sip-communicator.xml");
super.tearDown();
}
/**
* Tests whether the load method has properly loaded our conf file during
* setup.
*/
public void testLoadConfiguration()
{
Object returnedValueObj =
configurationService.getProperty(property1Path
+ property1);
assertNotNull("configuration not properly loaded", returnedValueObj);
assertTrue("returned prop is not a String",
returnedValueObj instanceof String);
String returnedValue = returnedValueObj.toString();
assertEquals("configuration not properly loaded",
property1Value, returnedValue);
returnedValueObj =
configurationService.getProperty(systemPropertyPath
+ systemProperty);
assertNotNull("configuration not properly loaded", returnedValueObj);
assertTrue("returned prop is not a String",
returnedValueObj instanceof String);
//check whether this property was resolved in System.properties
returnedValue = System.getProperty(systemPropertyPath + systemProperty);
assertNotNull("A system property was not resolved", returnedValue);
assertEquals("A system property was not resolved",
systemPropertyValue, returnedValue);
returnedValue = returnedValueObj.toString();
assertEquals("configuration not properly loaded",
systemPropertyValue, returnedValue);
//check whether inner properties are properly loaded
returnedValueObj =
configurationService.getProperty(innerPropertyPath
+ innerProperty).toString();
assertNotNull("configuration not properly loaded", returnedValueObj);
assertTrue("returned prop is not a String",
returnedValueObj instanceof String);
returnedValue = returnedValueObj.toString();
assertEquals("configuration not properly loaded",
innerPropertyValue, returnedValue);
}
/**
* Tests whether a configuration is properly reloaded (i.e. values of
* the properties are updated to match those present in the file, and
* any additional properties added since the previous load are clreared).
*/
public void testReLoadConfiguration() throws Exception
{
//set a new property so that we could see whether its deleted after
//the file contents is reloaded.
configurationService.setProperty(addedPropertyPath + addedProperty,
addedPropertyValue);
//write the new file
FileOutputStream out = new FileOutputStream(confFile);
out.write(confFileContent2.getBytes());
out.flush();
out.close();
configurationService.reloadConfiguration();
//check whether normal properties are properly reloaded
Object returnedValueObj =
configurationService.getProperty(property1Path
+ property1);
assertNotNull("configuration not properly loaded", returnedValueObj);
assertTrue("returned prop is not a String",
returnedValueObj instanceof String);
String returnedValue = returnedValueObj.toString();
assertEquals("configuration not properly reloaded",
property1Value2, returnedValue);
//check whether systemproperties are properly reresolved
returnedValueObj =
configurationService.getProperty(systemPropertyPath
+ systemProperty);
assertNotNull("configuration not properly reloaded", returnedValueObj);
assertTrue("returned prop is not a String",
returnedValueObj instanceof String);
returnedValue = returnedValueObj.toString();
assertEquals("configuration not properly reloaded",
systemPropertyValue2, returnedValue);
//make sure that the property was re-resolved in System.properties
returnedValue = System.getProperty(systemPropertyPath + systemProperty);
assertNotNull("A system property was not resolved", returnedValue);
assertEquals("A system property was not resolved",
systemPropertyValue2, returnedValue);
//verify that the inner property is also reloaded
returnedValueObj =
configurationService.getProperty(innerPropertyPath
+ innerProperty);
assertNotNull("configuration not properly reloaded", returnedValueObj);
assertTrue("returned prop is not a String",
returnedValueObj instanceof String);
returnedValue = returnedValueObj.toString();
assertEquals("configuration not properly reloaded",
innerPropertyValue2, returnedValue);
//make sure the property we added in the beginning is not there anymore.
returnedValueObj =
configurationService.getProperty(addedPropertyPath
+ addedProperty);
assertNull("reload didn't remove newly added properties",
returnedValueObj);
}
/**
* Test whether a configuration is properly stored in the configuration
* file.
*/
public void testStoreConfiguration() throws Exception
{
//add a new property that will have to be added to the xml conf file.
configurationService.setProperty(addedPropertyPath + addedProperty,
addedPropertyValue2);
//then give new values to existing properties
configurationService.setProperty(property1Path + property1,
property1Value2);
configurationService.setProperty(systemPropertyPath + systemProperty,
systemPropertyValue2);
configurationService.setProperty(innerPropertyPath + innerProperty,
innerPropertyValue2);
configurationService.storeConfiguration();
//reload the conf
configurationService.reloadConfiguration();
//Now reload the file and make sure it containts the updated values.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(confFile);
Node root = document.getFirstChild();
Node parent = XMLUtils.findChild( (Element) root, "parent");
Node property1Node = XMLUtils.findChild( (Element) parent, property1);
Node systemPropertyNode =
XMLUtils.findChild( (Element) parent, systemProperty);
Node addedPropertyNode =
XMLUtils.findChild( (Element) parent, addedProperty);
Node innerpropNode =
XMLUtils.findChild( (Element) parent, "innerprops");
Node innerPropertyNode =
XMLUtils.findChild((Element)innerpropNode, innerProperty);
String xmlProp1Value = XMLUtils.getAttribute(property1Node, "value");
String xmlProp2Value =
XMLUtils.getAttribute(systemPropertyNode, "value");
String xmlAddedPropertyValue =
XMLUtils.getAttribute(addedPropertyNode, "value");
String xmlInnerPropertyValue =
XMLUtils.getAttribute(innerPropertyNode, "value");
assertEquals("property1 was incorrectly stored",
property1Value2, xmlProp1Value);
assertEquals("System property was incorrectly stored",
systemPropertyValue2, xmlProp2Value);
assertEquals("The added property was incorrectly stored",
addedPropertyValue2, xmlAddedPropertyValue);
assertEquals("The inner property was incorrectly stored",
innerPropertyValue2, xmlInnerPropertyValue);
}
}

@ -0,0 +1,18 @@
Bundle-Activator: net.java.sip.communicator.slick.configuration.ConfigurationServiceLick
Bundle-Name: Configuration Service Implementation Compatibility Kit
Bundle-Description: A Service Implementation Compatibility Kit for the Configuration Service
Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
Import-Package: net.java.sip.communicator.service.configuration,
net.java.sip.communicator.service.configuration.event,
junit.framework,
org.osgi.framework,
org.w3c.dom,
javax.xml.parsers,
net.java.sip.communicator.util,
net.java.sip.communicator.util.xml,
javax.xml.transform,
javax.xml.transform.dom,
javax.xml.transform.stream,
org.apache.xml.serializer,
Export-Package: net.java.sip.communicator.slick.configuration,

@ -0,0 +1,58 @@
package net.java.sip.communicator.slick.history;
import java.util.Hashtable;
import junit.framework.TestSuite;
import net.java.sip.communicator.util.Logger;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
/**
* This class launches the bundle of which test the history bundle.
* this bundle is a set of (j)unit tests. It should be launched by the
* cruisecontrol module.
*
* @author Alexander Pelov
*/
public class HistoryServiceLick
extends TestSuite
implements BundleActivator
{
private static Logger logger = Logger.getLogger(HistoryServiceLick.class);
protected static BundleContext bc = null;
/**
* Start the History Sevice Implementation Compatibility Kit.
*
* @param bundleContext BundleContext
* @throws Exception
*/
public void start(BundleContext bundleContext) throws Exception
{
HistoryServiceLick.bc = bundleContext;
setName("HistoryServiceLick");
Hashtable properties = new Hashtable();
properties.put("service.pid", getName());
addTestSuite(TestHistoryService.class);
bundleContext.registerService(getClass().getName(), this, properties);
logger.debug("Successfully registered " + getClass().getName());
}
/**
* stop
*
* @param bundlecontext BundleContext
* @throws Exception
*/
public void stop(BundleContext bundlecontext) throws Exception
{
}
}

@ -0,0 +1,140 @@
package net.java.sip.communicator.slick.history;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import junit.framework.TestCase;
import net.java.sip.communicator.service.history.History;
import net.java.sip.communicator.service.history.HistoryID;
import net.java.sip.communicator.service.history.HistoryReader;
import net.java.sip.communicator.service.history.HistoryService;
import net.java.sip.communicator.service.history.HistoryWriter;
import net.java.sip.communicator.service.history.QueryResultSet;
import net.java.sip.communicator.service.history.records.HistoryRecord;
import net.java.sip.communicator.service.history.records.HistoryRecordStructure;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
public class TestHistoryService extends TestCase {
private static HistoryRecordStructure recordStructure =
new HistoryRecordStructure(new String[] {"name", "age", "sex"});
/**
* The ConfigurationService that we will be testing.
*/
private HistoryService historyService = null;
private ServiceReference historyServiceRef = null;
private History history = null;
private Random random = new Random();
public TestHistoryService(String name) throws Exception {
super(name);
}
protected void setUp() throws Exception {
BundleContext context = HistoryServiceLick.bc;
historyServiceRef = context.getServiceReference(
HistoryService.class.getName());
this.historyService = (HistoryService)context.getService(historyServiceRef);
HistoryID testID = HistoryID.createFromRawID(new String[] {"test",
"alltests"});
if(!this.historyService.isHistoryExisting(testID)) {
this.history = this.historyService.createHistory(testID,
recordStructure);
} else {
this.history = this.historyService.getHistory(testID);
}
}
protected void tearDown() throws Exception {
BundleContext context = HistoryServiceLick.bc;
context.ungetService(this.historyServiceRef);
this.history = null;
this.historyService = null;
this.historyServiceRef = null;
}
public void testCreateDB() {
ArrayList al = new ArrayList();
Iterator i = this.historyService.getExistingIDs();
while(i.hasNext()) {
HistoryID id = (HistoryID)i.next();
String[] components = id.getID();
if(components.length == 2 && "test".equals(components[0])) {
al.add(components[1]);
}
}
int count = al.size();
boolean unique = false;
String lastComp = null;
while(!unique) {
lastComp = Integer.toHexString(random.nextInt());
for(int j = 0; j < count; j++) {
if(lastComp.equals(al.get(j))) {
continue;
}
}
unique = true;
}
HistoryID id = HistoryID.createFromRawID(
new String[] {"test", lastComp});
try {
this.historyService.createHistory(id, recordStructure);
} catch (Exception e) {
fail("Could not create database with id " + id + " with error " + e);
}
}
public void testWriteRecords() {
HistoryWriter writer = this.history.getWriter();
try {
for(int i = 0; i < 202; i++) {
writer.addRecord(new String[] {"name"+i, ""+random.nextInt(),
i%2==0 ? "m" : "f"});
}
} catch(Exception e) {
fail("Could not write records. Reason: " + e);
}
}
public void testReadRecords() {
HistoryReader reader = this.history.getReader();
QueryResultSet result = reader.findByKeyword("name2");
assertTrue(result.hasNext());
while(result.hasNext()) {
HistoryRecord record = result.nextRecord();
String[] vals = record.getPropertyValues();
try {
int n = Integer.parseInt(vals[0].substring(4));
assertEquals(3, vals.length);
assertEquals(n%2==0 ? "m" : "f", vals[2]);
} catch(Exception e) {
fail("Bad data! Expected nameXXXX, where XXXX is " +
"an integer, but found: " + vals[0]);
}
}
}
}

@ -0,0 +1,22 @@
Bundle-Activator: net.java.sip.communicator.slick.history.HistoryServiceLick
Bundle-Name: History Service Implementation Compatibility Kit
Bundle-Description: A Service Implementation Compatibility Kit for the History Service
Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
Import-Package: junit.framework,
net.java.sip.communicator.slick.history,
net.java.sip.communicator.service.history.records,
net.java.sip.communicator.service.history.query,
net.java.sip.communicator.service.history,
net.java.sip.communicator.service.configuration,
net.java.sip.communicator.service.protocol,
org.osgi.framework,
org.w3c.dom,
javax.xml.parsers,
net.java.sip.communicator.util,
net.java.sip.communicator.util.xml,
javax.xml.transform,
javax.xml.transform.dom,
javax.xml.transform.stream,
org.apache.xml.serializer,
Export-Package: net.java.sip.communicator.slick.history,

@ -0,0 +1,68 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.slick.media;
import java.util.Hashtable;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import net.java.sip.communicator.service.media.MediaService;
import net.java.sip.communicator.util.Logger;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
/**
* This class launches the bundle which test the media bundle.
* this bundle is a set of (j)unit tests. It should be launched by the
* cruisecontrol module.
*
* @author Martin Andre
*/
public class MediaServiceLick
extends TestSuite
implements BundleActivator
{
private Logger logger = Logger.getLogger(getClass().getName());
protected static MediaService mediaService = null;
protected static BundleContext bc = null;
public static TestCase tcase = new TestCase(){};
/**
* Start the Media Service Implementation Compatibility Kit.
*
* @param bundleContext BundleContext
* @throws Exception
*/
public void start(BundleContext bundleContext) throws Exception
{
MediaServiceLick.bc = bundleContext;
setName("MediaServiceLick");
Hashtable properties = new Hashtable();
properties.put("service.pid", getName());
addTestSuite(TestMediaService.class);
bundleContext.registerService(getClass().getName(), this, properties);
logger.debug("Successfully registered " + getClass().getName());
}
/**
* stop
*
* @param bundlecontext BundleContext
* @throws Exception
*/
public void stop(BundleContext bundlecontext) throws Exception
{
}
}

@ -0,0 +1,133 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.slick.media;
import junit.framework.*;
import org.osgi.framework.*;
import net.java.sip.communicator.service.media.*;
import net.java.sip.communicator.service.media.event.MediaEvent;
import net.java.sip.communicator.service.media.event.MediaListener;
/**
* Tests basic MediaService behaviour.
*
* @author Martin Andre
*/
public class TestMediaService extends TestCase
{
/**
* The MediaService that we will be testing.
*/
private MediaService mediaService = null;
/**
* The MediaEvent that our test listeners will capture for testing.
* Make sure we null that upon tear down
*/
private MediaEvent mediaEvent = null;
/**
* A Media listener impl.
*/
private MediaListener mediaListener = new MediaListener()
{
public void receivedMediaStream(MediaEvent evt) {
// TODO Auto-generated method stub
mediaEvent = evt;
}
public void mediaServiceStatusChanged() {
// TODO Auto-generated method stub
}
};
/**
* Generic JUnit Constructor.
* @param name the name of the test
*/
public TestMediaService(String name)
{
super(name);
BundleContext context = MediaServiceLick.bc;
ServiceReference ref = context.getServiceReference(
MediaService.class.getName());
this.mediaService = (MediaService)context.getService(ref);
}
/**
* Generic JUnit setUp method.
* @throws Exception if anything goes wrong.
*/
protected void setUp() throws Exception
{
super.setUp();
}
/**
* Generic JUnit tearDown method.
* @throws Exception if anything goes wrong.
*/
protected void tearDown() throws Exception
{
//first remove any remaining listeners
mediaService.removeMediaListener(mediaListener);
mediaEvent = null;
super.tearDown();
}
/**
* Test initialisation check.
*/
public void testIsInitialized()
{
// Initial check
assertFalse(mediaService.isInitialized());
// Initialize service
mediaService.initialize();
assertTrue(mediaService.isInitialized());
// XXX Should also check that Media service is really initialized
// Shutdown service
mediaService.shutdown();
assertFalse(mediaService.isInitialized());
}
/**
* Tests media event notification through listeners.
*/
public void testMediaEventNotification()
{
mediaEvent = null;
mediaService.addMediaListener(mediaListener);
// test the initial set of a property.
mediaService.initialize();
assertNotNull("A MediaEvent with a registered listener", mediaEvent);
mediaService.shutdown();
//test remove
mediaEvent = null;
mediaService.removeMediaListener(mediaListener);
mediaService.initialize();
assertNull("A MediaEvent after unregistering a listener.",
mediaEvent);
mediaService.shutdown();
}
}

@ -0,0 +1,16 @@
Bundle-Activator: net.java.sip.communicator.slick.media.MediaServiceLick
Bundle-Name: Media Service Implementation Compatibility Kit
Bundle-Description: A Service Implementation Compatibility Kit for the Media Service
Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
Import-Package: junit.framework,
org.osgi.framework,
net.java.sip.communicator.service.media,
net.java.sip.communicator.service.media.event,
net.java.sip.communicator.service.configuration,
net.java.sip.communicator.service.configuration.event,
net.java.sip.communicator.util,
javax.media,
javax.media.format,
javax.media.protocol,
Export-Package: net.java.sip.communicator.slick.media,

@ -0,0 +1,60 @@
package net.java.sip.communicator.slick.netaddr;
import org.osgi.framework.*;
import junit.framework.*;
import junit.textui.*;
import net.java.sip.communicator.service.netaddr.*;
import net.java.sip.communicator.slick.configuration.TestConfigurationService;
import java.util.*;
import net.java.sip.communicator.util.*;
/**
* This class launche the bundle of which test the NetworkManagerBundle
* this bundle is a set of (j)unit tests. It aim to be launch by the
* cruisecontrol module to verify tha an implementation of the
* NetworkAddressManagerService interface is good.
*
* @author Emil Ivov
* @author Pierre Floury
*/
public class NetworkAddressManagerServiceLick
extends TestSuite
implements BundleActivator
{
private Logger logger = Logger.getLogger(getClass().getName());
protected static NetworkAddressManagerService networkAddressManagerService
= null;
protected static BundleContext bc = null;
public static TestCase tcase = new TestCase(){};
/**
* Start the Network Address Manager Sevice Implementation Compatibility Kit.
* @param bundleContext BundleContext
* @throws Exception
*/
public void start(BundleContext bundleContext) throws Exception
{
this.bc = bundleContext;
setName("NetworkAddressManagerServiceLick");
Hashtable properties = new Hashtable();
properties.put("service.pid", getName());
// addTestSuite(TestNetworkAddressManagerService.class);
// addTestSuite(TestAddressPool.class);
bundleContext.registerService(getClass().getName(), this, properties);
logger.debug("Successfully registered " + getClass().getName());
}
/**
* stop
*
* @param bundlecontext BundleContext
* @throws Exception
*/
public void stop(BundleContext bundlecontext) throws Exception
{
}
}

@ -0,0 +1,621 @@
package net.java.sip.communicator.slick.netaddr;
import junit.framework.*;
import net.java.sip.communicator.service.netaddr.*;
import net.java.sip.communicator.service.configuration.*;
import org.osgi.framework.*;
import java.net.*;
import java.net.NetworkInterface;
import java.util.*;
import net.java.sip.communicator.util.*;
import net.java.stun4j.StunAddress;
import net.java.stun4j.client.SimpleAddressDetector;
import net.java.stun4j.StunAddress;
/**
* Tests basic Network Address Manager Service behaviour.
*
* @author Emil Ivov
* @author Pierre Floury
*
*/
public class TestNetworkAddressManagerService extends TestCase {
/**
* The NetworkAddressManagerService that we will be testing.
*/
private NetworkAddressManagerService networkAddressManagerService = null;
private Logger logger = Logger.getLogger(getClass().getName());
private static final String PROP_STUN_SERVER_ADDR =
"net.java.sip.communicator.STUN_SERVER_ADDRESS";
private static final String PROP_STUN_SERVER_PORT =
"net.java.sip.communicator.STUN_SERVER_PORT";
private static final String PROP_PREFERRED_NET_IFACE =
"net.java.sip.communicator.PREFERRED_NETWORK_INTERFACE";
private static final String PROP_PREFERRED_NET_ADDR =
"net.java.sip.communicator.PREFERRED_NETWORK_ADDRESS";
/**
* The ConfigurationService that we will be using.
*/
private ConfigurationService configurationService = null;
/**
* Constructor.
* get a reference to the configuration service
*
* @param name the name of the test
*/
public TestNetworkAddressManagerService(String name) {
super(name);
}
/**
* Generic JUnit setUp method. That's where we get the configuration and
* net address manager services
* service.
*
* @throws Exception if anything goes wrong.
*/
protected void setUp() throws Exception {
super.setUp();
BundleContext context = NetworkAddressManagerServiceLick.bc;
// get the configuration service
ServiceReference confRef = context
.getServiceReference(ConfigurationService.class.getName());
configurationService = (ConfigurationService) context
.getService(confRef);
// get the netaddr service
ServiceReference netRef = context.getServiceReference(
NetworkAddressManagerService.class.getName());
networkAddressManagerService = (NetworkAddressManagerService)
context.getService(netRef);
}
/**
* Generic JUnit tearDown method.
*
* @throws Exception if anything goes wrong.
*/
protected void tearDown() throws Exception {
super.tearDown();
}
private static boolean isLocalInterfaceAddress(InetAddress address)
{
try {
Enumeration intfs = NetworkInterface.getNetworkInterfaces();
while (intfs.hasMoreElements()) {
NetworkInterface intf = (NetworkInterface) intfs.nextElement();
Enumeration addrs = intf.getInetAddresses();
while (addrs.hasMoreElements()) {
try {
InetAddress addr = (InetAddress) addrs.nextElement();
if(addr.equals(address))
return true;
} catch (Exception e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private static boolean isLocalInterfaceAddressIPv4(InetAddress address)
{
if(address instanceof Inet4Address)
return isLocalInterfaceAddress(address);
return false;
}
private static boolean isLocalInterfaceAddressIPv6(InetAddress address)
{
if(address instanceof Inet6Address)
return isLocalInterfaceAddress(address);
return false;
}
public void testDummyTest()
{
//we gotta have at least one test otherwise we have an error
}
/**
* This test will specify all local address one by one as "prefered address"
* and test the returned address.
*
* @throws java.lang.Exception if anything goes wrong.
*/
/**
public void testPreferredNetAddressProperty() throws Exception
{
initProperties();
//set the original properties
String valuePropertyStunName="";
String propertyStunPort="";
//disable stun for this test. we are onlytesting simple logics here.
configurationService.setProperty(PROP_STUN_SERVER_ADDR,"");
configurationService.setProperty(PROP_STUN_SERVER_PORT,"");
//restart the netaddress manager so the it takes the new settings into
//account
networkAddressManagerService.stop();
networkAddressManagerService.start();
Enumeration intfs = NetworkInterface.getNetworkInterfaces();
while (intfs.hasMoreElements())
{
NetworkInterface iface = (NetworkInterface) intfs.nextElement();
Enumeration addrs = iface.getInetAddresses();
while (addrs.hasMoreElements())
{
InetAddress addr = (InetAddress) addrs.nextElement();
//set the current address as the preferred one.
configurationService.setProperty(PROP_PREFERRED_NET_IFACE,
iface.getName());
configurationService.setProperty(PROP_PREFERRED_NET_ADDR,
addr.toString());
InetAddress localHost =
networkAddressManagerService.getLocalHost();
if( isRoutable(addr) )
{
//if the address we set as prefered was routable then
//the net address manager should have returned it.
assertEquals(addr, localHost);
}
else
{
assertFalse(networkAddressManagerService.
getLocalHost().isLoopbackAddress());
}
}
}
}
public void testBadIpAddressNoIPversionSpecified() throws Exception
{
initProperties();
// set th original properties
//Integer valuePropertyPreferedIPVersion;
String valuePropertyStunName="stun01.sipphone.com";
Integer valuePropertyStunPort=new Integer(3478);
String valuePropertyNetworkAddress="192.169.1.1";
//String propertyNetworkInterface=""
//valuePropertyPreferedIPVersion = new Integer(4);
configurationService.setProperty(PROP_STUN_SERVER_ADDR,
valuePropertyStunName);
configurationService.setProperty(PROP_STUN_SERVER_PORT,
valuePropertyStunPort);
configurationService.setProperty(PROP_PREFERRED_NET_ADDR,
valuePropertyNetworkAddress);
InetAddress addr = networkAddressManagerService.getLocalHost();
assertTrue(isLocalInterfaceAddressIPv4(addr)
|| isLinkLocalIPv4Address(addr)
|| isRoutable(addr)
|| getStunAddress().equals(addr));
}
public void testBadIpAddressIPv4Specified() throws Exception
{
initProperties();
// set th original properties
//Integer valuePropertyPreferedIPVersion;
String valuePropertyStunName="stun01.sipphone.com";
Integer valuePropertyStunPort=new Integer(3478);
String valuePropertyNetworkAddress="2001:660:4701:1001:800:1cff:fed1:51";
Integer valuePropertyPreferedIPVersion=new Integer(4);
//String propertyNetworkInterface=""
//valuePropertyPreferedIPVersion = new Integer(4);
configurationService.setProperty(PROP_STUN_SERVER_ADDR,
valuePropertyStunName);
configurationService.setProperty(PROP_STUN_SERVER_PORT,
valuePropertyStunPort);
configurationService.setProperty(PROP_PREFERRED_NET_ADDR,
valuePropertyNetworkAddress);
InetAddress addr = networkAddressManagerService.getLocalHost();
assertTrue(addr instanceof Inet4Address);
}
public void testBadStun() throws Exception
{
initProperties();
// set th original properties
//Integer valuePropertyPreferedIPVersion;
String valuePropertyStunName="stun01.sipphone.com";
Integer valuePropertyStunPort=new Integer(3478);
String valuePropertyNetworkAddress="192.169.1.1";
//String propertyNetworkInterface=""
//valuePropertyPreferedIPVersion = new Integer(4);
configurationService.setProperty(PROP_STUN_SERVER_ADDR,
valuePropertyStunName);
configurationService.setProperty(PROP_STUN_SERVER_PORT,
valuePropertyStunPort);
configurationService.setProperty(PROP_PREFERRED_NET_ADDR,
valuePropertyNetworkAddress);
InetAddress addr = networkAddressManagerService.getLocalHost();
assertTrue(isLocalInterfaceAddressIPv4(addr)
|| isLinkLocalIPv4Address(addr)
|| isRoutable(addr));
}
*/
/**
* Set the configuration to IPv4 pref if the network is not behind a nat
* if not it does nothing
* and watch if the result of "NetworkAddressManagerService.getlocalhost()
* is a valid (public) IPv4 address
*/
/*public void testIPv4Stack()
{
if(nat==true)
return;
// set properties
Boolean propertyIpV6Pref= new Boolean(false);
Boolean propertyIpV4Stack = new Boolean(true);
String propertieStunValue="stun01.sipphone.com";
Integer propertieStunPort=new Integer(3478);
Boolean natBoolean = new Boolean(nat);
try
{
configurationService.setProperty(propertyIpV4Stack, propertyIpV4Stack);
configurationService.setProperty(propertyStunName,propertieStunValue );
configurationService.setProperty(propertyStunPort,propertieStunPort );
configurationService.setProperty(propertyV6,propertyIpV6Pref );
configurationService.setProperty(propertyNat, natBoolean);
}
catch (Exception e) {}
try {
// get the locahost grom NetworkAddressManager Service
InetAddress serviceAdress =
networkAddressManagerService.getLocalHost();
// test must crash if the localHost is an IPv6 Address
if(serviceAdress instanceof Inet4Address)
assertTrue(foundInetAddr( serviceAdress,
propertyIpV6Pref.booleanValue()));
else
assertTrue(false);
}
catch (Exception e) {}
}*/
/**
* Set the configuration to IPv4 pref if the network is behind a nat
* if not it does nothing
* and watch if the result of "NetworkAddressManagerService.getlocalhost()
* is a valid (public) IPv4 address
*/
/*public void testIPv4StackWithNat()
{
if(nat==false)
return;
// set properties
Boolean propertyIpV6Pref= new Boolean(false);
Boolean propertyIpV4Stack = new Boolean(true);
String propertieStunValue="stun01.sipphone.com";
Integer propertieStunPort=new Integer(3478);
Boolean natBoolean = new Boolean(nat);
try
{
configurationService.setProperty(propertIpV4Stack, propertyIpV4Stack);
configurationService.setProperty(propertyStunName,propertieStunValue );
configurationService.setProperty(propertyStunPort,propertieStunPort );
configurationService.setProperty(propertyV6,propertyIpV6Pref );
configurationService.setProperty(propertyNat, natBoolean);
}
catch (Exception e) {}
try {
// get the locahost grom NetworkAddressManager Service
InetAddress serviceAdress =
networkAddressManagerService.getLocalHost();
// test must crash if the localHost is an IPv6 Address
if(serviceAdress instanceof Inet4Address)
assertTrue(!isLinkLocalIPv4Address(serviceAdress));
else
assertTrue(false);
}
catch (Exception e) {}
}*/
/**
* Set the configuration to IPv6 pref
* and watch if the result of "NetworkAddressManagerService.getlocalhost()
* is a valid IPv6 address
*/
/*public void testIPv6()
{
if(nat==true)
return;
// set properties
Boolean propertyIpV6Pref= new Boolean(true);
Boolean propertyIpV4Stack = new Boolean(false);
String propertieStunValue="stun01.sipphone.com";
Integer propertieStunPort=new Integer(3478);
Boolean natBoolean = new Boolean(nat);
try
{
configurationService.setProperty(propertIpV4Stack, propertyIpV4Stack);
configurationService.setProperty(propertyStunName,propertieStunValue );
configurationService.setProperty(propertyStunPort,propertieStunPort );
configurationService.setProperty(propertyV6,propertyIpV6Pref );
configurationService.setProperty(propertyNat, natBoolean);
}
catch (Exception e) {}
try {
// get localhost address from the NetworkAddressManager bundle
InetAddress serviceAdress =
networkAddressManagerService.getLocalHost();
if(serviceAdress instanceof Inet6Address)
assertTrue(foundInetAddr(serviceAdress,
propertyIpV6Pref.booleanValue()));
else
assertTrue(false);
}
catch (Exception e) { }
}*/
/**
* Set the configuration to IPv6 pref
* and watch if the result of "NetworkAddressManagerService.getlocalhost()
* is a valid IPv6 address
*/
/*public void testIPv6Nat()
{
if(nat==false)
return;
// set properties
Boolean propertyIpV6Pref= new Boolean(true);
Boolean propertyIpV4Stack = new Boolean(false);
String propertieStunValue="stun01.sipphone.com";
Integer propertieStunPort=new Integer(3478);
Boolean natBoolean = new Boolean(nat);
try
{
configurationService.setProperty(propertIpV4Stack, propertyIpV4Stack);
configurationService.setProperty(propertyStunName,propertieStunValue );
configurationService.setProperty(propertyStunPort,propertieStunPort );
configurationService.setProperty(propertyV6,propertyIpV6Pref );
configurationService.setProperty(propertyNat, natBoolean);
}
catch (Exception e) {}
try
{
// get localhost address from the NetworkAddressManager bundle
InetAddress serviceAdress =
networkAddressManagerService.getLocalHost();
if(serviceAdress instanceof Inet6Address)
assertTrue( isRoutable(serviceAdress));
else
assertTrue(false);
}
catch (Exception e) {}
}*/
/**
* verify if the address returned by the service is valid by listing local
* interfaces and compare them to the address retruned
*
* @param serviceAdress : address to check
* @param ipv6version : if true verifie if this address is an ipv6 belong
* to the local interface. if false, et do the same thing for
* IPv4 Addresses
* @return : true if it is an ipv4 address and if this addres belong to the
* local interface
*/
/*boolean foundInetAddr(InetAddress serviceAdress, boolean ipv6version)
{
try {
Enumeration intfs = NetworkInterface.getNetworkInterfaces();
while (intfs.hasMoreElements()) {
NetworkInterface intf = (NetworkInterface) intfs.nextElement();
Enumeration addrs = intf.getInetAddresses();
while (addrs.hasMoreElements()) {
try {
InetAddress addr = (InetAddress) addrs.nextElement();
if (!addr.isLoopbackAddress()
&& serviceAdress.equals(addr)
&& ((!ipv6version && addr.getClass().equals(Inet4Address.class)
||
(ipv6version && addr.getClass().equals(Inet6Address.class)))))
return true;
} catch (Exception e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}*/
/**
* test the getPublicAddressFor methode,
* but I don't know how test that
* it is still TODO
*
*/
/*public void testgetPublicAddressFor()
{
// set properties
Boolean propertyIpV6Pref= new Boolean(true);
Boolean propertyIpV4Stack = new Boolean(false);
String propertieStunValue="stun01.sipphone.com";
Integer propertieStunPort=new Integer(3478);
Boolean natBoolean = new Boolean(nat);
try
{
configurationService.setProperty(propertIpV4Stack, propertyIpV4Stack);
configurationService.setProperty(propertyStunName,propertieStunValue );
configurationService.setProperty(propertyStunPort,propertieStunPort );
configurationService.setProperty(propertyV6,propertyIpV6Pref );
configurationService.setProperty(propertyNat, natBoolean);
}
catch (Exception ex) {}
InetAddress serviceAddress = (networkAddressManagerService.
getPublicAddressFor(1024)).getAddress();
assertTrue(foundInetAddr(serviceAddress, propertyIpV6Pref.booleanValue()));
propertyIpV4Stack = new Boolean(true);
propertyIpV6Pref = new Boolean(false);
try
{
configurationService.setProperty(propertIpV4Stack, propertyIpV4Stack);
configurationService.setProperty(propertyV6,propertyIpV6Pref );
}
catch (Exception e) {}
serviceAddress = (networkAddressManagerService.
getPublicAddressFor(1024)).getAddress();
assertTrue(foundInetAddr(serviceAddress, propertyIpV6Pref.booleanValue()));
}*/
/**
* Determines whether the address is an IPv4 link local address. IPv4 link
* local addresses are those in the following networks:
*
* 10.0.0.0 to 10.255.255.255
* 172.16.0.0 to 172.31.255.255
* 192.168.0.0 to 192.168.255.255
*
* @param add the address to inspect
* @return true if add is a link local ipv4 address and false if not.
*/
private static boolean isLinkLocalIPv4Address(InetAddress add)
{
if(add instanceof Inet4Address)
{
byte address[] = add.getAddress();
if ( (address[0] & 0xFF) == 10)
return true;
if ( (address[0] & 0xFF) == 172
&& (address[1] & 0xFF) >= 16 && address[1] <= 31)
return true;
if ( (address[0] & 0xFF) == 192
&& (address[1] & 0xFF) == 168)
return true;
return false;
}
return false;
}
/**
* Determines whether the address could be used in a VoIP session. Attention,
* routable address as determined by this method are not only globally routable
* addresses in the general sense of the term. Link local addresses such as
* 192.168.x.x or fe80::xxxx are also considered usable.
* @param address the address to test.
* @return true if the address could be used in a VoIP session.
*/
private static boolean isRoutable(InetAddress address)
{
if(address instanceof Inet6Address)
{
return !address.isLoopbackAddress()
&& !address.isLinkLocalAddress();
}
else
{
return (!address.isLoopbackAddress())
&& (!isWindowsAutoConfiguredIPv4Address(address));
}
}
/**
* Determines whether the address is the result of windows auto configuration.
* (i.e. One that is in the 169.254.0.0 network)
* @param add the address to inspect
* @return true if the address is autoconfigured by windows, false otherwise.
*/
private static boolean isWindowsAutoConfiguredIPv4Address(InetAddress add)
{
return (add.getAddress()[0] & 0xFF) == 169
&& (add.getAddress()[1] & 0xFF) == 254;
}
/**
* return an ipv4 address get by stun
* @return an inet address
*/
private InetAddress getStunAddress()
{
try
{
String valuePropertyStunName="stun01.sipphone.com";
Integer propertieStunPort=new Integer(3478);
SimpleAddressDetector detector = null;
detector =new SimpleAddressDetector(new StunAddress(
valuePropertyStunName,propertieStunPort.intValue()));
detector.start();
InetAddress mappedAddress =
detector.getMappingFor(1024).getSocketAddress().getAddress();
return mappedAddress;
}
catch(Exception ex)
{
logger.error("Can't get Stun Address : " + ex );
}
return null;
}
private void initProperties()
{
try
{
configurationService.setProperty( PROP_STUN_SERVER_ADDR , null);
configurationService.setProperty( PROP_STUN_SERVER_PORT , null);
configurationService.setProperty( PROP_PREFERRED_NET_IFACE, null);
configurationService.setProperty( PROP_PREFERRED_NET_ADDR , null);
configurationService.setProperty( PROP_STUN_SERVER_ADDR , null);
}
catch(Exception ex){}
}
}

@ -0,0 +1,20 @@
Bundle-Activator: net.java.sip.communicator.slick.netaddr.NetworkAddressManagerServiceLick
Bundle-Name: Network Address Manager Service Implementation Compatibility Kit
Bundle-Description: A Service Implementation Compatibility Kit for the Network Adress Manager Service
Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
Import-Package: net.java.sip.communicator.util,
net.java.stun4j.client,
net.java.stun4j.StunAddress,
net.java.stun4j.StunException,
net.java.sip.communicator.service.netaddr,
net.java.sip.communicator.service.configuration,
net.java.sip.communicator.service.configuration.event,
junit,
junit.framework,
junit.swingui,
junit.textui,
junit.awtui,
junit.extensions,
junit.runner,
org.osgi.framework,

@ -0,0 +1,59 @@
package net.java.sip.communicator.slick.resources;
import org.osgi.framework.*;
import junit.framework.*;
import net.java.sip.communicator.service.resources.FileAccessService;
import java.util.*;
import net.java.sip.communicator.util.*;
/**
* This class launches the bundle of which test the resources bundle.
* this bundle is a set of (j)unit tests. It should be launched by the
* cruisecontrol module.
*
* @author Alexander Pelov
*/
public class ResourcesServicesLick
extends TestSuite
implements BundleActivator
{
private Logger logger = Logger.getLogger(getClass().getName());
protected static FileAccessService fileAccessService = null;
protected static BundleContext bc = null;
public static TestCase tcase = new TestCase(){};
/**
* Start the Resources Sevice Implementation Compatibility Kit.
*
* @param bundleContext BundleContext
* @throws Exception
*/
public void start(BundleContext bundleContext) throws Exception
{
ResourcesServicesLick.bc = bundleContext;
setName("ResourcesServicesLick");
Hashtable properties = new Hashtable();
properties.put("service.pid", getName());
addTestSuite(TestFileAccessService.class);
bundleContext.registerService(getClass().getName(), this, properties);
logger.debug("Successfully registered " + getClass().getName());
}
/**
* stop
*
* @param bundlecontext BundleContext
* @throws Exception
*/
public void stop(BundleContext bundlecontext) throws Exception
{
}
}

@ -0,0 +1,296 @@
package net.java.sip.communicator.slick.resources;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import junit.framework.TestCase;
import net.java.sip.communicator.service.resources.FileAccessService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
public class TestFileAccessService extends TestCase {
/**
* The ConfigurationService that we will be testing.
*/
private FileAccessService fileAccessService = null;
/**
* Some sample data to be writen.
*/
private static final byte[] testData =
"The quick brown fox jumped over the lazy dog".getBytes();
/**
* Random data to be added to the sample data.
*/
private static final Random randomData = new Random();
/**
* The persistent directory's name.
*/
private static final String dirName = "fileaccessservice.dir.tst";
/**
* The persistent directory's name.
*/
private static final String[] dirNames = {
"fileaccessservice.dir.tst",
"subdir1",
"subdir2"
};
/**
* The persistent file's name.
*/
private static final String fileName = "fileaccessservice.tst";
public TestFileAccessService(String name) {
super(name);
BundleContext context = ResourcesServicesLick.bc;
ServiceReference ref = context.getServiceReference(
FileAccessService.class.getName());
this.fileAccessService = (FileAccessService)context.getService(ref);
}
/*
* Test method for 'net.java.sip.communicator.service.resources.FileAccessServiceImpl.getTemporaryFile()'
*/
public void testCreateReadWriteTemporaryFile() {
try {
File tempFile = this.fileAccessService.getTemporaryFile();
// The file should be new!
assertEquals(tempFile.length(), 0);
writeReadFile(tempFile);
} catch (IOException e) {
fail("Error while opening the temp file: " + e.getMessage());
}
}
/*
* Test method for 'net.java.sip.communicator.service.resources.FileAccessServiceImpl.getTemporaryFile()'
*/
public void testCreateTemporaryDirectory() throws Exception {
try {
this.fileAccessService.getTemporaryDirectory();
} catch(IOException e) {
fail("Error creating the temp directory: " + e.getMessage());
}
}
/*
* Test method for 'net.java.sip.communicator.service.resources.FileAccessServiceImpl.getTemporaryFile()'
*/
public void testCreateReadWriteFileInTemporaryDirectory() throws Exception {
int testFiles = 10;
File[] files = new File[testFiles];
byte[][] randomData = new byte[testFiles][];
for(int i = 0; i < testFiles; i++) {
File tempDir = null;
try {
tempDir = this.fileAccessService.getTemporaryDirectory();
} catch(IOException e) {
fail("Error creating the temp directory: " + e.getMessage());
}
files[i] = new File(tempDir, fileName);
assertTrue("Error creating file in temp dir",
files[i].createNewFile());
randomData[i] = generateRandomData();
this.writeFile(files[i], randomData[i]);
}
// Read all files afterwards to ensure that temp directories
// are different
for(int i = 0; i < testFiles; i++) {
this.readFile(files[i], randomData[i]);
}
}
/*
* Tests if it is possible to create a persistent directory.
*/
public void testCreatePersistentDirectory() throws Exception {
try {
this.fileAccessService.getPrivatePersistentDirectory(dirName);
this.fileAccessService.getPrivatePersistentDirectory(dirNames);
} catch(IOException e) {
fail("Error creating the temp directory: " + e.getMessage());
}
}
/*
* Tests if it is possible to create a persistent directory and
* a create file and write and read data to this file.
*/
public void testCreateReadWriteFileInPersistentDirectory() throws Exception {
File privateDir = null;
try {
privateDir = this.fileAccessService.getPrivatePersistentDirectory(dirName);
} catch(IOException e) {
fail("Error creating the private directory: " + e.getMessage());
}
File file = new File(privateDir, fileName);
if(file.exists()) {
assertTrue("Persistent file exists. Delete attempt failed. " +
"Have you ran the tests with other user? " +
"Is the file locked?" + file.getAbsolutePath(), file.delete());
}
assertTrue("Error creating file in dir" + file.getAbsolutePath(),
file.createNewFile());
this.writeReadFile(file);
file.delete();
assertFalse("Could not clean up created file " +
file.getAbsolutePath(), file.exists());
}
/*
* Tests if it is possible for a file to be created if it does not exist
*/
public void testCreatePersistentFile() {
try {
File file = this.fileAccessService.getPrivatePersistentFile(fileName);
if(!file.exists()) {
// Assert that we CAN create the file if it does not exist
assertTrue(file.createNewFile());
}
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test will always pass, because it is not guaranteed that
* it is possible for the supplied file to be deleted. It is used in conjunction
* with the other tests
*/
public void testDeletePersistentFile() {
try {
File file = this.fileAccessService.getPrivatePersistentFile(fileName);
if(file.exists()) {
file.delete();
}
} catch (Exception e) {
}
}
/*
* Tests if it is possible for a file to be created if it does not exist
*/
public void testCreateReadWritePersistentFile() {
try {
File file = this.fileAccessService.getPrivatePersistentFile(fileName);
if(!file.exists()) {
assertTrue(file.createNewFile());
}
writeReadFile(file);
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* Tests if it data actually persists between calls
*/
public void testPersistentFilePersistency() {
try {
File file = this.fileAccessService.getPrivatePersistentFile(fileName);
if(!file.exists()) {
assertTrue(file.createNewFile());
}
writeReadFile(file);
File newFile = this.fileAccessService.getPrivatePersistentFile(fileName);
// Assert that those files are in fact the same
assertEquals(file, newFile);
// and with the same size
assertEquals(file.length(), newFile.length());
} catch (Exception e) {
fail(e.getMessage());
}
}
private void writeReadFile(File file) {
byte[] randomData = generateRandomData();
writeFile(file, randomData);
readFile(file, randomData);
}
private byte[] generateRandomData() {
int rndInt = TestFileAccessService.randomData.nextInt(Integer.MAX_VALUE);
return Integer.toHexString(rndInt).getBytes();
}
private void writeFile(File file, byte[] randomData) {
assertTrue(file.canWrite());
FileOutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(testData);
output.write(randomData);
output.flush();
} catch(Exception e) {
fail("Could not write to file: " + e.getMessage());
} finally {
try {
output.close();
} catch (IOException e) {}
}
}
private void readFile(File file, byte[] randomData) {
assertTrue(file.canRead());
FileInputStream input = null;
byte[] readBuff = new byte[testData.length + randomData.length];
try {
input = new FileInputStream(file);
input.read(readBuff);
} catch(Exception e) {
fail("Could not read from file: " + e.getMessage());
} finally {
try {
input.close();
} catch (IOException e) {}
}
// Check if testData was correctly written
for(int i = 0; i < testData.length; i++) {
assertEquals(readBuff[i], testData[i]);
}
// Check if randomData was correctly written
for(int i = 0; i < randomData.length; i++) {
assertEquals(readBuff[testData.length+i], randomData[i]);
}
}
}

@ -0,0 +1,19 @@
Bundle-Activator: net.java.sip.communicator.slick.resources.ResourcesServicesLick
Bundle-Name: Resources Services Implementation Compatibility Kit
Bundle-Description: A Service Implementation Compatibility Kit for the Resources Services
Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
Import-Package: junit.framework,
net.java.sip.communicator.slick.resources,
net.java.sip.communicator.service.resources,
net.java.sip.communicator.service.configuration,
org.osgi.framework,
org.w3c.dom,
javax.xml.parsers,
net.java.sip.communicator.util,
net.java.sip.communicator.util.xml,
javax.xml.transform,
javax.xml.transform.dom,
javax.xml.transform.stream,
org.apache.xml.serializer,
Export-Package: net.java.sip.communicator.slick.resources,

@ -0,0 +1,311 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*
* The code in this class was borrowed from the ant libs and included the
* following copyright notice:
* Copyright 2000-2004 The Apache Software Foundation
*
* 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 net.java.sip.communicator.slick.runner;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* Writes a DOM tree to a given Writer.
*
* <p>Utility class used by {@link org.apache.tools.ant.XmlLogger
* XmlLogger} and
* org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter
* XMLJUnitResultFormatter}.</p>
*
*/
public class DOMElementWriter {
private static String lSep = System.getProperty("line.separator");
/**
* Don't try to be too smart but at least recognize the predefined
* entities.
*/
protected String[] knownEntities = {"gt", "amp", "lt", "apos", "quot"};
/**
* Writes a DOM tree to a stream in UTF8 encoding. Note that
* it prepends the &lt;?xml version='1.0' encoding='UTF-8'?&gt;.
* The indent number is set to 0 and a 2-space indent.
* @param root the root element of the DOM tree.
* @param out the outputstream to write to.
* @throws IOException if an error happens while writing to the stream.
*/
public void write(Element root, OutputStream out) throws IOException {
Writer wri = new OutputStreamWriter(out, "UTF8");
wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
write(root, wri, 0, " ");
wri.flush();
}
/**
* Writes a DOM tree to a stream.
*
* @param element the Root DOM element of the tree
* @param out where to send the output
* @param indent number of
* @param indentWith string that should be used to indent the corresponding tag.
* @throws IOException if an error happens while writing to the stream.
*/
public void write(Element element, Writer out, int indent,
String indentWith)
throws IOException {
// Write indent characters
for (int i = 0; i < indent; i++) {
out.write(indentWith);
}
// Write element
out.write("<");
out.write(element.getTagName());
// Write attributes
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
out.write(" ");
out.write(attr.getName());
out.write("=\"");
out.write(encode(attr.getValue()));
out.write("\"");
}
out.write(">");
// Write child elements and text
boolean hasChildren = false;
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
switch (child.getNodeType()) {
case Node.ELEMENT_NODE:
if (!hasChildren) {
out.write(lSep);
hasChildren = true;
}
write((Element) child, out, indent + 1, indentWith);
break;
case Node.TEXT_NODE:
out.write(encode(child.getNodeValue()));
break;
case Node.COMMENT_NODE:
out.write("<!--");
out.write(encode(child.getNodeValue()));
out.write("-->");
break;
case Node.CDATA_SECTION_NODE:
out.write("<![CDATA[");
out.write(encodedata(((Text) child).getData()));
out.write("]]>");
break;
case Node.ENTITY_REFERENCE_NODE:
out.write('&');
out.write(child.getNodeName());
out.write(';');
break;
case Node.PROCESSING_INSTRUCTION_NODE:
out.write("<?");
out.write(child.getNodeName());
String data = child.getNodeValue();
if (data != null && data.length() > 0) {
out.write(' ');
out.write(data);
}
out.write("?>");
break;
}
}
// If we had child elements, we need to indent before we close
// the element, otherwise we're on the same line and don't need
// to indent
if (hasChildren) {
for (int i = 0; i < indent; i++) {
out.write(indentWith);
}
}
// Write element close
out.write("</");
out.write(element.getTagName());
out.write(">");
out.write(lSep);
out.flush();
}
/**
* Escape &lt;, &gt; &amp; &apos;, &quot; as their entities and
* drop characters that are illegal in XML documents.
*/
public String encode(String value) {
StringBuffer sb = new StringBuffer();
int len = value.length();
for (int i = 0; i < len; i++) {
char c = value.charAt(i);
switch (c) {
case '<':
sb.append("&lt;");
break;
case '>':
sb.append("&gt;");
break;
case '\'':
sb.append("&apos;");
break;
case '\"':
sb.append("&quot;");
break;
case '&':
int nextSemi = value.indexOf(";", i);
if (nextSemi < 0
|| !isReference(value.substring(i, nextSemi + 1))) {
sb.append("&amp;");
} else {
sb.append('&');
}
break;
default:
if (isLegalCharacter(c)) {
sb.append(c);
}
break;
}
}
return sb.substring(0);
}
/**
* Drop characters that are illegal in XML documents.
*
* <p>Also ensure that we are not including an <code>]]&gt;</code>
* marker by replacing that sequence with
* <code>&amp;#x5d;&amp;#x5d;&amp;gt;</code>.</p>
*
* <p>See XML 1.0 2.2 <a
* href="http://www.w3.org/TR/1998/REC-xml-19980210#charsets">http://www.w3.org/TR/1998/REC-xml-19980210#charsets</a> and
* 2.7 <a
* href="http://www.w3.org/TR/1998/REC-xml-19980210#sec-cdata-sect">http://www.w3.org/TR/1998/REC-xml-19980210#sec-cdata-sect</a>.</p>
*/
public String encodedata(final String value) {
StringBuffer sb = new StringBuffer();
int len = value.length();
for (int i = 0; i < len; ++i) {
char c = value.charAt(i);
if (isLegalCharacter(c)) {
sb.append(c);
}
}
String result = sb.substring(0);
int cdEnd = result.indexOf("]]>");
while (cdEnd != -1) {
sb.setLength(cdEnd);
sb.append("&#x5d;&#x5d;&gt;")
.append(result.substring(cdEnd + 3));
result = sb.substring(0);
cdEnd = result.indexOf("]]>");
}
return result;
}
/**
* Is the given argument a character or entity reference?
*/
public boolean isReference(String ent) {
if (!(ent.charAt(0) == '&') || !ent.endsWith(";")) {
return false;
}
if (ent.charAt(1) == '#') {
if (ent.charAt(2) == 'x') {
try {
Integer.parseInt(ent.substring(3, ent.length() - 1), 16);
return true;
} catch (NumberFormatException nfe) {
return false;
}
} else {
try {
Integer.parseInt(ent.substring(2, ent.length() - 1));
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
}
String name = ent.substring(1, ent.length() - 1);
for (int i = 0; i < knownEntities.length; i++) {
if (name.equals(knownEntities[i])) {
return true;
}
}
return false;
}
/**
* Is the given character allowed inside an XML document?
*
* <p>See XML 1.0 2.2 <a
* href="http://www.w3.org/TR/1998/REC-xml-19980210#charsets">
* http://www.w3.org/TR/1998/REC-xml-19980210#charsets</a>.</p>
*
* @since 1.10, Ant 1.5
*/
public boolean isLegalCharacter(char c) {
if (c == 0x9 || c == 0xA || c == 0xD) {
return true;
} else if (c < 0x20) {
return false;
} else if (c <= 0xD7FF) {
return true;
} else if (c < 0xE000) {
return false;
} else if (c <= 0xFFFD) {
return true;
}
return false;
}
}

@ -0,0 +1,155 @@
package net.java.sip.communicator.slick.runner;
import junit.textui.TestRunner;
import junit.framework.*;
import junit.runner.*;
import net.java.sip.communicator.util.*;
/**
* A command line based tool to run tests.
* <pre>
* java junit.textui.TestRunner [-wait] TestCaseClass
* </pre>
* TestRunner expects the name of a TestCase class as argument.
* If this class defines a static <code>suite</code> method it
* will be invoked and the returned test is run. Otherwise all
* the methods starting with "test" having no arguments are run.
* <p>
* When the wait command line argument is given TestRunner
* waits until the users types RETURN.
* <p>
* TestRunner prints a trace as the tests are executed followed by a
* summary at the end.
*/
public class ScTestRunner extends BaseTestRunner {
private Logger logger = Logger.getLogger(ScTestRunner.class.getName());
static private XmlFormatter testPrinter;
/**
* Constructs a TestRunner using the given ResultPrinter all the output
*/
public ScTestRunner(XmlFormatter printer) {
this.testPrinter = printer;
}
/**
* Runs a suite extracted from a TestCase subclass.
*/
static public void run(Class testClass, XmlFormatter fmtr) {
run(new TestSuite(testClass), fmtr);
}
/**
* Runs a single test and collects its results.
* This method can be used to start a test run
* from your program.
* <pre>
* public static void main (String[] args) {
* test.textui.TestRunner.run(suite());
* }
* </pre>
*/
static public TestResult run(Test test, XmlFormatter printer) {
ScTestRunner runner= new ScTestRunner(printer);
return runner.doRun(test);
}
/**
* Always use the StandardTestSuiteLoader. Overridden from
* BaseTestRunner.
*/
public TestSuiteLoader getLoader() {
return new StandardTestSuiteLoader();
}
public void testFailed(int status, Test test, Throwable t) {
logger.debug("test " + test.toString() + " failed.");
}
public void testStarted(String testName) {
logger.debug("started testName"+testName);
}
public void testEnded(String testName) {
logger.debug("ended testName"+testName);
}
/**
* Creates the TestResult to be used for the test run.
*/
protected TestResult createTestResult() {
return new TestResult();
}
public TestResult doRun(Test test) {
return doRun(test, false);
}
public TestResult doRun(Test suite, boolean wait) {
TestResult result= new TestResult();
result.addListener(testPrinter);
testPrinter.startTestSuite(suite, System.getProperties());
long startTime= System.currentTimeMillis();
suite.run(result);
long endTime= System.currentTimeMillis();
long runTime= endTime-startTime;
testPrinter.endTestSuite(suite, result.errorCount(), result.failureCount(), runTime);
return result;
}
protected void pause(boolean wait) {
if (!wait) return;
// testPrinter.printWaitPrompt();
try {
System.in.read();
}
catch(Exception e) {
}
}
/**
* Starts a test run. Analyzes the command line arguments
* and runs the given test suite.
*/
protected TestResult start(String args[]) throws Exception {
String testCase= "";
boolean wait= false;
for (int i= 0; i < args.length; i++) {
if (args[i].equals("-wait"))
wait= true;
else if (args[i].equals("-c"))
testCase= extractClassName(args[++i]);
else if (args[i].equals("-v"))
System.err.println("JUnit "+Version.id()+" by Kent Beck and Erich Gamma");
else
testCase= args[i];
}
if (testCase.equals(""))
throw new Exception("Usage: TestRunner [-wait] testCaseName, where name is the name of the TestCase class");
try {
Test suite= getTest(testCase);
return doRun(suite, wait);
}
catch(Exception e) {
throw new Exception("Could not create and run test suite: "+e);
}
}
protected void runFailed(String message) {
System.err.println(message);
System.exit(junit.textui.TestRunner.FAILURE_EXIT);
}
// public void setPrinter(ResultPrinter printer) {
// fPrinter= printer;
// }
}

@ -0,0 +1,294 @@
package net.java.sip.communicator.slick.runner;
import junit.framework.*;
import org.osgi.framework.*;
import java.util.StringTokenizer;
import java.io.*;
import net.java.sip.communicator.util.*;
/**
* Detects and runs all Service Implementation Compatibility Kits (SLICKs)inside
* the current OSGI instance. The SipCommunicatorSlickRunner produces an xml log
* file following ant format rules (so that it could be used by CruiseControl)
* and stores it inside the directory indicated in the
* net.java.sip.communicator.slick.runner.OUTPUT_DIR property (default is
* test-reports).
* <p>
* In order for the SipCommunicatorSlickRunner to detect all SLICKs they
* needs to be registered as services in the OSGI environment prior to the
* actication of the runner, and their names need to be specified in a
* whitespace separated list registered against the
* net.java.sip.communicator.slick.runner.TEST_LIST system property.
* <p>
* After running all unit tests the SipcCommunicatorSlickRunner will try to
* gracefully shutdown the OSCAR OSGI framework (if it fails it'll shut it
* down rudely ;) ) and will System.exit() with an error code in case any
* test failures occurred or with 0 if all tests passed.
*
* @author Emil Ivov
*/
public class SipCommunicatorSlickRunner
extends TestSuite implements BundleActivator
{
private Logger logger = Logger.getLogger(getClass().getName());
/**
* The name of the property indicating the Directory where test reports
* should be stored.
*/
private static final String OUTPUT_DIR_PROPERTY_NAME =
"net.java.sip.communicator.slick.runner.OUTPUT_DIR";
/**
* A default name for the Directory where test reports should be stored.
*/
private static final String DEFAULT_OUTPUT_DIR = "test-reports";
/**
* The name of the property indicating the name of the file where test
* reports should be stored.
*/
private static final String OUTPUT_FILE_NAME =
"sip-communicator.unit.test.reports.xml";
/**
* The name of the property that contains the list of Service ICKs that
* we'd have to run.
*/
private static final String TEST_LIST_PROPERTY_NAME =
"net.java.sip.communicator.slick.runner.TEST_LIST";
/**
* A reference to the bundle context received when activating the test
* runner.
*/
private BundleContext bundleContext = null;
/**
* The number of failures and errors that occurred during unit testing.
*/
private int errCount = 0;
/**
* The number of unit tests run by the slick runner.
*/
private int runCount = 0;
/**
* Starts the slick runner, runs all unit tests indicated in the
* TEST_LIST property, and exits with an error code corresponding to whether
* or there were failure while running the tests.
* @param bc BundleContext
* @throws Exception
*/
public void start(BundleContext bc) throws Exception
{
logger.logEntry();
try
{
bundleContext = bc;
setName(getClass().getName());
//Let's now see what tests have been scheduled for execution.
String tests = System.getProperty(TEST_LIST_PROPERTY_NAME);
if (tests == null || tests.trim().length() == 0)
{
tests = "";
}
logger.debug("specfied test list is: " + tests);
StringTokenizer st = new StringTokenizer(tests);
String[] ids = new String[st.countTokens()];
int n = 0;
while (st.hasMoreTokens())
{
ids[n++] = st.nextToken().trim();
}
//Determine the file specified for storing test results.
String outputDirName = System.getProperty(OUTPUT_DIR_PROPERTY_NAME);
if (outputDirName == null || outputDirName.trim().length() == 0)
{
outputDirName = DEFAULT_OUTPUT_DIR;
}
File outputDir = new File(outputDirName);
if (!outputDir.exists())
{
outputDir.mkdirs();
}
for (int i = 0; i < ids.length; i++)
{
logger.debug("Retrieving test suite: " + ids[i]);
TestSuite slick = getTestSuite(bc, ids[i]);
logger.debug("with " + slick.countTestCases() + " tests.");
File outputFile =
new File(outputDir, "SC-TEST-" + ids[i] + ".xml");
if (!outputFile.exists())
{
outputFile.createNewFile();
}
logger.debug("specified reports file: "
+ outputFile.getCanonicalFile());
OutputStream out =
new FileOutputStream(outputFile);
XmlFormatter fmtr = new XmlFormatter(new PrintStream(out));
TestResult res = ScTestRunner.run(slick, fmtr);
errCount += res.errorCount() + res.failureCount();
runCount += res.runCount();
out.flush();
out.close();
}
logger.info("We ran " + runCount
+ " tests and encountered " + errCount
+ " errors and failures.");
//in order to shutdown oscar we'd first need to wait for it to
//complete it's start process, so we'll have to implement shutdown
//in a framework listener.
bc.addFrameworkListener(new FrameworkListener(){
public void frameworkEvent(FrameworkEvent event){
if( event.getType() == FrameworkEvent.STARTED)
{
try
{
//first stop the system bundle thus causing oscar
//to stop all user bundles and shut down.
bundleContext.getBundle(0).stop();
}
catch (BundleException ex)
{
logger.error("Failed to gently shutdown Oscar",ex);
}
//if everything is ok then the stop call shouldn't have
//exited the the program since we must have set the
//"oscar.embedded.execution" property to true
//we could therefore now System.exit() with a code
//indicating whether or not all unit tests went wrong
System.exit(errCount > 0? -1: 0);
}
}
});
}
finally
{
logger.logExit();
}
}
/**
* Dummy impl
* @param bc BundleContext
*/
public void stop(BundleContext bc)
{
logger.debug("Stopping!");
}
/**
* Looks through the osgi framework for a service with a "service.pid"
* property set to <code>id</code>.
* @param bc the BundleContext where the service is to be looked for.
* @param id the value of the "service.pid" property for the specified
* service.
* @return a TestSuite service corresponding the specified <code>id</code>
* or a junit TestCase impl wrapping an exception in case we failed to
* retrieve the service for some reason.
*/
public TestSuite getTestSuite(BundleContext bc,
final String id)
{
Object obj = null;
try
{
ServiceReference[] srl =
bc.getServiceReferences(null, "(service.pid=" + id + ")");
if (srl == null || srl.length == 0)
{
obj = new TestCase("No id=" + id)
{
public void runTest()
{
throw new IllegalArgumentException("No test with id=" +
id);
}
};
}
if (srl != null && srl.length != 1)
{
obj = new TestCase("Multiple id=" + id)
{
public void runTest()
{
throw new IllegalArgumentException(
"More than one test with id=" + id);
}
};
}
if (obj == null)
{
obj = bc.getService(srl[0]);
}
}
catch (Exception e)
{
obj = new TestCase("Bad filter syntax id=" + id)
{
public void runTest()
{
throw new IllegalArgumentException("Bad syntax id=" + id);
}
};
}
if (! (obj instanceof Test))
{
final Object oldObj = obj;
obj = new TestCase("ClassCastException")
{
public void runTest()
{
throw new ClassCastException("Service implements " +
oldObj.getClass().getName() +
" instead of " +
Test.class.getName());
}
};
}
Test test = (Test) obj;
TestSuite suite;
if (test instanceof TestSuite)
{
suite = (TestSuite) test;
}
else
{
suite = new TestSuite(id);
suite.addTest(test);
}
return suite;
}
}

@ -0,0 +1,89 @@
/*
* Copyright 2001,2004 The Apache Software Foundation
*
* 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 net.java.sip.communicator.slick.runner;
/**
* <p> Interface groups XML constants.
* Interface that groups all constants used throughout the <tt>XML</tt>
* documents that are generated by the <tt>XMLJUnitResultFormatter</tt>
* As of now the DTD is:
* <code><pre>
* <----------------- @todo describe DTDs ---------------------->
*
* </pre></code>
* @see XMLJUnitResultFormatter
* @see XMLResultAggregator
*/
public interface XMLConstants {
/** the testsuites element for the aggregate document */
String TESTSUITES = "testsuites";
/** the testsuite element */
String TESTSUITE = "testsuite";
/** the testcase element */
String TESTCASE = "testcase";
/** the error element */
String ERROR = "error";
/** the failure element */
String FAILURE = "failure";
/** the system-err element */
String SYSTEM_ERR = "system-err";
/** the system-out element */
String SYSTEM_OUT = "system-out";
/** package attribute for the aggregate document */
String ATTR_PACKAGE = "package";
/** name attribute for property, testcase and testsuite elements */
String ATTR_NAME = "name";
/** time attribute for testcase and testsuite elements */
String ATTR_TIME = "time";
/** errors attribute for testsuite elements */
String ATTR_ERRORS = "errors";
/** failures attribute for testsuite elements */
String ATTR_FAILURES = "failures";
/** tests attribute for testsuite elements */
String ATTR_TESTS = "tests";
/** type attribute for failure and error elements */
String ATTR_TYPE = "type";
/** message attribute for failure elements */
String ATTR_MESSAGE = "message";
/** the properties element */
String PROPERTIES = "properties";
/** the property element */
String PROPERTY = "property";
/** value attribute for property elements */
String ATTR_VALUE = "value";
/** classname attribute for testcase elements */
String ATTR_CLASSNAME = "classname";
}

@ -0,0 +1,284 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*
* This class is based on code extracted from the ANT Project, property of the
* Apache Software Foundation. It originally included the following license
* Copyright 2000-2004 The Apache Software Foundation
*
* 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 net.java.sip.communicator.slick.runner;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import java.io.StringWriter;
import java.io.PrintWriter;
import junit.framework.*;
import junit.textui.*;
import java.io.*;
/**
* Prints XML output of the test to a specified Writer.
*
*
* @see FormatterElement
*/
public class XmlFormatter extends ResultPrinter implements XMLConstants {
private static DocumentBuilder getDocumentBuilder() {
try {
return DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (Exception exc) {
throw new ExceptionInInitializerError(exc);
}
}
/**
* The XML document.
*/
private Document doc;
/**
* The wrapper for the whole testsuite.
*/
private Element rootElement;
/**
* Element for the current test.
*/
private Hashtable testElements = new Hashtable();
/**
* tests that failed.
*/
private Hashtable failedTests = new Hashtable();
/**
* Timing helper.
*/
private Hashtable testStarts = new Hashtable();
/**
* Where to write the log to.
*/
private OutputStream out;
public XmlFormatter(PrintStream out) {
super(out);
setOutput(out);
}
public void setOutput(OutputStream out) {
this.out = out;
}
public void setSystemOutput(String out) {
formatOutput(SYSTEM_OUT, out);
}
public void setSystemError(String out) {
formatOutput(SYSTEM_ERR, out);
}
/**
* The whole testsuite started.
*/
public void startTestSuite(Test suite, Properties props) {
doc = getDocumentBuilder().newDocument();
rootElement = doc.createElement(TESTSUITE);
rootElement.setAttribute(ATTR_NAME, suite.toString());
// Output properties
Element propsElement = doc.createElement(PROPERTIES);
rootElement.appendChild(propsElement);
if (props != null) {
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
Element propElement = doc.createElement(PROPERTY);
propElement.setAttribute(ATTR_NAME, name);
propElement.setAttribute(ATTR_VALUE, props.getProperty(name));
propsElement.appendChild(propElement);
}
}
}
/**
* The whole testsuite ended.
*/
public void endTestSuite(Test suite,
int err_count,
int fail_count,
long time)
throws RuntimeException
{
rootElement.setAttribute(ATTR_TESTS, "" + suite.countTestCases());
rootElement.setAttribute(ATTR_FAILURES, "" + fail_count);
rootElement.setAttribute(ATTR_ERRORS, "" + err_count);
rootElement.setAttribute(ATTR_TIME, "" + (time / 1000.0));
if (out != null) {
Writer wri = null;
try {
wri = new BufferedWriter(new OutputStreamWriter(out, "UTF8"));
wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
(new DOMElementWriter()).write(rootElement, wri, 0, " ");
wri.flush();
} catch (IOException exc) {
throw new RuntimeException("Unable to write log file", exc);
} finally {
if (out != System.out && out != System.err) {
if (wri != null) {
try {
wri.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
}
/**
* Interface TestListener.
*
* <p>A new Test is started.
*/
public void startTest(Test test){
testStarts.put(test, new Long(System.currentTimeMillis()));
}
/**
* Interface TestListener.
*
* <p>A Test is finished.
*/
public void endTest(Test test) {
// Fix for bug #5637 - if a junit.extensions.TestSetup is
// used and throws an exception during setUp then startTest
// would never have been called
if (!testStarts.containsKey(test)) {
startTest(test);
}
Element currentTest = null;
if (!failedTests.containsKey(test)) {
currentTest = doc.createElement(TESTCASE);
currentTest.setAttribute(ATTR_NAME, test.getClass().getName());
// a TestSuite can contain Tests from multiple classes,
// even tests with the same name - disambiguate them.
currentTest.setAttribute(ATTR_CLASSNAME,
test.getClass().getName());
rootElement.appendChild(currentTest);
testElements.put(test, currentTest);
} else {
currentTest = (Element) testElements.get(test);
}
Long l = (Long) testStarts.get(test);
currentTest.setAttribute(ATTR_TIME,
"" + ((System.currentTimeMillis() - l.longValue()) / 1000.0));
}
/**
* Interface TestListener for JUnit &lt;= 3.4.
*
* <p>A Test failed.
*/
public void addFailure(Test test, Throwable t) {
formatError(FAILURE, test, t);
}
/**
* Interface TestListener for JUnit &gt; 3.4.
*
* <p>A Test failed.
*/
public void addFailure(Test test, AssertionFailedError t) {
addFailure(test, (Throwable) t);
}
/**
* Interface TestListener.
*
* <p>An error occurred while running the test.
*/
public void addError(Test test, Throwable t) {
formatError(ERROR, test, t);
}
private void formatError(String type, Test test, Throwable t) {
if (test != null) {
endTest(test);
failedTests.put(test, test);
}
Element nested = doc.createElement(type);
Element currentTest = null;
if (test != null) {
currentTest = (Element) testElements.get(test);
} else {
currentTest = rootElement;
}
currentTest.appendChild(nested);
String message = t.getMessage();
if (message != null && message.length() > 0) {
nested.setAttribute(ATTR_MESSAGE, t.getMessage());
}
nested.setAttribute(ATTR_TYPE, t.getClass().getName());
String strace = getStackTrace(t);
Text trace = doc.createTextNode(strace);
nested.appendChild(trace);
}
/**
* Convenient method to retrieve the full stacktrace from a given exception.
* @param t the exception to get the stacktrace from.
* @return the stacktrace from the given exception.
*/
public static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
pw.flush();
pw.close();
return sw.toString();
}
private void formatOutput(String type, String output) {
Element nested = doc.createElement(type);
rootElement.appendChild(nested);
nested.appendChild(doc.createCDATASection(output));
}
} // XMLJUnitResultFormatter

@ -0,0 +1,35 @@
Bundle-Activator: net.java.sip.communicator.slick.runner.SipCommunicatorSlickRunner
Bundle-Name: Slick Runner
Bundle-Description: A bundle that runs all SLICKs declared in the corresponding sys property
Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
Import-Package: net.java.sip.communicator.service.configuration,
net.java.sip.communicator.service.configuration.event,
junit,
junit.framework,
junit.swingui,
junit.textui,
junit.awtui,
junit.extensions,
junit.runner,
org.osgi.framework,
org.w3c.dom,
javax.xml.parsers,
net.java.sip.communicator.util.xml,
javax.xml.transform,
javax.xml.transform.dom,
javax.xml.transform.stream,
org.apache.xml.serializer,
net.java.sip.communicator.util,
org.apache.tools.ant,
org.apache.tools.ant.taskdefs.optional.junit,
org.osgi.framework,
junit,
junit.framework,
junit.swingui,
junit.textui,
junit.awtui,
junit.extensions,
junit.runner
Export-Package: org.apache.tools.ant,

@ -0,0 +1,54 @@
package net.java.sip.communicator.slick.slickless;
import org.osgi.framework.*;
import junit.framework.*;
import java.util.*;
import net.java.sip.communicator.slick.slickless.util.xml.*;
import net.java.sip.communicator.util.*;
/**
* Runs all unit tests that do not belong to any SLICK.
*
* @author Emil Ivov
*/
public class SlicklessTests
extends TestSuite
implements BundleActivator
{
private Logger logger = Logger.getLogger(getClass().getName());
protected static BundleContext bc = null;
/**
* Start the Configuration Sevice Implementation Compatibility Kit.
*
* @param bundleContext BundleContext
* @throws Exception
*/
public void start(BundleContext bundleContext) throws Exception
{
this.bc = bundleContext;
setName("SlicklessTests");
Hashtable properties = new Hashtable();
properties.put("service.pid", getName());
addTestSuite(TestXMLUtils.class);
bundleContext.registerService(getClass().getName(), this, properties);
logger.debug("Successfully registered " + getClass().getName());
}
/**
* stop
*
* @param bundlecontext BundleContext
* @throws Exception
*/
public void stop(BundleContext bundlecontext) throws Exception
{
}
}

@ -0,0 +1,25 @@
Bundle-Activator: net.java.sip.communicator.slick.slickless.SlicklessTests
Bundle-Name: SlicklessTesting
Bundle-Description: Unit testing for classes not belonging to any service implementation.
Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
Import-Package: net.java.sip.communicator.service.configuration,
net.java.sip.communicator.service.configuration.event,
junit,
junit.framework,
junit.swingui,
junit.textui,
junit.awtui,
junit.extensions,
junit.runner,
org.osgi.framework,
org.w3c.dom,
javax.xml.parsers,
net.java.sip.communicator.util.xml,
javax.xml.transform,
javax.xml.transform.dom,
javax.xml.transform.stream,
org.apache.xml.serializer,
net.java.sip.communicator.util,
Export-Package: net.java.sip.communicator.slick.slickless,
net.java.sip.communicator.slick.slickless.util.xml,

@ -0,0 +1,236 @@
package net.java.sip.communicator.slick.slickless.util.xml;
import junit.framework.*;
import org.w3c.dom.*;
import java.io.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.DocumentBuilder;
import java.util.Hashtable;
import javax.xml.parsers.DocumentBuilderFactory;
import net.java.sip.communicator.util.xml.*;
/**
* JUnit tests for the TestXMLUtils package.
*
* @author Emil Ivov
*/
public class TestXMLUtils extends TestCase
{
//property1 values
private static final String property1 = "p1";
private static final String property1Value = "p1.value";
private static final String property1Value2 = "p1.value.2";
private static final String property1Path = "parent.";
//property2 values
private static final String systemProperty = "SYSTEM_PROPERTY";
private static final String systemPropertyValue = "I AM the SyS guy";
private static final String systemPropertyValue2 = "sys guy's new face";
private static final String systemPropertyPath = "parent.";
//added_property values
private static final String addedProperty = "ADDED_PROPERTY";
private static final String addedPropertyValue = "added";
private static final String addedPropertyValue2 = "and then re-aded";
private static final String addedPropertyPath = "parent.";
//INNER_PROPERTY values
private static final String innerProperty = "INNER_PROPERTY";
private static final String innerPropertyValue = "I am an insider";
private static final String innerPropertyValue2 = "I am a modified inner";
private static final String innerPropertyPath = "parent.innerprops.";
//CDATA_NODE
private static final String cdataNode = "CDATA_NODE";
private static final String cdataNodeContent = "Thisis theCDATA nodeCOntent";
private static final String cdataNodeContent2 = "The return of the CDATA";
//TEXT_NODE
private static final String textNode = "TEXT_NODE";
private static final String textNodeContent = "Thisis the TeXt nodeCOntent";
private static final String textNodeContent2 = "The text strikes back";
/** the contents of our properties file.*/
private static String xmlString =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<sip-communicator>\n" +
" <parent>" +"\n"+
" <"+property1+" value=\""+property1Value+"\"/>" +"\n"+
" <"+systemProperty
+" value=\""+systemPropertyValue+"\" system=\"true\"/>" +"\n"+
" <innerprops>" +"\n"+
" <"+innerProperty+" value=\""+innerPropertyValue+"\"/>" +"\n"+
" </innerprops>" +"\n"+
" </parent>" +"\n"+
" <"+cdataNode+"><![CDATA["+cdataNodeContent+"]]></"+cdataNode+">" +"\n"+
" <"+textNode+">"+textNodeContent+"</"+textNode+">" +"\n"+
"</sip-communicator>\n";
DocumentBuilderFactory factory = null;
DocumentBuilder builder = null;
Document document = null;
Node rootNode = null;
public TestXMLUtils(String testName)
{
super(testName);
}
/**
* Create a XML Document that will be used as a fixture in later testing.
* @throws Exception if sth goes nuts
*/
protected void setUp() throws Exception
{
factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream in = new java.io.ByteArrayInputStream(xmlString.getBytes());
document = builder.parse(in);
rootNode = document.getFirstChild();
super.setUp();
}
/**
* Standard JUnit tear down
* @throws Exception ... don't know when
*/
protected void tearDown() throws Exception
{
super.tearDown();
}
/**
* Tests the find child method over a few nodes of the sample xml string.
*/
public void testFindChild()
{
Element parent = (Element)rootNode;
String tagName = "parent";
Element actualReturn = XMLUtils.findChild(parent, tagName);
//make sure it found the only "parent" child
assertEquals("parent", actualReturn.getTagName());
//let's now look for the inneroprs child
parent = actualReturn;
tagName = "innerprops";
actualReturn = XMLUtils.findChild(parent, tagName);
//make sure it found the innerprops child
assertEquals("innerprops", actualReturn.getTagName());
}
/**
* Tests the getAttribute method over property1
*/
public void testGetAttribute()
{
Element parent = (Element)rootNode;
String tagName = "parent";
Element actualReturn = XMLUtils.findChild(parent, tagName);
//make sure it found the only "parent" child
assertEquals("parent", actualReturn.getTagName());
//let's now look for the inneroprs child
parent = actualReturn;
actualReturn = XMLUtils.findChild(parent, property1);
//make sure it found the innerprops child
assertEquals(property1, actualReturn.getTagName());
//make sure it found the innerprops child
assertEquals(property1Value,
XMLUtils.getAttribute(actualReturn, "value"));
}
/**
* Tests getCData over the cdataNode of the sample XML.
*/
public void testGetSetCData()
{
Element parent = (Element)rootNode;
Element returnedCdataNode = XMLUtils.findChild(parent, cdataNode);
String actualReturn = XMLUtils.getCData(returnedCdataNode);
//compare the returned data with the actual.
assertEquals(cdataNodeContent, actualReturn);
//set, with a new value
XMLUtils.setCData(returnedCdataNode, cdataNodeContent2);
//now get it again and re-assert
returnedCdataNode = XMLUtils.findChild(parent, cdataNode);
actualReturn = XMLUtils.getCData(returnedCdataNode);
//compare the returned data with the actual.
assertEquals(cdataNodeContent2, actualReturn);
}
/**
* Tests getText over the textNode of the sample XML.
*/
public void testGetSetText()
{
Element parent = (Element)rootNode;
Element returnedTextNode = XMLUtils.findChild(parent, textNode);
String actualReturn = XMLUtils.getText(returnedTextNode);
//compare the returned data with the actual.
assertEquals(textNodeContent, actualReturn);
//set, with a new value
XMLUtils.setCData(returnedTextNode, textNodeContent2);
//now get it again and re-assert
returnedTextNode = XMLUtils.findChild(parent, textNode);
actualReturn = XMLUtils.getCData(returnedTextNode);
//compare the returned data with the actual.
assertEquals(textNodeContent2, actualReturn);
}
public void testWriteXML() throws Exception
{
StringWriter writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);
String doctypeSystem = null;
String doctypePublic = null;
XMLUtils.writeXML(document, streamResult, doctypeSystem, doctypePublic);
String writtenString = writer.toString();
//now run some of the previous tests to make sure they passe with the
//newly written string
xmlString = new StringBuffer(writtenString).toString();
setUp();
testFindChild();
xmlString = new StringBuffer(writtenString).toString();
setUp();
testGetAttribute();
xmlString = new StringBuffer(writtenString).toString();
setUp();
testGetSetCData();
xmlString = new StringBuffer(writtenString).toString();
setUp();
testGetSetText();
}
}
Loading…
Cancel
Save