You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ace.apache.org by ma...@apache.org on 2009/06/27 17:53:26 UTC

svn commit: r788992 [21/25] - in /incubator/ace/trunk: gateway/ gateway/src/ gateway/src/net/ gateway/src/net/luminis/ gateway/src/net/luminis/liq/ gateway/src/net/luminis/liq/bootstrap/ gateway/src/net/luminis/liq/bootstrap/multigateway/ gateway/src/n...

Added: incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/filebased/FileBasedProviderTest.java
URL: http://svn.apache.org/viewvc/incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/filebased/FileBasedProviderTest.java?rev=788992&view=auto
==============================================================================
--- incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/filebased/FileBasedProviderTest.java (added)
+++ incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/filebased/FileBasedProviderTest.java Sat Jun 27 15:53:04 2009
@@ -0,0 +1,275 @@
+package net.luminis.liq.deployment.provider.filebased;
+
+import static net.luminis.liq.test.utils.TestUtils.UNIT;
+
+import java.io.File;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import net.luminis.liq.deployment.provider.ArtifactData;
+import net.luminis.liq.deployment.provider.impl.ArtifactDataImpl;
+import net.luminis.liq.test.utils.FileUtils;
+import net.luminis.liq.test.utils.TestUtils;
+import net.luminis.liq.test.utils.deployment.BundleStreamGenerator;
+
+import org.osgi.service.log.LogService;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+/**
+ * This test class tests the FileBasedProvider class.
+ * This class implements 2 backend interfaces,
+ * and both are tested here.
+ */
+public class FileBasedProviderTest {
+
+    private FileBasedProvider m_backend;
+
+    private File m_tempDirectory;
+
+    private final String VERSION1 = "1.0.0";
+    private final String VERSION2 = "2.0.0";
+    private final String VERSION3 = "3.0.0";
+    private final String VERSION4 = "4.0.0";
+    private final String INVALIDVERSION = "Invalid.version.directory";
+
+    private final String GATEWAY = "gateway";
+    private final String MULTIPLEVERSIONGATEWAY = "multi-version-gateway";
+    private final String INVALIDVERSIONGATEWAY = "illegal-version-gateway";
+    private ArtifactData BUNDLE1;
+    private ArtifactData BUNDLE3;
+    private ArtifactData BUNDLE4;
+    private ArtifactData BUNDLE4_1;
+    private ArtifactData BUNDLE5;
+    private ArtifactData BUNDLE3_2;
+    private ArtifactData BUNDLE4_2;
+
+    @SuppressWarnings("serial")
+    @BeforeTest(alwaysRun = true)
+    protected void setUp() throws Exception {
+
+        // first create a file
+        m_tempDirectory = FileUtils.createTempFile(null);
+        // and make a directory with that name.
+        m_tempDirectory.mkdir();
+        setupSampleData();
+
+        m_backend = new FileBasedProvider();
+        TestUtils.configureObject(m_backend, LogService.class);
+        m_backend.updated(new Properties() {{put("BaseDirectoryName", m_tempDirectory.getAbsolutePath());}});
+    }
+
+    /**
+     * make a bundle with the given symbolic name and version in the given file.
+     */
+    private ArtifactData generateBundle(File file, String symbolicName, String version) throws Exception {
+        ArtifactData bundle = new ArtifactDataImpl(file.getName(), symbolicName, version, file.toURI().toURL(), false);
+        BundleStreamGenerator.generateBundle(bundle);
+        return bundle;
+    }
+
+    /**
+     * Create the test gateways, versions and testbundles..
+     */
+    private void setupSampleData() throws Exception {
+        File gateway = new File(m_tempDirectory, GATEWAY);
+        gateway.mkdirs();
+        File gatewayVersion1 = new File(gateway, VERSION1);
+        gatewayVersion1.mkdirs();
+        BUNDLE1 = generateBundle(FileUtils.createTempFile(gatewayVersion1), "Bundle1", "1.0.0");
+
+        File illegalVersionGateway = new File(m_tempDirectory, INVALIDVERSIONGATEWAY);
+        illegalVersionGateway.mkdirs();
+        File faultyVersion = new File(illegalVersionGateway, INVALIDVERSION);
+        faultyVersion.mkdirs();
+        // this bundle should never be accessed
+        generateBundle(FileUtils.createTempFile(faultyVersion), "Bundle2", "2.0.0");
+
+        File multipleVersionGateway = new File(m_tempDirectory, MULTIPLEVERSIONGATEWAY);
+        multipleVersionGateway.mkdir();
+        File multipleVersionGatewayVersion1 = new File(multipleVersionGateway, VERSION1);
+        multipleVersionGatewayVersion1.mkdir();
+        BUNDLE3 = generateBundle(FileUtils.createTempFile(multipleVersionGatewayVersion1), "Bundle3", "3.0.0");
+        BUNDLE4 = generateBundle(FileUtils.createTempFile(multipleVersionGatewayVersion1), "Bundle4", "4.0.0");
+        File multipleVersionGatewayVersion2 = new File(multipleVersionGateway, VERSION2);
+        multipleVersionGatewayVersion2.mkdir();
+        BUNDLE4_1 = generateBundle(FileUtils.createTempFile(multipleVersionGatewayVersion2), "Bundle4", "4.1.0");
+        BUNDLE5 = generateBundle(FileUtils.createTempFile(multipleVersionGatewayVersion2), "Bundle5", "5.0.0");
+        File multipleVersionGatewayVersion3 = new File(multipleVersionGateway, VERSION3);
+        multipleVersionGatewayVersion3.mkdir();
+        File multipleVersionGatewayVersion4 = new File(multipleVersionGateway, VERSION4);
+        multipleVersionGatewayVersion4.mkdir();
+        BUNDLE3_2 = generateBundle(FileUtils.createTempFile(multipleVersionGatewayVersion4), "Bundle3", "3.0.0");
+        BUNDLE4_2 = generateBundle(FileUtils.createTempFile(multipleVersionGatewayVersion4), "Bundle4", "5.0.0");
+    }
+
+    /**
+     * See if the getVersions() methods normal output works
+     */
+    @Test(groups = { UNIT })
+    public void testGetVersion() {
+        List<String> versions = m_backend.getVersions(GATEWAY);
+        assert versions.size() == 1 : "Expected one version to be found, but found " + versions.size();
+        assert versions.get(0).equals(VERSION1) : "Expected version " + VERSION1 + " but found " + versions.get(0);
+    }
+
+    /**
+     * Test the getVersions method with an illegal version (not in org.osgi.framework.Version format)
+     */
+    @Test(groups = { UNIT })
+    public void testIllegalVersion() {
+        // an illegal version should be silently ignored
+        List<String> versions = m_backend.getVersions(INVALIDVERSIONGATEWAY);
+        assert versions.isEmpty() : "Expected no versions to be found, but found " + versions.size();
+    }
+
+    /**
+     * Test with multiple versions. It expects all versions in an ascending order.
+     */
+    @Test(groups = { UNIT })
+    public void testMultipleVersions() {
+        List<String> versions = m_backend.getVersions(MULTIPLEVERSIONGATEWAY);
+        assert versions.size() == 4 : "Expected three version to be found, but found " + versions.size();
+        // all versions should be in ascending order
+        assert versions.get(0).equals(VERSION1) : "Expected version " + VERSION1 + " but found " + versions.get(0);
+        assert versions.get(1).equals(VERSION2) : "Expected version " + VERSION2 + " but found " + versions.get(1);
+        assert versions.get(2).equals(VERSION3) : "Expected version " + VERSION3 + " but found " + versions.get(2);
+        assert versions.get(3).equals(VERSION4) : "Expected version " + VERSION4 + " but found " + versions.get(3);
+    }
+
+    /**
+     * Test the getBundleData for a single version, returning a single bundle
+     */
+    @Test(groups = { UNIT })
+    public void testSingleBundleSingleVersionBundleData() {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(GATEWAY, VERSION1);
+        assert bundleData.size() == 1 : "Expected one bundle to be found, but found " + bundleData.size();
+        assert bundleData.contains(BUNDLE1) : "Expected to find bundle " + BUNDLE1.getSymbolicName();
+    }
+
+    /**
+     * Test the getBundleData for a single version, returning a multiple bundles
+     */
+    @Test(groups = { UNIT })
+    public void testMultipleBundleSingleVersionBundleData() {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION1);
+        assert bundleData.size() == 2 : "Expected two bundle to be found, but found " + bundleData.size();
+        assert bundleData.contains(BUNDLE3) : "Expected to find bundle " + BUNDLE3.getSymbolicName();
+        assert bundleData.contains(BUNDLE4) : "Expected to find bundle " + BUNDLE4.getSymbolicName();
+    }
+
+    /**
+     * Test the getBundleData with an illegal version (i.e. a version that doesn't exist)
+     */
+    @Test(groups = { UNIT })
+    public void testInvalidVersionBundleData() {
+        try {
+            m_backend.getBundleData(INVALIDVERSIONGATEWAY, INVALIDVERSION);
+            assert false : "Expected an error because version " + INVALIDVERSION + " doesn't exist for gateway" + INVALIDVERSIONGATEWAY;
+        } catch (IllegalArgumentException iae) {
+            // expected, because the version doesn't exist
+        }
+    }
+
+    /**
+     * Test the getBundleData for a two versions, returning a single bundle that hasn't changed
+     */
+    @Test(groups = { UNIT })
+    public void testSingleUnchangedBundleMultipleVersions() {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(GATEWAY, VERSION1, VERSION1);
+        assert bundleData.size() == 1 : "Expect one bundle, got " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            assert !data.hasChanged() : "The data should not have been changed.";
+        }
+    }
+
+    /**
+     * Test the getBundleData for a two versions, returning multiple bundles that haven't changed
+     */
+    @Test(groups = { UNIT })
+    public void testMultipleBundlesMultipleVersions() {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION1, VERSION1);
+        assert bundleData.size() == 2 : "Expected two bundle to be found, but found " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            assert !data.hasChanged() : "The data should not have been changed.";
+        }
+    }
+
+    /**
+     * Test the getBundleData for a two versions, where in the second version a bundle is removed
+     */
+    @Test(groups = { UNIT })
+    public void testRemovedBundleMultipleVersions() {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION1, VERSION3);
+        assert bundleData.size() == 0 : "Expected zero bundle to be found, but found " + bundleData.size();
+    }
+
+    /**
+     * Test the getBundleData for a two versions, where in the second version a bundle is added
+     */
+    @Test(groups = { UNIT })
+    public void testAddedBundleMultipleVersions() {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION3, VERSION1);
+        assert bundleData.size() == 2 : "Expected two bundle to be found, but found " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            assert data.hasChanged() : "The data should have been changed.";
+        }
+    }
+
+    /**
+     * Test the getBundleData for a two versions, where in the second version one bundle has changed and another hasn't
+     */
+    @Test(groups = { UNIT })
+    public void testSingleChangedBundleMultipleVersions() {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION1, VERSION4);
+        assert bundleData.size() == 2 : "Expected one bundle to be found, but found " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            if (data.equals(BUNDLE3_2)) {
+                assert !data.hasChanged() : "The data should not have been changed.";
+            } else if (data.equals(BUNDLE4_2)) {
+                assert data.hasChanged() : "The data should have been changed.";
+            } else {
+                assert false : "Unknown bundle found";
+            }
+        }
+    }
+
+    /**
+     * Test the getBundleData for a two versions, where two bundles have changed
+     */
+    @Test(groups = { UNIT })
+    public void testMultipleChangedBundlesMultipleVersions() {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION1, VERSION2);
+        assert bundleData.size() == 2 : "Expected one bundle to be found, but found " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            if (data.equals(BUNDLE4_1)) {
+                assert data.hasChanged() : "The data should have been changed.";
+            } else if (data.equals(BUNDLE5)) {
+                assert data.hasChanged() : "The data should have been changed.";
+            } else {
+                assert false : "Unknown bundle found";
+            }
+        }
+    }
+
+
+    @AfterTest(alwaysRun = true)
+    public void tearDown() throws Exception {
+        FileUtils.removeDirectoryWithContent(m_tempDirectory);
+    }
+
+
+}

