Author: [email protected]
Date: Tue Jan 24 12:53:13 2012
New Revision: 1984

Log:
Added integration tests for multi-tenancy. This is part of AMDATU-496.

Added:
   
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/
   
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/MultiTenantTest.java
   (contents, props changed)
   
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/
   
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependencyService.java
   (contents, props changed)
   
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependencyServiceImpl.java
   (contents, props changed)
   
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependentService.java
   (contents, props changed)
   
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependentServiceImpl.java
   (contents, props changed)
   
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyTenancyActivator.java
   (contents, props changed)
Modified:
   
trunk/amdatu-core/itest/base/src/main/java/org/amdatu/core/itest/base/TestContext.java

Modified: 
trunk/amdatu-core/itest/base/src/main/java/org/amdatu/core/itest/base/TestContext.java
==============================================================================
--- 
trunk/amdatu-core/itest/base/src/main/java/org/amdatu/core/itest/base/TestContext.java
      (original)
+++ 
trunk/amdatu-core/itest/base/src/main/java/org/amdatu/core/itest/base/TestContext.java
      Tue Jan 24 12:53:13 2012
@@ -95,12 +95,12 @@
         serviceTracker.open();
         m_serviceTrackers.add(serviceTracker);
 
-        T serviceInstance = null;
         try {
-            serviceInstance = (T) serviceTracker.waitForService(timeout);
+            return (T) serviceTracker.waitForService(timeout);
+        }
+        catch (InterruptedException e) {
+            throw new RuntimeException("Interrupted while waiting for 
service!");
         }
-        catch (InterruptedException e) {}
-        return serviceInstance;
     }
 
     public void waitForSystemToSettle() throws Exception {
@@ -112,52 +112,56 @@
         Dictionary<String, Object> props = new Hashtable<String, Object>();
         props.put("org.amdatu.core.itest.base.sid", uid);
         Component com = m_dependencyManager.createComponent()
-                    .setInterface(Object.class.getName(), props)
-                    .setImplementation(uid)
-                        
.add(m_dependencyManager.createConfigurationDependency()
-                                .setPid(pid));
+            .setInterface(Object.class.getName(), props)
+            .setImplementation(uid)
+            .add(m_dependencyManager.createConfigurationDependency()
+                .setPid(pid));
         m_dependencyManager.add(com);
         updateConfig(pid, new Properties());
         getService(Object.class, "(org.amdatu.core.itest.base.sid=" + uid + 
")");
         m_dependencyManager.remove(com);
     }
 