Added: incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/repositorybased/MockDeploymentRepository.java
URL: http://svn.apache.org/viewvc/incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/repositorybased/MockDeploymentRepository.java?rev=788992&view=auto
==============================================================================
--- incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/repositorybased/MockDeploymentRepository.java (added)
+++ incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/repositorybased/MockDeploymentRepository.java Sat Jun 27 15:53:04 2009
@@ -0,0 +1,42 @@
+package net.luminis.liq.deployment.provider.repositorybased;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import net.luminis.liq.repository.Repository;
+import net.luminis.liq.repository.SortedRangeSet;
+
+public class MockDeploymentRepository implements Repository {
+
+    private String m_range;
+    private String m_xmlRepository;
+
+    public MockDeploymentRepository(String range, String xmlRepository) {
+        m_range = range;
+        m_xmlRepository = xmlRepository;
+    }
+
+    /* (non-Javadoc)
+     * Magic number version 1, generates an IOException, else return
+     * @see net.luminis.liq.repository.Repository#checkout(long)
+     */
+    public InputStream checkout(long version) throws IOException, IllegalArgumentException {
+        if (version == 1) {
+            //throw an IOException!
+            throw new IOException("Checkout exception.");
+        }
+        else {
+            return new ByteArrayInputStream(m_xmlRepository.getBytes());
+        }
+    }
+
+    public boolean commit(InputStream data, long fromVersion) throws IOException, IllegalArgumentException {
+        // Not used in test
+        return false;
+    }
+
+    public SortedRangeSet getRange() throws IOException {
+        return new SortedRangeSet(m_range);
+    }
+}

Added: incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/repositorybased/RepositoryBasedProviderTest.java
URL: http://svn.apache.org/viewvc/incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/repositorybased/RepositoryBasedProviderTest.java?rev=788992&view=auto
==============================================================================
--- incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/repositorybased/RepositoryBasedProviderTest.java (added)
+++ incubator/ace/trunk/test/src/net/luminis/liq/deployment/provider/repositorybased/RepositoryBasedProviderTest.java Sat Jun 27 15:53:04 2009
@@ -0,0 +1,601 @@
+package net.luminis.liq.deployment.provider.repositorybased;
+
+import static net.luminis.liq.test.utils.TestUtils.UNIT;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.Attributes;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import net.luminis.liq.client.repository.helper.bundle.BundleHelper;
+import net.luminis.liq.client.repository.object.DeploymentArtifact;
+import net.luminis.liq.deployment.provider.ArtifactData;
+import net.luminis.liq.deployment.provider.impl.ArtifactDataImpl;
+import net.luminis.liq.repository.Repository;
+import net.luminis.liq.test.utils.FileUtils;
+import net.luminis.liq.test.utils.TestUtils;
+import net.luminis.liq.test.utils.deployment.BundleStreamGenerator;
+
+import org.osgi.framework.Constants;
+import org.osgi.service.log.LogService;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * This test class tests the Repositorybased Provider class.
+ * This class implements 2 backend interfaces,
+ * and both are tested here.
+ */
+public class RepositoryBasedProviderTest {
+
+    private static final String TAGS_TAG = "tags";
+    private static final String VERSION_TAG = "version";
+    private static final String GATEWAYID_TAG = "gatewayID";
+    private static final String ARTIFACTS_TAG = "artifacts";
+    private static final String ARTIFACT_TAG = "deploymentArtifact";
+    private static final String URL_TAG = "url";
+    private static final String DIRECTIVES_TAG = "directives";
+    private static final String ATTRIBUTES_TAG = "attributes";
+    private static final String DEPLOYMENTVERSION_TAG = "deploymentversion";
+
+    private RepositoryBasedProvider m_backend;
+
+    private File m_tempDirectory;
+
+    private final String VERSION1 = "1.0.0";
+    private final String VERSION2 = "2.0.0";
+    private final String VERSION3 = "3.0.0";
+    private final String VERSION4 = "4.0.0";
+    private final String INVALIDVERSION = "Invalid.version.directory";
+
+    private final String GATEWAY = "gateway";
+    private final String MULTIPLEVERSIONGATEWAY = "multi-version-gateway";
+    private final String INVALIDVERSIONGATEWAY = "illegal-version-gateway";
+    private final String EMPTYVERSIONGATEWAY = "empty-version-gateway";
+    private final String RESOURCEGATEWAY = "resource-gateway";
+
+    private ArtifactData BUNDLE1;
+    private ArtifactData BUNDLE3;
+    private ArtifactData BUNDLE4;
+    private ArtifactData BUNDLE4_1;
+    private ArtifactData BUNDLE5;
+    private ArtifactData BUNDLE3_2;
+    private ArtifactData BUNDLE4_2;
+
+    private ArtifactData RESOURCEPROCESSOR1;
+    private ArtifactData ARTIFACT1;
+
+    @SuppressWarnings("serial")
+    @BeforeMethod(alwaysRun = true)
+    protected void setUp() throws Exception {
+
+        // first create a file
+        m_tempDirectory = FileUtils.createTempFile(null);
+        // and make a directory with that name.
+        m_tempDirectory.mkdir();
+
+        // generate sample data
+        setupSampleData();
+        String deploymentRepositoryXml = generateValidTestXml();
+        String range = "1,2,3";
+
+        // setup mock repository
+        Repository mock = new MockDeploymentRepository(range, deploymentRepositoryXml);
+        m_backend = new RepositoryBasedProvider();
+        TestUtils.configureObject(m_backend, Repository.class, mock);
+        TestUtils.configureObject(m_backend, LogService.class);
+    }
+
+    /**
+     * make a bundle with the given symbolic name and version in the given file.
+     */
+    private ArtifactData generateBundle(File file, Map<String, String> directives, String symbolicName, String version, Map<String, String> additionalHeaders) throws Exception {
+        ArtifactData bundle = new ArtifactDataImpl(file.toURI().toURL(), directives, symbolicName, version, false);
+        if (additionalHeaders == null) {
+            BundleStreamGenerator.generateBundle(bundle);
+        }
+        else {
+            BundleStreamGenerator.generateBundle(bundle, additionalHeaders);
+        }
+        return bundle;
+    }
+
+    /**
+     * Create the testbundles in the tempdirectory
+     */
+    private void setupSampleData() throws Exception {
+        BUNDLE1 = generateBundle(FileUtils.createTempFile(m_tempDirectory), null, "Bundle1", "1.0.0", null);
+        BUNDLE3 = generateBundle(FileUtils.createTempFile(m_tempDirectory), null, "Bundle3", "3.0.0", null);
+        BUNDLE4 = generateBundle(FileUtils.createTempFile(m_tempDirectory), null, "Bundle4", "4.0.0", null);
+        BUNDLE4_1 = generateBundle(FileUtils.createTempFile(m_tempDirectory), null, "Bundle4", "4.1.0", null);
+        BUNDLE5 = generateBundle(FileUtils.createTempFile(m_tempDirectory), null, "Bundle5", "5.0.0", null);
+        BUNDLE3_2 = generateBundle(FileUtils.createTempFile(m_tempDirectory), null, "Bundle3", "3.0.0", null);
+        BUNDLE4_2 = generateBundle(FileUtils.createTempFile(m_tempDirectory), null, "Bundle4", "5.0.0", null);
+
+        Map<String, String> attr = new HashMap<String, String>();
+        attr.put(DeploymentArtifact.DIRECTIVE_ISCUSTOMIZER, "true");
+        RESOURCEPROCESSOR1 = generateBundle(FileUtils.createTempFile(m_tempDirectory), attr, "Autoconf", "1.0.0", null);
+        attr = new HashMap<String, String>();
+        attr.put(DeploymentArtifact.DIRECTIVE_KEY_PROCESSORID, "my.processor.pid");
+        ARTIFACT1 = new ArtifactDataImpl(FileUtils.createTempFile(m_tempDirectory).toURI().toURL(), attr, false);
+    }
+
+    private String generateValidTestXml() {
+        Document doc = null;
+        try {
+            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
+            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
+            doc = docBuilder.newDocument();
+        }
+        catch (ParserConfigurationException e) {
+            // Should not happen
+            e.printStackTrace();
+        }
+
+        // create the root element
+        Element root = doc.createElement("repository");
+        doc.appendChild(root);
+
+        // create the versions element
+        Element versions = doc.createElement("deploymentversions");
+        root.appendChild(versions);
+
+        // create deployment versions
+        versions.appendChild(generateDeploymentVersion(doc, GATEWAY, VERSION1, new String[] {BUNDLE1.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE1.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE1.getVersion()}));
+        versions.appendChild(generateDeploymentVersion(doc, MULTIPLEVERSIONGATEWAY, VERSION1, new String[] {BUNDLE3.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE3.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE3.getVersion()}, new String[] {BUNDLE4.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE4.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE4.getVersion()}));
+        versions.appendChild(generateDeploymentVersion(doc, MULTIPLEVERSIONGATEWAY, VERSION2, new String[] {BUNDLE4_1.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE4_1.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE4_1.getVersion()}, new String[] { BUNDLE5.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE5.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE5.getVersion()}));
+        versions.appendChild(generateDeploymentVersion(doc, MULTIPLEVERSIONGATEWAY, VERSION3 , new String[] {BUNDLE4.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE4.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE4.getVersion()}));
+        versions.appendChild(generateDeploymentVersion(doc, MULTIPLEVERSIONGATEWAY, VERSION4, new String[] {BUNDLE3_2.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE3_2.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE3_2.getVersion()}, new String[] { BUNDLE4_2.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE4_2.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE4_2.getVersion()}));
+        //Add versions with special characters like ' " < >
+        versions.appendChild(generateDeploymentVersion(doc, "'",VERSION1, new String[] {BUNDLE1.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE1.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE1.getVersion()}));
+        versions.appendChild(generateDeploymentVersion(doc, "\"",VERSION2, new String[] {BUNDLE1.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE1.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE1.getVersion()}));
+        versions.appendChild(generateDeploymentVersion(doc, "gateway'\"",VERSION3, new String[] {BUNDLE1.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE1.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE1.getVersion()}));
+        versions.appendChild(generateDeploymentVersion(doc, " '''' \"\"\"\" ", VERSION4, new String[] {BUNDLE1.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE1.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE1.getVersion()}));
+        versions.appendChild(generateDeploymentVersion(doc, "myGateway", "1'0'0", new String[] {BUNDLE1.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE1.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE1.getVersion()}));
+
+        //Add a valid deployment version (5.0.0) with no bundle urls (empty package)
+        versions.appendChild(generateDeploymentVersion(doc, EMPTYVERSIONGATEWAY, VERSION1, new String[] {BUNDLE1.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE1.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE1.getVersion()}));
+        versions.appendChild(generateDeploymentVersion(doc, EMPTYVERSIONGATEWAY, VERSION2));
+
+        versions.appendChild(generateDeploymentVersion(doc, RESOURCEGATEWAY, VERSION1, new String[] {BUNDLE1.getUrl().toString(), BundleHelper.KEY_SYMBOLICNAME, BUNDLE1.getSymbolicName(), BundleHelper.KEY_VERSION, BUNDLE1.getVersion()}, new String[] {RESOURCEPROCESSOR1.getUrl().toString(), DeploymentArtifact.DIRECTIVE_ISCUSTOMIZER, "true", BundleHelper.KEY_SYMBOLICNAME, RESOURCEPROCESSOR1.getSymbolicName(), BundleHelper.KEY_VERSION, RESOURCEPROCESSOR1.getVersion()}, new String[] {ARTIFACT1.getUrl().toString(), DeploymentArtifact.DIRECTIVE_KEY_PROCESSORID, "my.processor.pid"}));
+
+        // transform the document to string
+        TransformerFactory tFactory = TransformerFactory.newInstance();
+        Transformer transformer = null;
+        StringWriter sw = null;
+        try {
+            transformer = tFactory.newTransformer();
+            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+            transformer.setOutputProperty(OutputKeys.INDENT, "no");
+            DOMSource source = new DOMSource(doc);
+            sw = new StringWriter();
+            StreamResult result = new StreamResult(sw);
+            transformer.transform(source, result);
+        }
+        catch (TransformerConfigurationException e) {
+            // Should not happen
+            e.printStackTrace();
+        }
+        catch (TransformerException e) {
+            // Should not happen
+            e.printStackTrace();
+        }
+
+        return sw.toString();
+    }
+
+    /**
+     * Helper method to create the description of a deploymentpacakge with given data.
+     * @param doc The document to add the version to.
+     * @param gatewayText The gatewayID in the deploymentversion.
+     * @param versionText The version in the deploymentversion.
+     * @param data An array of data for the deployment artifact. [0] is the url, and each following item is
+     * first a directive key, and a directive value. For example,<br>
+     * <code>new String[] { "http://mybundle", "somedirective", "somevalue" }</code>
+     * @return
+     */
+    private Node generateDeploymentVersion(Document doc, String gatewayText, String versionText, String[]... data) {
+        Element deploymentversion = doc.createElement(DEPLOYMENTVERSION_TAG);
+        Element attr = doc.createElement(ATTRIBUTES_TAG);
+        deploymentversion.appendChild(attr);
+
+        //Create and add gatewayTag
+        Element elem = null;
+        elem = doc.createElement(GATEWAYID_TAG);
+        elem.setTextContent(gatewayText);
+        attr.appendChild(elem);
+
+        //Create and add versionTag
+        elem = doc.createElement(VERSION_TAG);
+        elem.setTextContent(versionText);
+        attr.appendChild(elem);
+
+        //Create and add empty tagsTag to deploymentversion
+        elem = doc.createElement(TAGS_TAG);
+        deploymentversion.appendChild(elem);
+
+        // create and add bundlesTag
+        elem = doc.createElement(ARTIFACTS_TAG);
+        for (String[] s : data) {
+            Element artifact = doc.createElement(ARTIFACT_TAG);
+            Element url = doc.createElement(URL_TAG);
+            url.setTextContent(s[0]);
+            artifact.appendChild(url);
+            Element directives = doc.createElement(DIRECTIVES_TAG);
+            for (int i = 1; i < s.length; i += 2) {
+                Element directive = doc.createElement(s[i]);
+                directive.setTextContent(s[i+1]);
+                directives.appendChild(directive);
+            }
+            artifact.appendChild(directives);
+            elem.appendChild(artifact);
+        }
+
+        deploymentversion.appendChild(elem);
+
+        return deploymentversion;
+    }
+
+    /**
+     * Without any checked in data, we should just get back no version,
+     * but the provider should not crash.
+     * @throws IOException
+     */
+    @Test(groups = { UNIT })
+    public void testEmptyRepository() throws IOException {
+        Repository mock = new MockDeploymentRepository("", null);
+        TestUtils.configureObject(m_backend, Repository.class, mock);
+
+        List<String> versions = m_backend.getVersions(GATEWAY);
+        assert versions.size() == 0 : "From an empty repository, we should get 0 versions, but we get " + versions.size();
+    }
+
+
+    /**
+     * See if the getVersions() methods normal output works
+     */
+    @Test(groups = { UNIT })
+    public void testGetVersion() throws IOException {
+        List<String> versions = m_backend.getVersions(GATEWAY);
+        assert versions.size() == 1 : "Expected one version to be found, but found " + versions.size();
+        assert versions.get(0).equals(VERSION1) : "Expected version " + VERSION1 + " but found " + versions.get(0);
+    }
+
+    /**
+     * Test the getVersions method with an illegal version (not in org.osgi.framework.Version format)
+     */
+    @Test(groups = { UNIT })
+    public void testIllegalVersion() throws IOException {
+        // an illegal version should be silently ignored
+        List<String> versions = m_backend.getVersions(INVALIDVERSIONGATEWAY);
+        assert versions.isEmpty() : "Expected no versions to be found, but found " + versions.size();
+    }
+
+    /**
+     * Test with multiple versions. It expects all versions in an ascending order.
+     */
+    @Test(groups = { UNIT })
+    public void testMultipleVersions() throws IOException {
+        List<String> versions = m_backend.getVersions(MULTIPLEVERSIONGATEWAY);
+        assert versions.size() == 4 : "Expected three version to be found, but found " + versions.size();
+        // all versions should be in ascending order
+        assert versions.get(0).equals(VERSION1) : "Expected version " + VERSION1 + " but found " + versions.get(0);
+        assert versions.get(1).equals(VERSION2) : "Expected version " + VERSION2 + " but found " + versions.get(1);
+        assert versions.get(2).equals(VERSION3) : "Expected version " + VERSION3 + " but found " + versions.get(2);
+        assert versions.get(3).equals(VERSION4) : "Expected version " + VERSION4 + " but found " + versions.get(3);
+    }
+
+    /**
+     * Test the getBundleData for a single version, returning a single bundle
+     */
+    @Test(groups = { UNIT })
+    public void testSingleBundleSingleVersionBundleData() throws IOException {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(GATEWAY, VERSION1);
+        assert bundleData.size() == 1 : "Expected one bundle to be found, but found " + bundleData.size();
+        assert bundleData.contains(BUNDLE1) : "Expected to find bundle " + BUNDLE1.getSymbolicName();
+    }
+
+    /**
+     * Test the getBundleData for a single version, returning a multiple bundles
+     */
+    @Test(groups = { UNIT })
+    public void testMultipleBundleSingleVersionBundleData() throws IOException {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION1);
+        assert bundleData.size() == 2 : "Expected two bundle to be found, but found " + bundleData.size();
+        assert bundleData.contains(BUNDLE3) : "Expected to find bundle " + BUNDLE3.getSymbolicName();
+        assert bundleData.contains(BUNDLE4) : "Expected to find bundle " + BUNDLE4.getSymbolicName();
+    }
+
+    /**
+     * Test the getBundleData with an illegal version (i.e. a version that doesn't exist)
+     */
+    @Test(groups = { UNIT })
+    public void testInvalidVersionBundleData() throws IOException {
+        try {
+            m_backend.getBundleData(GATEWAY, INVALIDVERSION);
+            assert false : "Expected an error because version " + INVALIDVERSION + " doesn't exist for gateway" + GATEWAY;
+        } catch (IllegalArgumentException iae) {
+            // expected, because the version doesn't exist
+        }
+    }
+
+    /**
+     * Test the getBundleData with an illegal gateway (i.e. a gateway that doesn't exist)
+     */
+    @Test(groups = { UNIT })
+    public void testInvalidGatewayBundleData() throws IOException {
+        try {
+            m_backend.getBundleData(INVALIDVERSIONGATEWAY, VERSION1);
+            assert false : "Expected an error because version " + VERSION1 + " doesn't exist for gateway" + INVALIDVERSIONGATEWAY;
+        } catch (IllegalArgumentException iae) {
+            // expected, because the version doesn't exist
+        }
+    }
+    /**
+     * Test the getBundleData for a two versions, returning a single bundle that hasn't changed
+     */
+    @Test(groups = { UNIT })
+    public void testSingleUnchangedBundleMultipleVersions() throws IOException {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(GATEWAY, VERSION1, VERSION1);
+        assert bundleData.size() == 1 : "Expect one bundle, got " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            assert !data.hasChanged() : "The data should not have been changed.";
+        }
+    }
+
+    /**
+     * Test the getBundleData for a two versions, returning multiple bundles that haven't changed
+     */
+    @Test(groups = { UNIT })
+    public void testMultipleBundlesMultipleVersions() throws IOException {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION1, VERSION1);
+        assert bundleData.size() == 2 : "Expected two bundle to be found, but found " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            assert !data.hasChanged() : "The data should not have been changed.";
+        }
+    }
+
+    /**
+     * Test the getBundleData for a two versions, where in the second version a bundle is removed
+     */
+    @Test(groups = { UNIT })
+    public void testRemovedBundleMultipleVersions() throws IOException {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION1, VERSION3);
+        assert bundleData.size() == 1 : "Expected one bundle to be found, but found " + bundleData.size();
+    }
+
+    /**
+     * Test the getBundleData for a two versions, where in the second version a bundle is added
+     */
+    @Test(groups = { UNIT })
+    public void testAddedBundleMultipleVersions() throws IOException {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION3, VERSION1);
+        assert bundleData.size() == 2 : "Expected two bundle to be found, but found " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            if (data.getSymbolicName().equals("Bundle4")) {
+                assert !data.hasChanged() : "The data (Bundle4) should not have been changed.";
+            }
+            else {
+                assert data.hasChanged() : "The data (Bundle3) should have been changed.";
+            }
+        }
+    }
+
+    /**
+     * Test the getBundleData for a two versions, where in the second version one bundle has changed and another hasn't
+     */
+    @Test(groups = { UNIT })
+    public void testSingleChangedBundleMultipleVersions() throws IOException {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION1, VERSION4);
+        assert bundleData.size() == 2 : "Expected two bundles to be found, but found " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            if (data.equals(BUNDLE3_2)) {
+                assert !data.hasChanged() : "The data should not have been changed.";
+            } else if (data.equals(BUNDLE4_2)) {
+                assert data.hasChanged() : "The data should have been changed.";
+            } else {
+                assert false : "Unknown bundle found";
+            }
+        }
+    }
+
+    /**
+     * Test the getBundleData for a two versions, where two bundles have changed
+     */
+    @Test(groups = { UNIT })
+    public void testMultipleChangedBundlesMultipleVersions() throws IOException {
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(MULTIPLEVERSIONGATEWAY, VERSION1, VERSION2);
+        assert bundleData.size() == 2 : "Expected two bundles to be found, but found " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            if (data.equals(BUNDLE4_1)) {
+                assert data.hasChanged() : "The data should have been changed.";
+            } else if (data.equals(BUNDLE5)) {
+                assert data.hasChanged() : "The data should have been changed.";
+            } else {
+                assert false : "Unknown bundle found";
+            }
+        }
+    }
+
+    /**
+     * See if the getVersions() methods normal output works with literals ' and "
+     */
+    @Test(groups = { UNIT })
+    public void testGetLiteralGatewayVersion() throws IOException {
+        List<String> versions = m_backend.getVersions("'");
+        assert versions.size() == 1 : "Expected one version to be found, but found " + versions.size();
+        assert versions.get(0).equals(VERSION1) : "Expected version " + VERSION1 + " but found " + versions.get(0);
+
+        versions = m_backend.getVersions("\"");
+        assert versions.size() == 1 : "Expected one version to be found, but found " + versions.size();
+        assert versions.get(0).equals(VERSION2) : "Expected version " + VERSION2 + " but found " + versions.get(0);
+
+        versions = m_backend.getVersions("gateway'\"");
+        assert versions.size() == 1 : "Expected one version to be found, but found " + versions.size();
+        assert versions.get(0).equals(VERSION3) : "Expected version " + VERSION3 + " but found " + versions.get(0);
+
+        versions = m_backend.getVersions(" '''' \"\"\"\" ");
+        assert versions.size() == 1 : "Expected one version to be found, but found " + versions.size();
+        assert versions.get(0).equals(VERSION4) : "Expected version " + VERSION4 + " but found " + versions.get(0);
+    }
+
+    /**
+     * Test the getBundleData for an empty version (no bundle URLS are included)
+     */
+    @Test(groups = { UNIT })
+    public void testEmptyDeploymentVersion() throws IOException {
+        // get the version number
+        List<String> versions = m_backend.getVersions(EMPTYVERSIONGATEWAY);
+        assert versions.size() == 2 : "Expected two version to be found, but found " + versions.size();
+
+        //get the (empty bundle data version (2))
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(EMPTYVERSIONGATEWAY, VERSION2);
+        assert bundleData.size() == 0 : "Expected no bundles to be found, but got: " + bundleData.size();
+
+        //check an update from and to an empty version
+        Collection<ArtifactData> bundleData2 = m_backend.getBundleData(EMPTYVERSIONGATEWAY, VERSION1, VERSION2);
+        assert bundleData2.size() == 0 : "Expected no bundles to be found, but got: " + bundleData2.size();
+
+        Collection<ArtifactData> bundleData3 = m_backend.getBundleData(EMPTYVERSIONGATEWAY, VERSION2, VERSION1);
+        assert bundleData3.size() == 1 : "Expected one bundle to be found, but got: " + bundleData3.size();
+        assert bundleData3.iterator().next().getVersion().equals("1.0.0");
+    }
+
+
+    /**
+     * See if a version with a literal is parsed correct and ignored.
+     */
+    @Test(groups = { UNIT })
+    public void testGetLiteralGatewayIllegalVersion() throws IOException {
+        List<String> versions = m_backend.getVersions("myGateway");
+        assert versions.size() == 0 : "Expected no versions to be found, but found " + versions.size();
+    }
+
+    /**
+     * Test the getBundleData with some resources.
+     */
+    @Test(groups = { UNIT })
+    public void testBundleDataWithResources() throws IOException {
+        List<String> versions = m_backend.getVersions(RESOURCEGATEWAY);
+        assert versions.size() == 1 : "Expected two version to be found, but found " + versions.size();
+
+        Collection<ArtifactData> bundleData = m_backend.getBundleData(RESOURCEGATEWAY, versions.get(0));
+
+        assert bundleData.size() == 3 : "Expected three bundle to be found, but found " + bundleData.size();
+        Iterator<ArtifactData> it = bundleData.iterator();
+        while(it.hasNext()) {
+            ArtifactData data = it.next();
+            if (data.equals(BUNDLE1)) {
+                // fine
+            } else if (data.equals(RESOURCEPROCESSOR1)) {
+                // fine
+            } else if (data.equals(ARTIFACT1)) {
+                // fine
+            } else {
+                assert false : "Unknown bundle found";
+            }
+        }
+    }
+
+    @Test(groups = { UNIT })
+    public void testArtifactDataManifestGeneration() {
+        Attributes B1NoFixpack = BUNDLE1.getManifestAttributes(false);
+        assert B1NoFixpack.size() == 2;
+        for (Map.Entry<Object, Object> entry : B1NoFixpack.entrySet()) {
+            if (entry.getKey().toString().equals(Constants.BUNDLE_SYMBOLICNAME)) {
+                assert entry.getValue().toString().equals(BUNDLE1.getSymbolicName());
+            }
+            else if (entry.getKey().toString().equals(Constants.BUNDLE_VERSION)) {
+                assert entry.getValue().toString().equals(BUNDLE1.getVersion());
+            }
+            else {
+                assert false : "Unknown header found: " + entry.getKey().toString();
+            }
+        }
+
+        Attributes B1Fixpack = BUNDLE1.getManifestAttributes(true);
+        assert B1Fixpack.size() == 3;
+        for (Map.Entry<Object, Object> entry : B1Fixpack.entrySet()) {
+            if (entry.getKey().toString().equals(Constants.BUNDLE_SYMBOLICNAME)) {
+                assert entry.getValue().toString().equals(BUNDLE1.getSymbolicName());
+            }
+            else if (entry.getKey().toString().equals(Constants.BUNDLE_VERSION)) {
+                assert entry.getValue().toString().equals(BUNDLE1.getVersion());
+            }
+            else if (entry.getKey().toString().equals("DeploymentPackage-Missing")) {
+                assert entry.getValue().toString().equals("true");
+            }
+            else {
+                assert false : "Unknown header found: " + entry.getKey().toString();
+            }
+        }
+
+        Attributes R1NoFixpack = RESOURCEPROCESSOR1.getManifestAttributes(false);
+        assert R1NoFixpack.size() == 3 : "We expect 3 headers, but find " + R1NoFixpack.size();
+        for (Map.Entry<Object, Object> entry : R1NoFixpack.entrySet()) {
+            if (entry.getKey().toString().equals(Constants.BUNDLE_SYMBOLICNAME)) {
+                assert entry.getValue().toString().equals(RESOURCEPROCESSOR1.getSymbolicName());
+            }
+            else if (entry.getKey().toString().equals(Constants.BUNDLE_VERSION)) {
+                assert entry.getValue().toString().equals(RESOURCEPROCESSOR1.getVersion());
+            }
+            else if (entry.getKey().toString().equals(DeploymentArtifact.DIRECTIVE_ISCUSTOMIZER)) {
+                assert entry.getValue().toString().equals("true");
+            }
+            else {
+                assert false : "Unknown header found: " + entry.getKey().toString();
+            }
+        }
+
+        Attributes A1NoFixpack = ARTIFACT1.getManifestAttributes(false);
+        assert A1NoFixpack.size() == 1 : "We expect 1 headers, but find " + A1NoFixpack.size();
+        for (Map.Entry<Object, Object> entry : A1NoFixpack.entrySet()) {
+            if (entry.getKey().toString().equals(DeploymentArtifact.DIRECTIVE_KEY_PROCESSORID)) {
+                assert entry.getValue().toString().equals("my.processor.pid");
+            }
+            else {
+                assert false : "Unknown header found: " + entry.getKey().toString();
+            }
+        }
+
+
+    }
+
+
+    @AfterTest(alwaysRun = true)
+    public void tearDown() throws Exception {
+        FileUtils.removeDirectoryWithContent(m_tempDirectory);
+    }
+
+
+}