-    public void updateConfig(String pid, Properties properties) throws 
Exception {
-        updateConfig(pid, properties, false);
+    public Configuration updateConfig(String pid, Properties properties) 
throws Exception {
+        return updateConfig(pid, properties, false);
     }
 
-    public void updateFactoryConfig(String pid, Properties properties) throws 
Exception {
-        updateConfig(pid, properties, true);
+    public Configuration updateFactoryConfig(String pid, Properties 
properties) throws Exception {
+        return updateConfig(pid, properties, true);
     }
 
-    public void updateConfig(String pid, Properties properties, boolean 
factory) throws Exception {
+    public Configuration updateConfig(String pid, Properties properties, 
boolean factory) throws Exception {
         ServiceReference sr = getConfigAdminServiceRef();
-        ConfigurationAdmin configurationAdmin = getConfigAdminService(sr);
-        if (!factory) {
-            Configuration configuration =
-                configurationAdmin.getConfiguration(pid, null);
-            configuration.update(properties);
-            m_bundleContext.ungetService(sr);
+        try {
+            ConfigurationAdmin configurationAdmin = getConfigAdminService(sr);
+            if (!factory) {
+                Configuration configuration = 
configurationAdmin.getConfiguration(pid, null);
+                configuration.update(properties);
+                return configuration;
+            }
+            else {
+                Configuration config = 
configurationAdmin.createFactoryConfiguration(pid, null);
+                config.update(properties);
+                return config;
+            }
         }
-        else {
-            Configuration config = 
configurationAdmin.createFactoryConfiguration(pid, null);
-            config.update(properties);
+        finally {
+            m_bundleContext.ungetService(sr);
         }
-        m_bundleContext.ungetService(sr);
     }
 
     public ConfigurationAdmin getConfigurationAdmin() throws Exception {
         return getService(ConfigurationAdmin.class);
     }
 
-    private ConfigurationAdmin getConfigAdminService(ServiceReference sr) {
+    private ConfigurationAdmin getConfigAdminService(ServiceReference<?> sr) {
         ConfigurationAdmin configurationAdmin = (ConfigurationAdmin) 
m_bundleContext.getService(sr);
         assertThat("ConfigurationAdmin service unavailable", 
configurationAdmin, is(notNullValue()));
         return configurationAdmin;
     }
 
-    private ServiceReference getConfigAdminServiceRef() {
-        ServiceReference sr = 
m_bundleContext.getServiceReference(ConfigurationAdmin.class.getName());
+    private ServiceReference<?> getConfigAdminServiceRef() {
+        ServiceReference<?> sr = 
m_bundleContext.getServiceReference(ConfigurationAdmin.class.getName());
         assertThat("ConfigurationAdmin serviceReference unavailable", sr, 
is(notNullValue()));
         return sr;
     }

Added: 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/MultiTenantTest.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/MultiTenantTest.java
 Tue Jan 24 12:53:13 2012
@@ -0,0 +1,370 @@
+/*
+ * Copyright (c) 2010-2012 The Amdatu 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 org.amdatu.core.itest.tests.tenant;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+import static org.ops4j.pax.exam.CoreOptions.cleanCaches;
+import static org.ops4j.pax.exam.CoreOptions.junitBundles;
+import static org.ops4j.pax.exam.CoreOptions.options;
+import static org.ops4j.pax.exam.CoreOptions.provision;
+import static org.ops4j.pax.exam.CoreOptions.systemTimeout;
+import static org.ops4j.pax.tinybundles.core.TinyBundles.bundle;
+import static org.ops4j.pax.tinybundles.core.TinyBundles.withBnd;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Properties;
+import java.util.UUID;
+
+import javax.inject.Inject;
+
+import org.amdatu.core.itest.base.CoreFixture;
+import org.amdatu.core.itest.base.CoreFixture.Configs;
+import org.amdatu.core.itest.base.TestContext;
+import org.amdatu.core.itest.tests.tenant.mock.MyDependencyService;
+import org.amdatu.core.itest.tests.tenant.mock.MyDependencyServiceImpl;
+import org.amdatu.core.itest.tests.tenant.mock.MyDependentService;
+import org.amdatu.core.itest.tests.tenant.mock.MyDependentServiceImpl;
+import org.amdatu.core.itest.tests.tenant.mock.MyTenancyActivator;
+import org.amdatu.core.tenant.TenantConstants;
+import org.amdatu.core.tenant.adaptor.MultiTenantBundleActivator;
+import org.apache.felix.dm.DependencyManager;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.junit.ExamReactorStrategy;
+import org.ops4j.pax.exam.junit.JUnit4TestRunner;
+import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.cm.Configuration;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventConstants;
+import org.osgi.service.event.EventHandler;
+
+/**
+ * Integration test cases for multi-tenancy.
+ * 
+ * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+ */
+@RunWith(JUnit4TestRunner.class)
+@ExamReactorStrategy(AllConfinedStagedReactorFactory.class)
+public class MultiTenantTest {
+
+    /**
+     * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+     */
+    static class TestEventHandler implements EventHandler {
+
+        private final List<String> m_messages = new ArrayList<String>();
+
+        /**
+         * @return a copy of the current messages.
+         */
+        public List<String> getMessages() {
+            List<String> result;
+            synchronized (m_messages) {
+                result = new ArrayList<String>(m_messages);
+                m_messages.clear();
+            }
+            return result;
+        }
+
+        /**
+         * @see 
org.osgi.service.event.EventHandler#handleEvent(org.osgi.service.event.Event)
+         */
+        public void handleEvent(Event event) {
+            String msg = (String) event.getProperty("message");
+            synchronized (m_messages) {
+                m_messages.add(msg.substring(4));
+            }
+        }
+    }
+
+    @Inject
+    private BundleContext m_bundleContext;
+    private TestContext m_testContext;
+    private final List<Configuration> m_configurations = new 
ArrayList<Configuration>();
+    private final TestEventHandler m_eventHandler = new TestEventHandler();
+
+    /**
+     * @param collection
+     * @param searchValue
+     */
+    private static void assertStringFound(Collection<String> collection, 
String searchValue) {
+        for (String s : collection) {
+            if (searchValue.equals(s)) {
+                return;
+            }
+        }
+        fail("Search value not found! Searched for: " + searchValue + "; got: 
" + collection);
+    }
+
+    /**
+     * Helper method to count the number of service registrations for a given 
service-class.
+     * 
+     * @param context the bundle context to use;
+     * @param service the service to count.
+     * @return a service registration count, >= 0.
+     */
+    private static int countAllServices(BundleContext context, Class<?> 
service) {
+        ServiceReference<?>[] serviceReferences = null;
+        try {
+            serviceReferences = 
context.getAllServiceReferences(service.getName(), null);
+        }
+        catch (InvalidSyntaxException exception) {
+            throw new RuntimeException("null-filter is incorrect?!");
+        }
+        return serviceReferences == null ? 0 : serviceReferences.length;
+    }
+
+    /**
+     * Creates the PAX-exam configuration.
+     * 
+     * @return a PAX-exam configuration, never <code>null</code>.
+     */
+    @org.ops4j.pax.exam.junit.Configuration
+    public Option[] config() {
+        InputStream mtBundle = bundle()
+            .add(MyTenancyActivator.class)
+            .add(MyDependentService.class)
+            .add(MyDependentServiceImpl.class)
+            .add(MyDependencyService.class)
+            .add(MyDependencyServiceImpl.class)
+            .set(TenantConstants.MULTITENANT_SCOPE_KEY, 
TenantConstants.MULTITENANT_SCOPE_VALUE_BOTH)
+            .set(TenantConstants.MULTITENANT_VERSION_KEY, 
TenantConstants.MULTITENANT_VERSION_VALUE)
+            .set(TenantConstants.MULTITENANT_BUNDLE_ACTIVATOR_KEY, 
MyTenancyActivator.class.getName())
+            .set(Constants.BUNDLE_ACTIVATOR, 
MultiTenantBundleActivator.class.getName())
+            .set(Constants.BUNDLE_SYMBOLICNAME, "My Tenancy Bundle")
+            .set(Constants.IMPORT_PACKAGE, 
"org.amdatu.core.tenant,org.osgi.framework,org.apache.felix.dm,*")
+            .build(withBnd());
+
+        return options(
+            cleanCaches(),
+            junitBundles(),
+            CoreFixture.provision(),
+            provision(mtBundle),
+            systemTimeout(30000));
+    }
+
+    /**
+     * Sets up an individual test case.
+     * 
+     * @throws Exception not part of this test case.
+     */
+    @Before
+    public void setUp() throws Exception {
+        m_testContext = new TestContext(m_bundleContext);
+        CoreFixture.configure(m_testContext, Configs.TENANT);
+
+        Properties properties = new Properties();
+        properties.put(EventConstants.EVENT_TOPIC, new String[] { 
"org/osgi/service/log/LogEntry/LOG_INFO" });
+        properties.put(EventConstants.EVENT_FILTER, "(message=MTL:*)");
+
+        // Register our own log listener to the framework...
+        DependencyManager dm = m_testContext.getDependencyManager();
+        dm.add(dm.createComponent()
+            .setInterface(EventHandler.class.getName(), properties)
+            .setImplementation(m_eventHandler)
+            );
+
+        m_testContext.waitForSystemToSettle();
+    }
+
+    /**
+     * Tears down an individual test case.
+     * 
+     * @throws Exception not part of this test case.
+     */
+    @After
+    public void tearDown() throws Exception {
+        for (Configuration config : m_configurations) {
+            try {
+                config.delete();
+            }
+            catch (Exception exception) {
+                // Ignore...
+            }
+        }
+        m_configurations.clear();
+        m_testContext.tearDown();
+    }
+
+    /**
+     * Tests that when a multi-tenant aware service is registered, multiple 
service registrations are made, one for each tenant.
+     * 
+     * @throws Exception not part of this test case.
+     */
+    @Test
+    public void 
testAddingMultiTenantAwareServiceCausesNewServiceRegistrations() throws 
Exception {
+        String tenantId = generateTenantId();
+   
+        Properties properties = createTenantConfiguration(tenantId);
+        updateTenantConfig(properties);
+
+        // We've got a number of explicit tenants + one framework (= default) 
tenant
+        int expectedServiceCount = m_configurations.size() + 1;
+
+        // A non-MT aware bundle should be able to see *all* service 
registrations...
+        assertEquals(expectedServiceCount, countAllServices(m_bundleContext, 
MyDependentService.class));
+    }
+
+    /**
+     * Tests that when a multi-tenant aware service is registered, multiple 
service registrations are made, one for each tenant.
+     * 
+     * @throws Exception not part of this test case.
+     */
+    @Test
+    public void 
testMultiTenantAwareServiceCausesMultipleServiceRegistrations() throws 
Exception {
+        // We've got a number of explicit tenants + one framework (= default) 
tenant
+        int expectedServiceCount = m_configurations.size() + 1;
+
+        // A non-MT aware bundle should be able to see *all* service 
registrations...
+        assertEquals(expectedServiceCount, countAllServices(m_bundleContext, 
MyDependentService.class));
+    }
+
+    /**
+     * Tests that when a multi-tenant aware service is registered, each tenant 
only sees its own services, not the services of other tenants.
+     * 
+     * @throws Exception not part of this test case.
+     */
+    @Test
+    public void testMultiTenantAwareServiceOnlySeesItsOwnServices() throws 
Exception {
+        String tenantId = generateTenantId();
+        
+        List<String> msg = m_eventHandler.getMessages();
+        
+        Properties properties = createTenantConfiguration(tenantId);
+        updateTenantConfig(properties);
+
+        msg = m_eventHandler.getMessages();
+        assertNotNull(msg);
+
+        assertStringFound(msg, "START{tenant_id;" +tenantId + "}");
+    }
+
+    /**
+     * Tests that when a non-multi-tenant service (= this test case) tries to 
obtain a multi-tenant aware service, this would fail.
+     * 
+     * @throws Exception not part of this test case.
+     */
+    @Test
+    public void 
testObtainMultiTenantServiceInstanceFailsForNonMultiTenantService() throws 
Exception {
+        String tenantId = generateTenantId();
+        
+        Properties properties = createTenantConfiguration(tenantId);
+        updateTenantConfig(properties);
+
+        ServiceReference<?>[] serviceRefs = 
m_bundleContext.getServiceReferences(MyDependentService.class.getName(), 
"(tenant_id=" + tenantId + ")");
+        assertNull(serviceRefs);
+    }
+
+    /**
+     * Tests that when a non-multi-tenant service (= this test case) tries to 
obtain a multi-tenant aware service, this would fail.
+     * 
+     * @throws Exception not part of this test case.
+     */
+    @Ignore
+    @Test
+    public void 
testObtainPlatformServiceInstanceSucceedsForNonMultiTenantService() throws 
Exception {
+        String tenantId = generateTenantId();
+        
+        Properties properties = createTenantConfiguration(tenantId);
+        updateTenantConfig(properties);
+
+        ServiceReference<?> serviceRef = 
m_bundleContext.getServiceReference(MyDependentService.class.getName());
+        assertNotNull("Failed to obtain the MT-platform service?!", 
serviceRef);
+    }
+    
+    /**
+     * Tests that when a multi-tenant aware service is registered, multiple 
service registrations are made, one for each tenant.
+     * 
+     * @throws Exception not part of this test case.
+     */
+    @Test
+    public void 
testRemovingMultiTenantAwareServiceCausesServiceDeregistrations() throws 
Exception {
+        String tenantId = generateTenantId();
+        List<String> msg = m_eventHandler.getMessages();
+        
+        Properties properties = createTenantConfiguration(tenantId);
+        Configuration config = updateTenantConfig(properties);
+
+        // We've got a number of explicit tenants + one framework (= default) 
tenant
+        int expectedServiceCount = m_configurations.size() + 1;
+
+        // A non-MT aware bundle should be able to see *all* service 
registrations...
+        assertEquals(expectedServiceCount, countAllServices(m_bundleContext, 
MyDependentService.class));
+
+        // Remove configuration; should cause service de-registration for 
tenant...
+        removeTenantConfig(config);
+
+        // A non-MT aware bundle should be able to see *all* service 
registrations...
+        assertEquals(expectedServiceCount - 1, 
countAllServices(m_bundleContext, MyDependentService.class));
+        
+        msg = m_eventHandler.getMessages();
+
+        assertStringFound(msg, "STOP{tenant_id;" + tenantId + "}");
+    }
+
+    /**
+     * @param tenantId
+     * @return
+     */
+    private Properties createTenantConfiguration(String tenantId) {
+        Properties properties = new Properties();
+        properties.put("id", tenantId);
+        properties.put("name", "Tenant " + tenantId);
+        properties.put("host", "localhost");
+        return properties;
+    }
+
+    /**
+     * @return
+     */
+    private String generateTenantId() {
+        return String.format("mt%s", Long.toHexString(System.nanoTime()));
+    }
+
+    /**
+     * @param properties
+     * @throws Exception
+     */
+    private void removeTenantConfig(Configuration config) throws Exception {
+        config.delete();
+        m_testContext.waitForSystemToSettle();
+    }
+
+    /**
+     * @param properties
+     * @throws Exception
+     */
+    private Configuration updateTenantConfig(Properties properties) throws 
Exception {
+        Configuration config = 
m_testContext.updateFactoryConfig(CoreFixture.Configs.TENANT.getPid(), 
properties);
+        m_configurations.add(config);
+        m_testContext.waitForSystemToSettle();
+        return config;
+    }
+}

Added: 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependencyService.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependencyService.java
        Tue Jan 24 12:53:13 2012
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2010-2012 The Amdatu 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 org.amdatu.core.itest.tests.tenant.mock;
+
+/**
+ * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+ *
+ */
+public interface MyDependencyService {
+
+}

Added: 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependencyServiceImpl.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependencyServiceImpl.java
    Tue Jan 24 12:53:13 2012
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2010-2012 The Amdatu 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 org.amdatu.core.itest.tests.tenant.mock;
+
+import org.apache.felix.dm.Component;
+import org.osgi.service.log.LogService;
+
+/**
+ * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+ */
+public class MyDependencyServiceImpl implements MyDependencyService {
+    private volatile Component m_component;
+    private volatile LogService m_logService;
+
+    /**
+     * Called by Felix DependencyManager upon starting this component!
+     */
+    protected void start() {
+        m_logService.log(LogService.LOG_INFO, "Starting " + 
getClass().getSimpleName());
+        m_logService.log(LogService.LOG_INFO, 
MyDependentServiceImpl.getMTServiceTag(m_component.getServiceRegistration().getReference(),
 "START"));
+    }
+
+    /**
+     * Called by Felix DependencyManager upon starting this component!
+     */
+    protected void stop() {
+        m_logService.log(LogService.LOG_INFO, "Stopping " + 
getClass().getSimpleName());
+        m_logService.log(LogService.LOG_INFO, 
MyDependentServiceImpl.getMTServiceTag(m_component.getServiceRegistration().getReference(),
 "STOP"));
+    }
+}

Added: 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependentService.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependentService.java
 Tue Jan 24 12:53:13 2012
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2010-2012 The Amdatu 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 org.amdatu.core.itest.tests.tenant.mock;
+
+
+/**
+ * Provides a "mock" multi-tenant aware service.
+ * 
+ * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+ */
+public interface MyDependentService {
+    
+}

Added: 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependentServiceImpl.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyDependentServiceImpl.java
     Tue Jan 24 12:53:13 2012
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2010-2012 The Amdatu 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 org.amdatu.core.itest.tests.tenant.mock;
+
+import junit.framework.Assert;
+
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.log.LogService;
+
+/**
+ * Test implementation of {@link MyDependentService}.
+ * 
+ * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+ */
+public class MyDependentServiceImpl implements MyDependentService {
+    private volatile BundleContext m_bundleContext;
+    private volatile LogService m_logService;
+
+    private ServiceReference<?> m_serviceReference;
+
+    /**
+     * Called by Felix DependencyManager upon starting this component!
+     */
+    protected void start() throws Exception {
+        ServiceReference<?>[] serviceReferences =
+            
m_bundleContext.getServiceReferences(MyDependencyService.class.getName(), null);
+        Assert.assertNotNull(serviceReferences);
+        Assert.assertEquals(1, serviceReferences.length);
+
+        m_serviceReference = serviceReferences[0];
+
+        m_logService.log(LogService.LOG_INFO, "Starting " + 
getClass().getSimpleName());
+        m_logService.log(LogService.LOG_INFO, 
getMTServiceTag(m_serviceReference, "START"));
+    }
+
+    /**
+     * Called by Felix DependencyManager upon starting this component!
+     */
+    protected void stop() throws Exception {
+        m_logService.log(LogService.LOG_INFO, "Stopping " + 
getClass().getSimpleName());
+        m_logService.log(LogService.LOG_INFO, 
getMTServiceTag(m_serviceReference, "STOP"));
+    }
+
+    /**
+     * @param serviceRef
+     * @return
+     */
+    static String getMTServiceTag(ServiceReference<?> serviceRef, String id) {
+        StringBuilder sb = new StringBuilder("MTL:");
+        sb.append(id);
+        if (serviceRef != null) {
+            for (String key : serviceRef.getPropertyKeys()) {
+                if (key.startsWith("tenant_")) {
+                    
sb.append("{").append(key).append(";").append(serviceRef.getProperty(key)).append("}");
+                }
+            }
+        }
+        return sb.toString();
+    }
+}

Added: 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyTenancyActivator.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-core/itest/tests/src/test/java/org/amdatu/core/itest/tests/tenant/mock/MyTenancyActivator.java
 Tue Jan 24 12:53:13 2012
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2010-2012 The Amdatu 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 org.amdatu.core.itest.tests.tenant.mock;
+
+import org.apache.felix.dm.DependencyActivatorBase;
+import org.apache.felix.dm.DependencyManager;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.log.LogService;
+
+/**
+ * Test activator for {@link MyDependentService}.
+ * 
+ * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+ */
+public class MyTenancyActivator extends DependencyActivatorBase {
+
+    /**
+     * @see 
org.apache.felix.dm.DependencyActivatorBase#init(org.osgi.framework.BundleContext,
 org.apache.felix.dm.DependencyManager)
+     */
+    @Override
+    public void init(BundleContext context, DependencyManager manager) throws 
Exception {
+        manager.add(createComponent()
+            .setInterface(MyDependencyService.class.getName(), null)
+            .setImplementation(new MyDependencyServiceImpl())
+            .add(createServiceDependency()
+                .setService(LogService.class)
+                .setRequired(false)
+            )
+            );
+        manager.add(createComponent()
+            .setInterface(MyDependentService.class.getName(), null)
+            .setImplementation(new MyDependentServiceImpl())
+            .add(createServiceDependency()
+                .setService(LogService.class)
+                .setRequired(false)
+            )
+            );
+    }
+
+    /**
+     * @see 
org.apache.felix.dm.DependencyActivatorBase#destroy(org.osgi.framework.BundleContext,
 org.apache.felix.dm.DependencyManager)
+     */
+    @Override
+    public void destroy(BundleContext context, DependencyManager manager) 
throws Exception {
+        // NO-op
+    }
+}
_______________________________________________
Amdatu-commits mailing list
[email protected]
http://lists.amdatu.org/mailman/listinfo/amdatu-commits

Reply via email to