Added: incubator/ace/trunk/test/src/net/luminis/liq/deployment/servlet/DeploymentServletTest.java
URL: http://svn.apache.org/viewvc/incubator/ace/trunk/test/src/net/luminis/liq/deployment/servlet/DeploymentServletTest.java?rev=788992&view=auto
==============================================================================
--- incubator/ace/trunk/test/src/net/luminis/liq/deployment/servlet/DeploymentServletTest.java (added)
+++ incubator/ace/trunk/test/src/net/luminis/liq/deployment/servlet/DeploymentServletTest.java Sat Jun 27 15:53:04 2009
@@ -0,0 +1,216 @@
+package net.luminis.liq.deployment.servlet;
+
+import static net.luminis.liq.test.utils.TestUtils.UNIT;
+import static net.luminis.liq.test.utils.TestUtils.configureObject;
+import static net.luminis.liq.test.utils.TestUtils.createMockObjectAdapter;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import net.luminis.liq.deployment.provider.ArtifactData;
+import net.luminis.liq.deployment.provider.DeploymentProvider;
+import net.luminis.liq.deployment.streamgenerator.StreamGenerator;
+
+import org.osgi.service.log.LogService;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class DeploymentServletTest {
+
+    private DeploymentServlet m_servlet;
+
+    private HttpServletRequest m_request;
+    private String m_requestCurrentParameter;
+    private String m_requestPathInfo;
+
+    private HttpServletResponse m_response;
+    private ByteArrayOutputStream m_responseOutputStream;
+    private int m_responseStatus;
+
+    private DeploymentProvider m_provider;
+    private List<String> m_providerVersions;
+
+    private StreamGenerator m_generator;
+    private InputStream m_generatorResultStream;
+    private String m_generatorId;
+    private String m_generatorFromVersion;
+    private String m_generatorToVersion;
+
+
+    @BeforeMethod(alwaysRun = true)
+    protected void setUp() throws Exception {
+        // resets variables that store results of tests
+        m_generatorResultStream = null;
+        m_generatorId = null;
+        m_generatorFromVersion = null;
+        m_generatorToVersion = null;
+        m_providerVersions = null;
+
+        // create mock stream generator
+        m_generator = new StreamGenerator() {
+            public InputStream getDeploymentPackage(String id, String version) throws IOException {
+                if (m_generatorResultStream == null) {
+                    throw new IOException("No data for " + id + " " + version);
+                }
+                m_generatorId = id;
+                m_generatorToVersion = version;
+                return m_generatorResultStream;
+            }
+            public InputStream getDeploymentPackage(String id, String fromVersion, String toVersion) throws IOException {
+                if (m_generatorResultStream == null) {
+                    throw new IOException("No delta for " + id + " " + fromVersion + " " + toVersion);
+                }
+                m_generatorId = id;
+                m_generatorFromVersion = fromVersion;
+                m_generatorToVersion = toVersion;
+                return m_generatorResultStream;
+            }
+        };
+
+
+        // create mock deployment provider
+        m_provider = new DeploymentProvider() {
+            public List<ArtifactData> getBundleData(String gatewayId, String version) throws IllegalArgumentException {
+                return null; // not used
+            }
+            public List<ArtifactData> getBundleData(String gatewayId, String versionFrom, String versionTo) throws IllegalArgumentException {
+                return null; // not used
+            }
+            public List<String> getVersions(String gatewayId) throws IllegalArgumentException {
+                if (m_providerVersions == null) {
+                    throw new IllegalArgumentException();
+                }
+                return m_providerVersions;
+            }
+        };
+
+        // create a HttpServletRequest mock object
+        m_request = createMockObjectAdapter(HttpServletRequest.class, new Object() {
+            @SuppressWarnings("unused")
+            public String getParameter(String param) {
+                if (param.equals(DeploymentServlet.CURRENT)) {
+                    return m_requestCurrentParameter;
+                }
+                return null;
+            }
+            @SuppressWarnings("unused")
+            public String getPathInfo() {
+                return m_requestPathInfo;
+//                "/" + m_requestGatewayID + "/versions/" + m_requestRequestedVersion;
+            }
+        });
+
+        // create a HttpServletResponse mock object
+        m_response = createMockObjectAdapter(HttpServletResponse.class, new Object() {
+            @SuppressWarnings("unused")
+            public ServletOutputStream getOutputStream() {
+                return new ServletOutputStream() {
+                    @Override
+                    public void write(int b) throws IOException {
+                        m_responseOutputStream.write(b);
+                    }
+                };
+            }
+            @SuppressWarnings("unused")
+            public void sendError(int status) {
+                m_responseStatus = status;
+            }
+            @SuppressWarnings("unused")
+            public void sendError(int status, String desc) {
+                sendError(status);
+            }
+        });
+
+        m_responseStatus = HttpServletResponse.SC_OK;
+        m_responseOutputStream = new ByteArrayOutputStream();
+
+        // create the instance to test
+        m_servlet = new DeploymentServlet();
+        configureObject(m_servlet, LogService.class);
+        configureObject(m_servlet, StreamGenerator.class, m_generator);
+        configureObject(m_servlet, DeploymentProvider.class, m_provider);
+
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown() throws Exception {
+    }
+
+    @Test(groups = { UNIT })
+    public void getDataForExistingGateway() throws Exception {
+        m_requestPathInfo = "/GW1/versions/2.0.0";
+        m_generatorResultStream = new ByteArrayInputStream(new byte[10]);
+        m_providerVersions = new ArrayList<String>();
+        m_providerVersions.add("2.0.0");
+        m_servlet.doGet(m_request, m_response);
+
+        // make sure the request went fine
+        assert m_responseStatus == HttpServletResponse.SC_OK : "We should have got response code " + HttpServletResponse.SC_OK + " and we got " + m_responseStatus;
+        assert m_responseOutputStream.size() == 10 : "We should have got a (dummy) deployment package of 10 bytes.";
+        assert m_generatorId.equals("GW1") : "Wrong gateway ID.";
+        assert m_generatorToVersion.equals("2.0.0") : "Wrong version.";
+    }
+
+    @Test(groups = { UNIT })
+    public void getFixPackageForExistingGateway() throws Exception {
+        m_requestPathInfo = "/GW1/versions/2.0.0";
+        m_requestCurrentParameter = "1.0.0";
+        m_generatorResultStream = new ByteArrayInputStream(new byte[10]);
+        m_providerVersions = new ArrayList<String>();
+        m_providerVersions.add("2.0.0");
+        m_servlet.doGet(m_request, m_response);
+
+        // make sure the request went fine
+        assert m_responseStatus == HttpServletResponse.SC_OK : "We should have got response code " + HttpServletResponse.SC_OK + " and we got " + m_responseStatus;
+        assert m_responseOutputStream.size() == 10 : "We should have got a (dummy) deployment package of 10 bytes.";
+        assert m_generatorId.equals("GW1") : "Wrong gateway ID.";
+        assert m_generatorToVersion.equals("2.0.0") : "Wrong version.";
+        assert m_generatorFromVersion.equals("1.0.0") : "Wrong current version.";
+    }
+
+    @Test(groups = { UNIT })
+    public void getDataForNonExistingGateway() throws Exception {
+        m_requestPathInfo = "/GW?/versions/2.0.0";
+        m_servlet.doGet(m_request, m_response);
+        assert m_responseStatus == HttpServletResponse.SC_NOT_FOUND : "We should have gotten response code" + HttpServletResponse.SC_NOT_FOUND + ", actual code: " + m_responseStatus;
+    }
+
+    @Test(groups = { UNIT })
+    public void getDataForBadURL() throws Exception {
+        HttpServletRequest garbage = createMockObjectAdapter(HttpServletRequest.class, new Object() {
+            @SuppressWarnings("unused")
+            public String getPathInfo() {
+                return "/";
+            }
+        });
+        m_servlet.doGet(garbage, m_response);
+        assert m_responseStatus == HttpServletResponse.SC_BAD_REQUEST : "We should have gotten response code " + HttpServletResponse.SC_NOT_FOUND + ", actual code: " + m_responseStatus;
+    }
+
+
+    @Test(groups = { UNIT })
+    public void getVersionsExistingGateway() throws Exception {
+        m_requestPathInfo = "/GW1/versions";
+        m_providerVersions = new ArrayList<String>();
+        m_providerVersions.add("2.0.0");
+        m_servlet.doGet(m_request, m_response);
+        assert "2.0.0\n".equals(m_responseOutputStream.toString()) : "Expected to get version 2.0.0 in the response";
+    }
+
+    @Test(groups = { UNIT })
+    public void getVersionsNonExistingGateway() throws Exception {
+        m_requestPathInfo = "/GW1/versions";
+        m_servlet.doGet(m_request, m_response);
+        assert "".equals(m_responseOutputStream.toString()) : "Expected to get an empty response";
+    }
+
+}

Added: incubator/ace/trunk/test/src/net/luminis/liq/deployment/streamgenerator/impl/StreamTest.java
URL: http://svn.apache.org/viewvc/incubator/ace/trunk/test/src/net/luminis/liq/deployment/streamgenerator/impl/StreamTest.java?rev=788992&view=auto
==============================================================================
--- incubator/ace/trunk/test/src/net/luminis/liq/deployment/streamgenerator/impl/StreamTest.java (added)
+++ incubator/ace/trunk/test/src/net/luminis/liq/deployment/streamgenerator/impl/StreamTest.java Sat Jun 27 15:53:04 2009
@@ -0,0 +1,281 @@
+package net.luminis.liq.deployment.streamgenerator.impl;
+
+import static net.luminis.liq.test.utils.TestUtils.UNIT;
+import static net.luminis.liq.test.utils.TestUtils.BROKEN;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.HashSet;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarInputStream;
+import java.util.jar.Manifest;
+
+import net.luminis.liq.deployment.provider.DeploymentProvider;
+import net.luminis.liq.test.utils.TestUtils;
+import net.luminis.liq.test.utils.deployment.TestProvider;
+
+import org.osgi.service.log.LogService;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+/**
+ * Unit tests for the deployment admin stream.
+ */
+public class StreamTest {
+    private static final int COPY_BUFFER_SIZE = 4096;
+
+    private StreamGeneratorImpl m_generator;
+
+    private TestProvider m_provider;
+
+    @BeforeTest(alwaysRun = true)
+    protected void setUp() throws Exception {
+        m_generator = new StreamGeneratorImpl();
+        m_provider = new TestProvider();
+        // IMPORTANT NOTE: if you run this test with Eclipse, a different base path is used
+        // than when you run the tests via the console. So this test will only succeed when
+        // ran in a console.
+        m_provider.addData("A1.jar", "A1", new URL("file:ext/javax.servlet.jar"), "1.0.0", true);
+        m_provider.addData("A2.jar", "A2", new URL("file:ext/javax.servlet.jar"), "1.0.0", false);
+        m_provider.addData("A3.jar", "A3", new URL("file:ext/javax.servlet.jar"), "1.0.0", true);
+        TestUtils.configureObject(m_generator, DeploymentProvider.class, m_provider);
+        TestUtils.configureObject(m_generator, LogService.class);
+    }
+
+    public static void main(String[] args) {
+        final InputStream[] streams = new InputStream[300];
+        for (int i = 1; i <= 250; i++) {
+            final String id = "gateway-" + i;
+            try {
+                streams[i - 1] = new URL("http://127.0.0.1:8080/data/" + id + "/versions/1.0.0").openStream();
+            }
+            catch (IOException ex) {
+                ex.printStackTrace();
+            }
+        }
+        new Thread() {
+            @Override
+            public void run() {
+                int done = 0;
+                while (done < 50) {
+                    for (int i = 0; i < 50; i++) {
+                        try {
+                            int in = streams[i].read();
+                            if (in == -1) {
+                                System.out.println(1);
+                                done++;
+                            }
+                        }
+                        catch (IOException e) {
+                            // TODO Auto-generated catch block
+                            e.printStackTrace();
+                        }
+                    }
+                }
+            }
+        }.start();
+        new Thread() {
+            @Override
+            public void run() {
+                int done = 0;
+                while (done < 50) {
+                    for (int i = 50; i < 100; i++) {
+                        try {
+                            int in = streams[i].read();
+                            if (in == -1) {
+                                System.out.println(2);
+                                done++;
+                            }
+                        }
+                        catch (IOException e) {
+                            // TODO Auto-generated catch block
+                            e.printStackTrace();
+                        }
+                    }
+                }
+            }
+        }.start();
+        new Thread() {
+            @Override
+            public void run() {
+                int done = 0;
+                while (done < 50) {
+                    for (int i = 100; i < 150; i++) {
+                        try {
+                            int in = streams[i].read();
+                            if (in == -1) {
+                                System.out.println(3);
+                                done++;
+                            }
+                        }
+                        catch (IOException e) {
+                            // TODO Auto-generated catch block
+                            e.printStackTrace();
+                        }
+                    }
+                }
+            }
+        }.start();
+        new Thread() {
+            @Override
+            public void run() {
+                int done = 0;
+                while (done < 50) {
+                    for (int i = 150; i < 200; i++) {
+                        try {
+                            int in = streams[i].read();
+                            if (in == -1) {
+                                System.out.println(4);
+                                done++;
+                            }
+                        }
+                        catch (IOException e) {
+                            // TODO Auto-generated catch block
+                            e.printStackTrace();
+                        }
+                    }
+                }
+            }
+        }.start();
+        new Thread() {
+            @Override
+            public void run() {
+                int done = 0;
+                while (done < 50) {
+                    for (int i = 200; i < 250; i++) {
+                        try {
+                            int in = streams[i].read();
+                            if (in == -1) {
+                                System.out.println(5);
+                                done++;
+                            }
+                        }
+                        catch (IOException e) {
+                            // TODO Auto-generated catch block
+                            e.printStackTrace();
+                        }
+                    }
+                }
+            }
+        }.start();
+        new Thread() {
+            @Override
+            public void run() {
+                int done = 0;
+                while (done < 50) {
+                    for (int i = 250; i < 300; i++) {
+                        try {
+                            if (streams[i] == null) {
+                                streams[i] = new URL("http://127.0.0.1:8080/data/gateway-" + (i + 1) + "/versions/1.0.0").openStream();
+                            }
+                            int in = streams[i].read();
+                            if (in == -1) {
+                                System.out.println(5);
+                                done++;
+                            }
+                        }
+                        catch (IOException e) {
+                            // TODO Auto-generated catch block
+                            e.printStackTrace();
+                        }
+                    }
+                }
+            }
+        }.start();
+    }
+
+    /**
+     * The specification requires the stream to be readable by JarInputStream (114.3) so make sure it is.
+     */
+    @Test(groups = { UNIT })
+    public void isJarInputStreamReadable() throws Exception {
+        isJarInputStreamReadable(new JarInputStream(m_generator.getDeploymentPackage("test", "1.0.0")), false);
+        isJarInputStreamReadable(new JarInputStream(m_generator.getDeploymentPackage("test", "0.0.0", "1.0.0")), true);
+    }
+
+    private void isJarInputStreamReadable(JarInputStream jis, boolean fixPackage) throws Exception {
+        assert jis != null : "We should have got an input stream for this deployment package.";
+        Manifest m = jis.getManifest();
+        assert m != null : "The stream should contain a valid manifest.";
+        Attributes att = m.getMainAttributes();
+        assert att.getValue("DeploymentPackage-SymbolicName").equals("test");
+        assert att.getValue("DeploymentPackage-Version").equals("1.0.0");
+        assert (fixPackage && att.getValue("DeploymentPackage-FixPack").equals("[0.0.0,1.0.0)")) || (att.getValue("DeploymentPackage-FixPack") == null);
+        HashSet<String> names = new HashSet<String>();
+        JarEntry e = jis.getNextJarEntry();
+        while (e != null) {
+            String name = e.getName();
+            names.add(name);
+            if (fixPackage && name.equals("A2.jar")) {
+                assert e.getAttributes().getValue("DeploymentPackage-Missing").equals("true");
+            }
+            // we could check the name here against the manifest
+            // and make sure we actually get what was promised
+            Attributes a = m.getAttributes(name);
+            assert a != null : "The stream should contain a named section for " + name + " in the manifest.";
+
+            byte[] buffer = new byte[COPY_BUFFER_SIZE];
+            int bytes = jis.read(buffer);
+            long size = 0;
+            while (bytes != -1) {
+                size += bytes;
+                bytes = jis.read(buffer);
+            }
+
+            // get the next entry, if any
+            e = jis.getNextJarEntry();
+        }
+        if (!fixPackage) {
+            assert names.size() == 3 : "The stream should have contained three resources.";
+        }
+        else {
+            assert names.size() == 2 : "The stream should have contained three resources";
+        }
+        assert names.contains("A1.jar") : "The stream should have contained a resource called A1.jar";
+        assert fixPackage ^ names.contains("A2.jar") : "The stream should have contained a resource called A2.jar";
+        assert names.contains("A3.jar") : "The stream should have contained a resource called A3.jar";
+    }
+
+    /**
+     * Test reading 100 streams sequentially.
+     */
+    @Test(groups = { UNIT, BROKEN })
+    public void hundredStreamsSequentially() throws Exception {
+        for (int i = 0; i < 100; i++) {
+            isJarInputStreamReadable();
+        }
+    }
+
+    private Exception m_failure;
+
+    /**
+     * Test reading 100 streams concurrently.
+     */
+    @Test(groups = { UNIT, BROKEN }) // marked broken after discussing it with Karl
+    public void hundredStreamsConcurrently() throws Exception {
+        ExecutorService e = Executors.newFixedThreadPool(5);
+        for (int i = 0; i < 10; i++) {
+            e.execute(new Runnable() {
+                public void run() {
+                    for (int i = 0; i < 10; i++) {
+                        try {
+                            isJarInputStreamReadable();
+                        }
+                        catch (Exception e) {
+                            m_failure = e;
+                        }
+                    }
+                }
+            });
+        }
+        e.shutdown();
+        e.awaitTermination(10, TimeUnit.SECONDS);
+
+        assert m_failure == null : "Test failed: " + m_failure.getLocalizedMessage();
+    }
+}

Added: incubator/ace/trunk/test/src/net/luminis/liq/deployment/task/DeploymentUpdateTaskTest.java
URL: http://svn.apache.org/viewvc/incubator/ace/trunk/test/src/net/luminis/liq/deployment/task/DeploymentUpdateTaskTest.java?rev=788992&view=auto
==============================================================================
--- incubator/ace/trunk/test/src/net/luminis/liq/deployment/task/DeploymentUpdateTaskTest.java (added)
+++ incubator/ace/trunk/test/src/net/luminis/liq/deployment/task/DeploymentUpdateTaskTest.java Sat Jun 27 15:53:04 2009
@@ -0,0 +1,226 @@
+package net.luminis.liq.deployment.task;
+
+import static net.luminis.liq.test.utils.TestUtils.UNIT;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+
+import net.luminis.liq.deployment.Deployment;
+import net.luminis.liq.deployment.task.DeploymentUpdateTask;
+import net.luminis.liq.discovery.Discovery;
+import net.luminis.liq.gateway.log.store.LogStore;
+import net.luminis.liq.identification.Identification;
+import net.luminis.liq.test.utils.TestUtils;
+
+import org.osgi.framework.Version;
+import org.osgi.service.log.LogService;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class DeploymentUpdateTaskTest {
+
+    private DeploymentUpdateTask m_deploymentTask;
+    private MockDeploymentService m_mockDeploymentService;
+
+    private static final Version m_version1 = new Version("1.0.0");
+    private static final Version m_version2 = new Version("2.0.0");
+    private static final Version m_version3 = new Version("3.0.0");
+
+    boolean m_correctVersionInstalled;
+    boolean m_installCalled;
+
+    @BeforeMethod(alwaysRun = true)
+    protected void setUp() throws Exception {
+        m_mockDeploymentService = new MockDeploymentService();
+        m_correctVersionInstalled = false;
+        m_installCalled = false;
+        m_deploymentTask = new DeploymentUpdateTask();
+        TestUtils.configureObject(m_deploymentTask, LogService.class);
+        TestUtils.configureObject(m_deploymentTask, Identification.class);
+        TestUtils.configureObject(m_deploymentTask, Discovery.class);
+        TestUtils.configureObject(m_deploymentTask, Deployment.class, m_mockDeploymentService);
+    }
+
+    @Test(groups = { UNIT })
+    public synchronized void testGetHighestLocalVersion() {
+        prepareMockEnvironment(new Version[] {m_version1, m_version2, m_version3}, null, null, null);
+        Version highestVersion = m_deploymentTask.getHighestLocalVersion();
+        assert highestVersion.equals(m_version3) : "Highest local version is incorrect, expected " + m_version3.toString() + " but got " + highestVersion.toString();
+    }
+
+    @Test(groups = { UNIT })
+    public synchronized void testGetHighestRemoteVersion() throws MalformedURLException, IOException {
+        URL[] urls = prepareMockEnvironment(null, new Version[] {m_version1, m_version2, m_version3}, null, null);
+        Version highestVersion = m_deploymentTask.getHighestRemoteVersion(urls[0]);
+        assert highestVersion.equals(m_version3) : "Highest remote version is incorrect, expected " + m_version3.toString() + " but got " + highestVersion.toString();
+    }
+
+    /**
+     * Helper method to setup the correct endpoints and deploymentservice based on the appropriate mock classes.
+     *
+     * @param localVersions The versions that should appear to be installed.
+     * @param remoteVersions The versions that should appear to be available remotely.
+     * @param expectedInstallVersion The version that is expected to be installed.
+     * @param malformedVersion Optional malformed version to be added to the remote versions.
+     *
+     * @return Array of two urls, element [0] is the controlEndpoint, element [1] is the dataEndpoint
+     */
+    private URL[] prepareMockEnvironment(Version[] localVersions, Version[] remoteVersions, Version expectedInstallVersion, String malformedVersion) {
+        if (localVersions == null) {
+            localVersions = new Version[]{};
+        }
+        if (remoteVersions == null) {
+            remoteVersions = new Version[]{};
+        }
+        if (expectedInstallVersion == null) {
+            expectedInstallVersion = Version.emptyVersion;
+        }
+        // mock installed versions
+        m_mockDeploymentService.setList(localVersions);
+
+        // mock versions available remotely through the control channel
+        MockURLConnection controlURLConnection = new MockURLConnection();
+        controlURLConnection.setVersions(remoteVersions, malformedVersion);
+
+        // mock version available remotely through the data channel
+        MockURLConnection dataURLConnection = new MockURLConnection();
+        dataURLConnection.setVersions(new Version[] {expectedInstallVersion}, null);
+        m_mockDeploymentService.setExpectedInstallVersion(expectedInstallVersion);
+
+        URL controlEndpoint = null;
+        URL dataEndpoint = null;
+        try {
+            // create endpoints based on mock classes
+            controlEndpoint = new URL(new URL("http://notmalformed"), "", new MockURLStreamHandler(controlURLConnection));
+            dataEndpoint = new URL(new URL("http://notmalformed"), "", new MockURLStreamHandler(dataURLConnection));
+        }
+        catch (MalformedURLException e) {
+            e.printStackTrace();
+        }
+        return new URL[] {controlEndpoint, dataEndpoint};
+    }
+    /**
+     * Mock implementation of <code>DeploymentService</code> that expects Version objects.
+     * The Version objects that are 'installed' can be mocked with the new <code>setList(Version[] objects)</code>
+     * method. The <code>install(Inputstream is)</code> method only checks if the call was expected by verifying the
+     * version matches the version set by the <code>setExpectedInstallVersion(Version v)</code> method. If so a boolean
+     * in the outer class is set to true.
+     */
+    private class MockDeploymentService implements Deployment {
+        Object[] m_objects = new Object[]{};
+        Version m_expectedInstallVersion = Version.emptyVersion;
+
+        public String getName(Object object) throws IllegalArgumentException {
+            return ((Version) object).toString();
+        }
+
+        public void setExpectedInstallVersion(Version version) {
+            m_expectedInstallVersion = version;
+        }
+
+        public Version getVersion(Object object) throws IllegalArgumentException {
+            return (Version) object;
+        }
+
+        public Object install(InputStream inputStream) throws Exception {
+            m_installCalled = true;
+            BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream));
+            String versionString = bufReader.readLine();
+            if (m_expectedInstallVersion.equals(new Version(versionString))) {
+                m_correctVersionInstalled = true;
+            }
+            return new Version(versionString);
+        }
+
+        public Object[] list() {
+            return m_objects;
+        }
+
+        public void setList(Version[] objects) {
+            m_objects = objects;
+        }
+
+    }
+
+    /**
+     * Mock implementation of <code>URLStreamHandler</code>. Will return the <code>URLConnection</code>
+     * supplied in the constructor instead when <code>openConnection(URL url)</code> is called.
+     */
+    private class MockURLStreamHandler extends URLStreamHandler {
+
+        private final URLConnection m_urlConnection;
+
+        public MockURLStreamHandler(URLConnection urlConnection) {
+            m_urlConnection = urlConnection;
+        }
+
+        @Override
+        protected URLConnection openConnection(URL url) throws IOException {
+            return m_urlConnection;
+        }
+    }
+
+    /**
+     * Mock implementation of <code>URLConnection</code>. Instead of returning an inputstream
+     * based on the URL it will return an inputstream based on the versions specified by the
+     * new <code>setVersions(Version[] versions)</code> method.
+     */
+    private class MockURLConnection extends URLConnection {
+        private ByteArrayInputStream m_inputStream = new ByteArrayInputStream(new byte[]{});
+
+        protected MockURLConnection() {
+            super(null);
+        }
+
+        @Override
+        public void connect() throws IOException {
+            // do nothing
+        }
+
+        @Override
+        public InputStream getInputStream() {
+            return m_inputStream;
+        }
+
+        public void setVersions(Version[] versions, String malformedVersion) {
+            String versionsString = "";
+            for(int i = 0; i < versions.length; i++) {
+                versionsString += versions[i] + "\n";
+            }
+            if (malformedVersion != null) {
+                versionsString += malformedVersion + "\n";
+            }
+            byte[] bytes = versionsString.getBytes();
+            m_inputStream = new ByteArrayInputStream(bytes);
+        }
+
+    }
+
+    public URL discover() {
+        return null;
+    }
+
+    public Deployment getDeployment() {
+        return TestUtils.createMockObjectAdapter(Deployment.class, m_mockDeploymentService);
+    }
+
+    public String getID() {
+        return null;
+    }
+
+    public LogService getLog() {
+        return TestUtils.createNullObject(LogService.class);
+    }
+
+    public LogStore getAuditStore() {
+        return null;
+    }
+
+}

Added: incubator/ace/trunk/test/src/net/luminis/liq/discovery/property/SimpleDiscoveryTest.java
URL: http://svn.apache.org/viewvc/incubator/ace/trunk/test/src/net/luminis/liq/discovery/property/SimpleDiscoveryTest.java?rev=788992&view=auto
==============================================================================
--- incubator/ace/trunk/test/src/net/luminis/liq/discovery/property/SimpleDiscoveryTest.java (added)
+++ incubator/ace/trunk/test/src/net/luminis/liq/discovery/property/SimpleDiscoveryTest.java Sat Jun 27 15:53:04 2009
@@ -0,0 +1,65 @@
+package net.luminis.liq.discovery.property;
+
+import static net.luminis.liq.test.utils.TestUtils.UNIT;
+
+import java.net.URL;
+import java.util.Dictionary;
+import java.util.Hashtable;
+
+import net.luminis.liq.discovery.property.constants.DiscoveryConstants;
+
+import org.osgi.service.cm.ConfigurationException;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+public class SimpleDiscoveryTest {
+
+    private static final String SERVERURL_KEY = DiscoveryConstants.DISCOVERY_URL_KEY;
+    private static final String VALID_URL = "http://test.url.com:8080";
+    private static final String INVALID_URL = "malformed url";
+
+    private PropertyBasedDiscovery m_discovery;
+
+    @BeforeTest(alwaysRun = true)
+    protected void setUp() throws Exception {
+        m_discovery = new PropertyBasedDiscovery();
+    }
+
+    /**
+     * Test if setting a valid configuration is handled correctly
+     * @throws Exception
+     */
+    @Test(groups = { UNIT })
+    public void simpleDiscoveryValidConfiguration() throws ConfigurationException {
+        Dictionary<String, String> properties = new Hashtable<String, String>();
+        properties.put(SERVERURL_KEY, VALID_URL);
+        m_discovery.updated(properties);
+        URL url = m_discovery.discover();
+        assert VALID_URL.equals(url.toString()) : "Configured url was not returned";
+    }
+
+    /**
+     * Test if setting an invalid configuration is handled correctly.
+     * @throws ConfigurationException
+     */
+    @Test(groups = {UNIT}, expectedExceptions = ConfigurationException.class)
+    public void simpleDiscoveryInvalidConfiguration() throws ConfigurationException {
+        Dictionary<String, String> properties = new Hashtable<String, String>();
+        properties.put(SERVERURL_KEY, INVALID_URL);
+        m_discovery.updated(properties);
+    }
+
+    /**
+     * Test if supplying an empty configuration results in the service's default being used.
+     * @throws ConfigurationException
+     */
+    @Test(groups = {UNIT})
+    public void simpleDiscoveryEmptyConfiguration() throws ConfigurationException {
+        // set valid config
+        Dictionary<String, String> properties = new Hashtable<String, String>();
+        properties.put(SERVERURL_KEY, VALID_URL);
+        m_discovery.updated(properties);
+        // set empty config
+        m_discovery.updated(null);
+    }
+}

Added: incubator/ace/trunk/test/src/net/luminis/liq/discovery/upnp/SimpleDiscoveryTest.java
URL: http://svn.apache.org/viewvc/incubator/ace/trunk/test/src/net/luminis/liq/discovery/upnp/SimpleDiscoveryTest.java?rev=788992&view=auto
==============================================================================
--- incubator/ace/trunk/test/src/net/luminis/liq/discovery/upnp/SimpleDiscoveryTest.java (added)
+++ incubator/ace/trunk/test/src/net/luminis/liq/discovery/upnp/SimpleDiscoveryTest.java Sat Jun 27 15:53:04 2009
@@ -0,0 +1,127 @@
+package net.luminis.liq.discovery.upnp;
+
+import static net.luminis.liq.test.utils.TestUtils.UNIT;
+
+import java.net.URL;
+import java.util.Properties;
+
+import org.easymock.EasyMock;
+import org.easymock.IMocksControl;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.cm.ConfigurationException;
+import org.osgi.service.upnp.UPnPAction;
+import org.osgi.service.upnp.UPnPDevice;
+import org.osgi.service.upnp.UPnPService;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class SimpleDiscoveryTest {
+
+    private static final String VALID_URL = "http://test.url.com:8080";
+    private static final String INVALID_URL = "malformed url";
+
+    private UPnPBasedDiscovery m_discovery;
+
+
+    private IMocksControl m_control = EasyMock.createControl();
+
+
+    @BeforeMethod(alwaysRun = true)
+    protected void setUp() throws Exception {
+        m_discovery = new UPnPBasedDiscovery();
+        m_discovery.start();
+    }
+
+
+
+    /**
+     * Test if discovering while there's no UPnPService
+     * works as expected (returns null)
+     *
+     * @throws Exception
+     */
+    @Test(groups = { UNIT })
+    public void simpleDiscoveryNoUPnPServices() throws ConfigurationException {
+        URL url = m_discovery.discover();
+        assert (url == null) : "Invalid url was returned (should have been null): " + url;
+    }
+
+
+
+    private UPnPDevice expectDeviceAdditionForURL(String url, String type) throws Exception {
+        final String returnLocation = "returnLocation";
+        final String returnType = "returnType";
+
+        final Properties p = new Properties();
+        p.put(returnLocation, url);
+        p.put(returnType, type);
+
+        m_control.checkOrder(false);
+
+        final UPnPAction action1 = m_control.createMock(UPnPAction.class);
+        EasyMock.expect(action1.getOutputArgumentNames()).andReturn(new String[]{returnLocation}).anyTimes();
+        EasyMock.expect(action1.invoke(null)).andReturn(p).anyTimes();
+
+        final UPnPAction action2 = m_control.createMock(UPnPAction.class);
+        EasyMock.expect(action2.getOutputArgumentNames()).andReturn(new String[]{returnType}).anyTimes();
+        EasyMock.expect(action2.invoke(null)).andReturn(p).anyTimes();
+
+        final UPnPService service = m_control.createMock(UPnPService.class);
+        EasyMock.expect(service.getAction("GetLocation")).andReturn(action1).anyTimes();
+        EasyMock.expect(service.getAction("GetServerType")).andReturn(action2).anyTimes();
+
+        UPnPDevice device = m_control.createMock(UPnPDevice.class);
+        EasyMock.expect(device.getService(EasyMock.isA(String.class))).andReturn(service).anyTimes();
+
+        return device;
+    }
+
+
+    /**
+     * Test if the url as provided by a UPnPDevice
+     * is returned as expected.
+     * @throws Exception
+     */
+    @Test(groups = {UNIT})
+    public void simpleDiscoverySingleUPnPDevice() throws Exception {
+
+        m_control.reset();
+
+        UPnPDevice device = expectDeviceAdditionForURL(VALID_URL, "RelayServer");
+        ServiceReference ref = m_control.createMock(ServiceReference.class);
+
+        m_control.replay();
+
+        m_discovery.added(ref, device);
+        m_discovery.discover();
+
+        m_control.verify();
+
+
+    }
+
+    /**
+     * Test if the url as provided by a UPnPDevice
+     * is returned as expected.
+     * @throws Exception
+     */
+    @Test(groups = {UNIT})
+    public void simpleDiscoveryMultipleUPnPDevices() throws Exception {
+        m_control.reset();
+
+        UPnPDevice device1 = expectDeviceAdditionForURL(VALID_URL, "RelayServer");
+        UPnPDevice device2 = expectDeviceAdditionForURL(INVALID_URL, "RelayServer");
+
+        ServiceReference ref = m_control.createMock(ServiceReference.class);
+
+        m_control.replay();
+
+        m_discovery.added(ref, device1);
+        m_discovery.added(ref, device2);
+
+        URL url = m_discovery.discover();
+        assert VALID_URL.equals(url.toString()) : "Valid url was not returned";
+
+        m_control.verify();
+    }
+}

Added: incubator/ace/trunk/test/src/net/luminis/liq/gateway/log/store/impl/GatewayLogStoreTester.java
URL: http://svn.apache.org/viewvc/incubator/ace/trunk/test/src/net/luminis/liq/gateway/log/store/impl/GatewayLogStoreTester.java?rev=788992&view=auto
==============================================================================
--- incubator/ace/trunk/test/src/net/luminis/liq/gateway/log/store/impl/GatewayLogStoreTester.java (added)
+++ incubator/ace/trunk/test/src/net/luminis/liq/gateway/log/store/impl/GatewayLogStoreTester.java Sat Jun 27 15:53:04 2009
@@ -0,0 +1,86 @@
+package net.luminis.liq.gateway.log.store.impl;
+
+import static net.luminis.liq.test.utils.TestUtils.UNIT;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+
+import net.luminis.liq.gateway.log.store.LogStore;
+import net.luminis.liq.identification.Identification;
+import net.luminis.liq.log.AuditEvent;
+import net.luminis.liq.log.LogEvent;
+import net.luminis.liq.test.utils.TestUtils;
+
+import org.osgi.service.log.LogService;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class GatewayLogStoreTester {
+    private LogStoreImpl m_logStore;
+    private File m_dir = null;
+
+    @BeforeMethod(alwaysRun = true)
+    protected void setUp() throws Exception {
+        m_dir  = File.createTempFile(LogStore.class.getName(), null);
+        m_dir.delete();
+        m_logStore = new LogStoreImpl(m_dir);
+        TestUtils.configureObject(m_logStore, LogService.class);
+        TestUtils.configureObject(m_logStore, Identification.class, TestUtils.createMockObjectAdapter(Identification.class, new Object() {
+            @SuppressWarnings("unused")
+            public String getID() {
+                return "test";
+            }
+        }));
+        m_logStore.start();
+    }
+
+    @AfterMethod(alwaysRun = true)
+    protected void tearDown() throws IOException {
+        m_logStore.stop();
+        delete(m_dir);
+        m_logStore = null;
+    }
+
+    @SuppressWarnings({ "serial", "unchecked" })
+    @Test(groups = {UNIT})
+    public void testLog() throws IOException {
+        long[] ids = m_logStore.getLogIDs();
+        assert ids.length == 1 : "New store should have only one id";
+        List<String> events = new ArrayList<String>();
+        events.add(m_logStore.put(AuditEvent.FRAMEWORK_STARTED, new Properties() {{put("test", "test");}}).toRepresentation());
+        events.add(m_logStore.put(AuditEvent.BUNDLE_INSTALLED, new Properties() {{put("test", "test");}}).toRepresentation());
+        events.add(m_logStore.put(AuditEvent.DEPLOYMENTADMIN_COMPLETE, new Properties() {{put("test", "test");}}).toRepresentation());
+        ids = m_logStore.getLogIDs();
+        assert ids.length == 1 : "Error free store should have only one id";
+        long highest = m_logStore.getHighestID(ids[0]);
+        assert  highest == 3 : "Store with 3 entries should have 3 as highest id but was: " + highest;
+        List<String> result = new ArrayList<String>();
+        for (LogEvent event : (List<LogEvent>) m_logStore.get(ids[0])) {
+            result.add(event.toRepresentation());
+        }
+        assert result.equals(events) : "Events " + events + " should equal full log " + result;
+        result = new ArrayList<String>();
+        for (LogEvent event : (List<LogEvent>) m_logStore.get(ids[0], 1, highest)) {
+            result.add(event.toRepresentation());
+        }
+        assert result.equals(events) : "Events " + events + " should equal full log " + result;
+    }
+
+    @Test(groups = {UNIT}, expectedExceptions = {IOException.class})
+    public void testExceptionHandling() throws IOException {
+        m_logStore.handleException(m_logStore.getLog(4711), new IOException("test"));
+    }
+
+    private static void delete(File target) {
+        if (target.isDirectory()) {
+            for (File child : target.listFiles()) {
+                delete(child);
+            }
+        }
+        target.delete();
+    }
+}