upgrade to use R43 OSGi API
diff --git a/core/src/main/java/org/eclipse/gemini/blueprint/compendium/internal/cm/CMUtils.java b/core/src/main/java/org/eclipse/gemini/blueprint/compendium/internal/cm/CMUtils.java
index 88c5f2d..ea47dc9 100644
--- a/core/src/main/java/org/eclipse/gemini/blueprint/compendium/internal/cm/CMUtils.java
+++ b/core/src/main/java/org/eclipse/gemini/blueprint/compendium/internal/cm/CMUtils.java
@@ -18,6 +18,7 @@
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
+import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
@@ -120,7 +121,7 @@
}
// no valid props, register a listener and start waiting
final Object monitor = new Object();
- Properties props = new Properties();
+ Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_PID, pid);
ServiceRegistration reg =
@@ -167,7 +168,7 @@
public static ServiceRegistration registerManagedService(BundleContext bundleContext, ManagedService listener,
String pid) {
- Properties props = new Properties();
+ Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_PID, pid);
Bundle bundle = bundleContext.getBundle();
props.put(Constants.BUNDLE_SYMBOLICNAME, OsgiStringUtils.nullSafeSymbolicName(bundle));
diff --git a/core/src/main/java/org/eclipse/gemini/blueprint/context/support/AbstractOsgiBundleApplicationContext.java b/core/src/main/java/org/eclipse/gemini/blueprint/context/support/AbstractOsgiBundleApplicationContext.java
index 3e7822b..f51d5da 100644
--- a/core/src/main/java/org/eclipse/gemini/blueprint/context/support/AbstractOsgiBundleApplicationContext.java
+++ b/core/src/main/java/org/eclipse/gemini/blueprint/context/support/AbstractOsgiBundleApplicationContext.java
@@ -319,9 +319,9 @@
@SuppressWarnings("unchecked")
private void publishContextAsOsgiServiceIfNecessary() {
if (publishContextAsService && serviceRegistration == null) {
- final Dictionary<Object, Object> serviceProperties = new MapBasedDictionary<Object, Object>();
+ final Dictionary<String, Object> serviceProperties = new MapBasedDictionary<String, Object>();
- customizeApplicationContextServiceProperties((Map<Object, Object>) serviceProperties);
+ customizeApplicationContextServiceProperties((Map<String, Object>) serviceProperties);
if (logger.isInfoEnabled()) {
logger.info("Publishing application context as OSGi service with properties " + serviceProperties);
@@ -396,7 +396,7 @@
*
* @param serviceProperties service properties map (can be casted to {@link Dictionary})
*/
- protected void customizeApplicationContextServiceProperties(Map<Object, Object> serviceProperties) {
+ protected void customizeApplicationContextServiceProperties(Map<String, Object> serviceProperties) {
serviceProperties.put(APPLICATION_CONTEXT_SERVICE_PROPERTY_NAME, getBundleSymbolicName());
serviceProperties.put(SPRING_DM_APPLICATION_CONTEXT_SERVICE_PROPERTY_NAME, getBundleSymbolicName());
serviceProperties.put(Constants.BUNDLE_SYMBOLICNAME, getBundleSymbolicName());
diff --git a/core/src/main/java/org/eclipse/gemini/blueprint/util/OsgiBundleUtils.java b/core/src/main/java/org/eclipse/gemini/blueprint/util/OsgiBundleUtils.java
index 685f598..4dcbbac 100644
--- a/core/src/main/java/org/eclipse/gemini/blueprint/util/OsgiBundleUtils.java
+++ b/core/src/main/java/org/eclipse/gemini/blueprint/util/OsgiBundleUtils.java
@@ -195,10 +195,10 @@
if (OsgiPlatformDetector.isR41()) {
if (bundle.getState() == Bundle.STARTING) {
- Dictionary<Object, Object> headers = bundle.getHeaders();
+ Dictionary<String, String> headers = bundle.getHeaders();
if (headers != null) {
Object val = headers.get(Constants.BUNDLE_ACTIVATIONPOLICY);
- if (val instanceof String) {
+ if (val != null) {
String value = ((String) val).trim();
return (value.startsWith(Constants.ACTIVATION_LAZY));
}
diff --git a/core/src/main/java/org/eclipse/gemini/blueprint/util/OsgiServiceUtils.java b/core/src/main/java/org/eclipse/gemini/blueprint/util/OsgiServiceUtils.java
index d783e8d..555c7e9 100644
--- a/core/src/main/java/org/eclipse/gemini/blueprint/util/OsgiServiceUtils.java
+++ b/core/src/main/java/org/eclipse/gemini/blueprint/util/OsgiServiceUtils.java
@@ -1,20 +1,20 @@
-/******************************************************************************
- * Copyright (c) 2006, 2010 VMware Inc.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * and Apache License v2.0 which accompanies this distribution.
- * The Eclipse Public License is available at
- * http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0
- * is available at http://www.opensource.org/licenses/apache2.0.php.
- * You may elect to redistribute this code under either of these licenses.
- *
- * Contributors:
- * VMware Inc.
- *****************************************************************************/
-
+/******************************************************************************
+ * Copyright (c) 2006, 2010 VMware Inc.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Apache License v2.0 which accompanies this distribution.
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0
+ * is available at http://www.opensource.org/licenses/apache2.0.php.
+ * You may elect to redistribute this code under either of these licenses.
+ *
+ * Contributors:
+ * VMware Inc.
+ *****************************************************************************/
+
package org.eclipse.gemini.blueprint.util;
-import org.osgi.framework.ServiceRegistration;
+import org.osgi.framework.ServiceRegistration;
/**
* Utility class offering easy access to OSGi services.
@@ -29,7 +29,7 @@
* true if the unregistration process succeeded, false otherwise.
*
* @param registration service registration (can be null)
- * @return true if the unregistration successeded, false otherwise
+ * @return true if the unregistration succeeded, false otherwise
*/
public static boolean unregisterService(ServiceRegistration registration) {
try {
@@ -37,8 +37,8 @@
registration.unregister();
return true;
}
- }
- catch (IllegalStateException alreadyUnregisteredException) {
+ } catch (IllegalStateException alreadyUnregisteredException) {
+ // do nothing
}
return false;
}
diff --git a/core/src/main/java/org/eclipse/gemini/blueprint/util/internal/ClassUtils.java b/core/src/main/java/org/eclipse/gemini/blueprint/util/internal/ClassUtils.java
index df64f2e..d065ebc 100644
--- a/core/src/main/java/org/eclipse/gemini/blueprint/util/internal/ClassUtils.java
+++ b/core/src/main/java/org/eclipse/gemini/blueprint/util/internal/ClassUtils.java
@@ -120,7 +120,7 @@
/** Include only the class hierarchy (interfaces are excluded) */
CLASS_HIERARCHY,
/** Include all inherited classes (classes or interfaces) */
- ALL_CLASSES;
+ ALL_CLASSES
}
/**
diff --git a/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ConfigPropertiesHandlerTest.java b/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ConfigPropertiesHandlerTest.java
index 2f01f4b..d61368a 100644
--- a/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ConfigPropertiesHandlerTest.java
+++ b/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ConfigPropertiesHandlerTest.java
@@ -53,7 +53,7 @@
private ConfigurationAdmin admin;
- private Dictionary<String, String> config;
+ private Dictionary<String, Object> config;
private String persistentId = "foo.bar";
private Configuration cfg;
@@ -65,7 +65,7 @@
admin = adminControl.createMock(ConfigurationAdmin.class);
cfg = createMock(Configuration.class);
- config = new Hashtable<String, String>();
+ config = new Hashtable<String, Object>();
expect(admin.getConfiguration(persistentId)).andReturn(cfg).atLeastOnce();
expect(cfg.getProperties()).andReturn(config).atLeastOnce();
diff --git a/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ManagedPropertiesTest.java b/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ManagedPropertiesTest.java
index db193b3..d8deb75 100644
--- a/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ManagedPropertiesTest.java
+++ b/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ManagedPropertiesTest.java
@@ -16,6 +16,7 @@
import java.io.IOException;
import java.util.Dictionary;
+import java.util.Hashtable;
import java.util.Properties;
import junit.framework.TestCase;
@@ -48,7 +49,7 @@
protected void setUp() throws Exception {
final Configuration cfg = createNiceMock(Configuration.class);
- expect(cfg.getProperties()).andReturn(new Properties());
+ expect(cfg.getProperties()).andReturn(new Hashtable<String, Object>());
replay(cfg);
registrationCounter = 0;
diff --git a/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ManagedServiceFactoryTest.java b/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ManagedServiceFactoryTest.java
index 41dce0e..fe15d60 100644
--- a/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ManagedServiceFactoryTest.java
+++ b/core/src/test/java/org/eclipse/gemini/blueprint/compendium/config/ManagedServiceFactoryTest.java
@@ -17,6 +17,7 @@
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
+import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
@@ -49,7 +50,7 @@
final Configuration cfg = createMock(Configuration.class);
- expect(cfg.getProperties()).andReturn(new Properties());
+ expect(cfg.getProperties()).andReturn(new Hashtable<String, Object>());
replay(cfg);
BundleContext bundleContext = new MockBundleContext() {
diff --git a/core/src/test/java/org/eclipse/gemini/blueprint/compendium/internal/cm/ConfigurationAdminManagerTest.java b/core/src/test/java/org/eclipse/gemini/blueprint/compendium/internal/cm/ConfigurationAdminManagerTest.java
index 7dc69a3..685e8fe 100644
--- a/core/src/test/java/org/eclipse/gemini/blueprint/compendium/internal/cm/ConfigurationAdminManagerTest.java
+++ b/core/src/test/java/org/eclipse/gemini/blueprint/compendium/internal/cm/ConfigurationAdminManagerTest.java
@@ -17,6 +17,7 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.Dictionary;
+import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -50,7 +51,7 @@
services = new LinkedHashMap();
IMocksControl mc = createNiceControl();
cfg = mc.createMock(Configuration.class);
- expect(cfg.getProperties()).andReturn(new Properties());
+ expect(cfg.getProperties()).andReturn(new Hashtable<String, Object>());
mc.replay();
bundleContext = new MockBundleContext() {
diff --git a/core/src/test/java/org/eclipse/gemini/blueprint/internal/service/interceptor/OsgiServiceDynamicInterceptorListenerTest.java b/core/src/test/java/org/eclipse/gemini/blueprint/internal/service/interceptor/OsgiServiceDynamicInterceptorListenerTest.java
index 821b344..52cb2fd 100644
--- a/core/src/test/java/org/eclipse/gemini/blueprint/internal/service/interceptor/OsgiServiceDynamicInterceptorListenerTest.java
+++ b/core/src/test/java/org/eclipse/gemini/blueprint/internal/service/interceptor/OsgiServiceDynamicInterceptorListenerTest.java
@@ -113,7 +113,7 @@
Dictionary props = new Hashtable();
// increase service ranking
- props.put(Constants.SERVICE_RANKING, new Integer(10));
+ props.put(Constants.SERVICE_RANKING, 10);
ServiceReference ref = new MockServiceReference(null, props, null);
@@ -152,7 +152,7 @@
Dictionary props = new Hashtable();
// increase service ranking
- props.put(Constants.SERVICE_RANKING, new Integer(10));
+ props.put(Constants.SERVICE_RANKING, 10);
ServiceReference ref = new MockServiceReference(null, props, null);
ServiceEvent event = new ServiceEvent(ServiceEvent.REGISTERED, ref);
@@ -174,12 +174,12 @@
Dictionary props = new Hashtable();
// increase service ranking
- props.put(Constants.SERVICE_RANKING, new Integer(10));
+ props.put(Constants.SERVICE_RANKING, 10);
ServiceReference higherRankingRef = new MockServiceReference(null, props, null);
refs = new ServiceReference[] { new MockServiceReference(), higherRankingRef };
- assertTrue(Arrays.equals(bundleContext.getServiceReferences(null, null), refs));
+ assertTrue(Arrays.equals(bundleContext.getServiceReferences((String)null, null), refs));
assertEquals(1, SimpleTargetSourceLifecycleListener.BIND);
assertEquals(0, SimpleTargetSourceLifecycleListener.UNBIND);
diff --git a/core/src/test/java/org/eclipse/gemini/blueprint/service/exporter/BeanNameServicePropertiesResolverTest.java b/core/src/test/java/org/eclipse/gemini/blueprint/service/exporter/BeanNameServicePropertiesResolverTest.java
index 32f7b2b..e51779d 100644
--- a/core/src/test/java/org/eclipse/gemini/blueprint/service/exporter/BeanNameServicePropertiesResolverTest.java
+++ b/core/src/test/java/org/eclipse/gemini/blueprint/service/exporter/BeanNameServicePropertiesResolverTest.java
@@ -15,6 +15,8 @@
package org.eclipse.gemini.blueprint.service.exporter;
+import java.util.Dictionary;
+import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
@@ -53,7 +55,7 @@
expect(mockBundle.getSymbolicName()).andReturn("symbolic-name");
expect(mockContext.getBundle()).andReturn(mockBundle);
- Properties props = new Properties();
+ Dictionary<String, String> props = new Hashtable<String, String>();
props.put(Constants.BUNDLE_VERSION, "1.0.0");
expect(mockBundle.getHeaders()).andReturn(props);
diff --git a/core/src/test/java/org/eclipse/gemini/blueprint/util/BundleDelegatingClassLoaderTest.java b/core/src/test/java/org/eclipse/gemini/blueprint/util/BundleDelegatingClassLoaderTest.java
index b323cc1..bbb1d44 100644
--- a/core/src/test/java/org/eclipse/gemini/blueprint/util/BundleDelegatingClassLoaderTest.java
+++ b/core/src/test/java/org/eclipse/gemini/blueprint/util/BundleDelegatingClassLoaderTest.java
@@ -63,7 +63,7 @@
public void testFindClass() throws Exception {
String className = "foo.bar";
String anotherClassName = "bar.foo";
- expect(bundle.loadClass(className)).andReturn(Object.class);
+ expect(bundle.loadClass(className)).andReturn((Class)Object.class);
expect(bundle.loadClass(anotherClassName)).andThrow(new ClassNotFoundException());
expect(bundle.getSymbolicName()).andReturn("Test Bundle Symbolic Name");
diff --git a/extender/src/main/java/org/eclipse/gemini/blueprint/extender/internal/support/NamespaceManager.java b/extender/src/main/java/org/eclipse/gemini/blueprint/extender/internal/support/NamespaceManager.java
index 685c0d3..72604fb 100644
--- a/extender/src/main/java/org/eclipse/gemini/blueprint/extender/internal/support/NamespaceManager.java
+++ b/extender/src/main/java/org/eclipse/gemini/blueprint/extender/internal/support/NamespaceManager.java
@@ -16,7 +16,9 @@
import java.io.IOException;
import java.util.Collections;
+import java.util.Dictionary;
import java.util.Enumeration;
+import java.util.Hashtable;
import java.util.Properties;
import org.apache.commons.logging.Log;
@@ -186,11 +188,11 @@
}
Bundle bnd = BundleUtils.getDMCoreBundle(context);
- Properties props = null;
+ Dictionary<String, Object> props = null;
if (bnd != null) {
- props = new Properties();
- props.setProperty(BundleUtils.DM_CORE_ID, "" + bnd.getBundleId());
- props.setProperty(BundleUtils.DM_CORE_TS, "" + bnd.getLastModified());
+ props = new Hashtable<String, Object>();
+ props.put(BundleUtils.DM_CORE_ID, bnd.getBundleId());
+ props.put(BundleUtils.DM_CORE_TS, bnd.getLastModified());
}
nsResolverRegistration =
context.registerService(new String[] { NamespaceHandlerResolver.class.getName() },
diff --git a/extender/src/test/java/org/eclipse/gemini/blueprint/extender/internal/ContextLoaderListenerTest.java b/extender/src/test/java/org/eclipse/gemini/blueprint/extender/internal/ContextLoaderListenerTest.java
index 1f2cbae..8e33852 100644
--- a/extender/src/test/java/org/eclipse/gemini/blueprint/extender/internal/ContextLoaderListenerTest.java
+++ b/extender/src/test/java/org/eclipse/gemini/blueprint/extender/internal/ContextLoaderListenerTest.java
@@ -72,7 +72,7 @@
context.addBundleListener(null);
expectLastCall().times(2);
- expect(context.registerService(new String[0], null, new Properties())).andReturn(new MockServiceRegistration()).atLeastOnce();
+ expect(context.registerService(new String[0], null, new Hashtable<String, Object>())).andReturn(new MockServiceRegistration()).atLeastOnce();
replay(context);
this.listener.start(context);
diff --git a/integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/proxycreator/ClassDependenciesVisibilityTest.java b/integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/proxycreator/ClassDependenciesVisibilityTest.java
index 6574a01..f6dc4f3 100644
--- a/integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/proxycreator/ClassDependenciesVisibilityTest.java
+++ b/integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/proxycreator/ClassDependenciesVisibilityTest.java
@@ -17,6 +17,7 @@
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
+import java.security.Permission;
import java.util.ArrayList;
import java.util.List;
@@ -27,6 +28,10 @@
import org.osgi.framework.AdminPermission;
/**
+ *
+ * FIXME:
+ * TODO: this is not an applicable test anymore. As equinox now exports javax.swing.* as part of org.osgi.framework.system.packages
+ *
* Integration test for bug OSGI-597.
*
* This test tries to create a proxy for DocumentEvent w/o importing its
@@ -87,8 +92,7 @@
try {
cl.loadClass(DEPENDENCY_CLASS);
fail("should not be able to load " + DEPENDENCY_CLASS);
- }
- catch (ClassNotFoundException cnfe) {
+ }catch (ClassNotFoundException cnfe) {
// expected
}
}
@@ -98,13 +102,21 @@
List packages = super.getBootDelegationPackages();
packages.remove("javax.*");
packages.remove("javax.swing.*");
+
+
return packages;
}
- protected List getTestPermissions() {
- List perms = super.getTestPermissions();
+ protected List<Permission> getTestPermissions() {
+ List<Permission> perms = super.getTestPermissions();
// export package
perms.add(new RuntimePermission("*", "getClassLoader"));
return perms;
}
+
+ @Override
+ protected boolean isDisabledInThisEnvironment(String testMethodName) {
+ // TODO: disabling this set of tests for now.
+ return true;
+ }
}
diff --git a/integration-tests/tests/src/test/resources/logback-test.xml b/integration-tests/tests/src/test/resources/logback-test.xml
index 7e67039..c27d7e3 100644
--- a/integration-tests/tests/src/test/resources/logback-test.xml
+++ b/integration-tests/tests/src/test/resources/logback-test.xml
@@ -1,16 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
-<!-- For assistance related to logback-translator or configuration -->
-<!-- files in general, please contact the logback user mailing list -->
-<!-- at http://www.qos.ch/mailman/listinfo/logback-user -->
-<!-- -->
-<!-- For professional support please see -->
-<!-- http://www.qos.ch/shop/products/professionalSupport -->
-<!-- -->
<configuration debug="true">
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
- <pattern>%-30(%d{HH:mm:ss.SSS} [%thread]) %-5level %logger{32} : %line - %msg %ex%n</pattern>
+ <pattern>%-30(%d{HH:mm:ss.SSS} [%thread]) %-5level %logger{32}:%line - %msg %ex%n</pattern>
</encoder>
</appender>
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
@@ -19,22 +12,31 @@
<encoder>
<pattern>%-30(%d{HH:mm:ss.SSS} [%thread]) %-5level %logger{32}:%line - %msg %ex%n</pattern>
</encoder>
+ <!--<filter class="ch.qos.logback.classic.filter.ThresholdFilter">-->
+ <!--<level>TRACE</level>-->
+ <!--</filter>-->
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <maxIndex>2</maxIndex>
+ <maxIndex>10</maxIndex>
<FileNamePattern>./target/out.log.%i</FileNamePattern>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
- <logger name="org.springframework" level="INFO"/>
- <logger name="org.eclipse.gemini.blueprint.context.support.DelegatedNamespaceHandlerResolver" level="WARN"/>
- <logger name="org.eclipse.gemini.blueprint.service.dependency.internal" level="WARN"/>
- <logger name="org.eclipse.gemini.blueprint.extender.internal.support.NamespaceManager" level="WARN"/>
- <logger name="org.eclipse.gemini.blueprint.extender.internal.support.NamespacePlugins" level="WARN"/>
+ <logger name="org.eclipse.gemini.blueprint.util" level="TRACE"/>
+ <logger name="org.eclipse.gemini.blueprint" level="TRACE"/>
<logger name="org.eclipse.gemini.blueprint.context.support.ChainedEntityResolver" level="WARN"/>
- <logger name="org.eclipse.gemini.blueprint.util.BundleDelegatingClassLoader" level="INFO"/>
- <root level="TRACE">
+ <logger name="org.eclipse.gemini.blueprint.context.support.DelegatedNamespaceHandlerResolver" level="WARN"/>
+ <logger name="org.eclipse.gemini.blueprint.extender.internal.activator.listeners" level="WARN"/>
+ <logger name="org.eclipse.gemini.blueprint.extender.internal.activator.ContextLoaderListener$ContextBundleListener" level="WARN"/>
+ <logger name="org.eclipse.gemini.blueprint.extender.internal.blueprint.activator.support" level="INFO"/>
+ <logger name="org.eclipse.gemini.blueprint.io" level="WARN"/>
+ <logger name="org.eclipse.gemini.blueprint.test.provisioning.internal" level="INFO"/>
+ <logger name="org.eclipse.gemini.blueprint.extender.internal.support" level="WARN"/>
+ <logger name="org.springframework.test" level="TRACE"/>
+ <logger name="org.springframework" level="INFO"/>
+ <logger name="org.eclipse.gemini.blueprint.iandt" level="TRACE"/>
+ <root level="WARN">
<appender-ref ref="stdout"/>
<appender-ref ref="file"/>
</root>
diff --git a/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockBundle.java b/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockBundle.java
index 945eeb3..8cae7f8 100644
--- a/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockBundle.java
+++ b/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockBundle.java
@@ -14,6 +14,7 @@
package org.eclipse.gemini.blueprint.mock;
+import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
@@ -60,7 +61,12 @@
private final Version version;
- private static class EmptyEnumeration implements Enumeration {
+ @Override
+ public int compareTo(Bundle o) {
+ return 0; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ private static class EmptyEnumeration implements Enumeration {
public boolean hasMoreElements() {
return false;
@@ -233,7 +239,17 @@
return version;
}
- private static Version getVersion(Dictionary headers) {
+ @Override
+ public <A> A adapt(Class<A> type) {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ @Override
+ public File getDataFile(String filename) {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ private static Version getVersion(Dictionary headers) {
if (headers != null) {
Object header = headers.get(Constants.BUNDLE_VERSION);
if (header instanceof String) {
diff --git a/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockBundleContext.java b/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockBundleContext.java
index f0ab196..427c626 100644
--- a/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockBundleContext.java
+++ b/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockBundleContext.java
@@ -17,8 +17,16 @@
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import java.lang.reflect.Array;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
import java.util.Dictionary;
import java.util.LinkedHashSet;
+import java.util.List;
import java.util.Properties;
import java.util.Set;
@@ -54,7 +62,8 @@
private Properties properties;
- protected Set serviceListeners, bundleListeners;
+ protected Set<ServiceListener> serviceListeners;
+ protected Set<BundleListener> bundleListeners;
/**
@@ -87,9 +96,9 @@
if (props != null)
properties.putAll(props);
- // make sure the order is preserved
- this.serviceListeners = new LinkedHashSet(2);
- this.bundleListeners = new LinkedHashSet(2);
+ // make sure the order is preserved
+ this.serviceListeners = new LinkedHashSet<ServiceListener>(2);
+ this.bundleListeners = new LinkedHashSet<BundleListener>(2);
}
public void addBundleListener(BundleListener listener) {
@@ -99,14 +108,13 @@
public void addFrameworkListener(FrameworkListener listener) {
}
- public void addServiceListener(ServiceListener listener) {
- try {
- addServiceListener(listener, null);
- }
- catch (InvalidSyntaxException ex) {
- throw new IllegalStateException("exception should not occur");
- }
- }
+ public void addServiceListener(ServiceListener listener) {
+ try {
+ addServiceListener(listener, null);
+ } catch (InvalidSyntaxException ex) {
+ throw new IllegalStateException("exception should not occur");
+ }
+ }
public void addServiceListener(ServiceListener listener, String filter) throws InvalidSyntaxException {
if (listener == null)
@@ -118,7 +126,13 @@
return new MockFilter(filter);
}
- public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
+ @Override
+ public Bundle getBundle(String location) {
+ // always return null as we do not keep track of location.
+ return null;
+ }
+
+ public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
return new ServiceReference[] {};
}
@@ -142,18 +156,66 @@
return properties.getProperty(key);
}
- public Object getService(ServiceReference reference) {
- return new Object();
- }
+ public <S> S getService(ServiceReference<S> reference) {
+ Class type = getClass(reference.getClass().getGenericSuperclass());
+ try {
+ @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"}) S result = (S)type.newInstance();
+ return result;
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ private static Class<?> getClass(Type type) {
+ if (type instanceof Class) {
+ return (Class) type;
+ }
+ else if (type instanceof ParameterizedType) {
+ return getClass(((ParameterizedType) type).getRawType());
+ }
+ else if (type instanceof GenericArrayType) {
+ Type componentType = ((GenericArrayType) type).getGenericComponentType();
+ Class<?> componentClass = getClass(componentType);
+ if (componentClass != null ) {
+ return Array.newInstance(componentClass, 0).getClass();
+ }
+ else {
+ return null;
+ }
+ }
+ else {
+ return null;
+ }
+ }
public ServiceReference getServiceReference(String clazz) {
return new MockServiceReference(getBundle(), new String[] { clazz });
}
- public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
- // Some jiggery-pokery to get round the fact that we don't ever use the
- // clazz
- if (clazz == null)
+ @Override
+ public <S> ServiceReference<S> getServiceReference(Class<S> clazz) {
+ @SuppressWarnings({"UnnecessaryLocalVariable", "unchecked"})
+ ServiceReference<S> result = (ServiceReference<S>) getServiceReference(clazz.getName());
+ return result;
+ }
+
+ @Override
+ public <S> Collection<ServiceReference<S>> getServiceReferences(Class<S> clazz, String filter) throws InvalidSyntaxException {
+ @SuppressWarnings("unchecked")
+ ServiceReference<S>[] refs = (ServiceReference<S>[]) getServiceReferences(clazz.getName(), filter);
+ if (refs == null) {
+ return Collections.emptyList();
+ }
+ List<ServiceReference<S>> result = new ArrayList<ServiceReference<S>>(refs.length);
+ for (ServiceReference<S> r : refs) {
+ result.add(r);
+ }
+ return result;
+ }
+
+ public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
+ // Some jiggery-pokery to get round the fact that we don't ever use the clazz
+ if (clazz == null) {
if (filter != null) {
// flatten filter since the constants might be case insensitive
String flattenFilter = filter.toLowerCase();
@@ -162,9 +224,10 @@
clazz = filter.substring(i + Constants.OBJECTCLASS.length() + 1);
clazz = clazz.substring(0, clazz.indexOf(")"));
}
- }
- else
+ } else {
clazz = Object.class.getName();
+ }
+ }
return new ServiceReference[] { new MockServiceReference(getBundle(), new String[] { clazz }) };
}
@@ -177,8 +240,7 @@
public Bundle installBundle(String location, InputStream input) throws BundleException {
try {
input.close();
- }
- catch (IOException ex) {
+ } catch (IOException ex) {
throw new BundleException("cannot close stream", ex);
}
return installBundle(location);
@@ -211,7 +273,14 @@
public void removeFrameworkListener(FrameworkListener listener) {
}
- public void removeServiceListener(ServiceListener listener) {
+ @Override
+ public <S> ServiceRegistration<S> registerService(Class<S> clazz, S service, Dictionary<String, ?> properties) {
+ @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
+ ServiceRegistration<S> registration = (ServiceRegistration<S>) registerService(clazz.getName(), service, properties);
+ return registration;
+ }
+
+ public void removeServiceListener(ServiceListener listener) {
serviceListeners.remove(listener);
}
@@ -235,7 +304,7 @@
*
* @return set of registered service listeners
*/
- public Set getServiceListeners() {
+ public Set<ServiceListener> getServiceListeners() {
return serviceListeners;
}
@@ -244,7 +313,7 @@
*
* @return set of registered bundle listeners
*/
- public Set getBundleListeners() {
+ public Set<BundleListener> getBundleListeners() {
return bundleListeners;
}
}
\ No newline at end of file
diff --git a/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockFilter.java b/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockFilter.java
index 2139c0e..e6397d1 100644
--- a/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockFilter.java
+++ b/mock/src/main/java/org/eclipse/gemini/blueprint/mock/MockFilter.java
@@ -15,6 +15,7 @@
package org.eclipse.gemini.blueprint.mock;
import java.util.Dictionary;
+import java.util.Map;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceReference;
@@ -63,4 +64,9 @@
public String toString() {
return filter;
}
+
+ @Override
+ public boolean matches(Map<String, ?> map) {
+ return false; //To change body of implemented methods use File | Settings | File Templates.
+ }
}
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 00e3f78..66cd4df 100644
--- a/pom.xml
+++ b/pom.xml
@@ -44,14 +44,14 @@
<env.buildNumber></env.buildNumber>
<!-- compiled against osgi Revision -->
- <osgi.ver>4.2.0</osgi.ver>
+ <osgi.ver>4.3.0</osgi.ver>
<!-- platform versions -->
<!-- equinox 3.7 is R4.3 impl -->
<!-- todo: would like to use this version -->
- <!--<equinox.ver>3.7.2.v20120110-1415</equinox.ver>-->
+ <equinox.ver>3.7.2.v20120110-1415</equinox.ver>
<!-- todo: only found this in public repos -->
<!-- note - another reason why ebr is so important -->
- <equinox.ver>3.7.1</equinox.ver>
+ <!--<equinox.ver>3.7.1</equinox.ver>-->
<!-- Knopflerfish 4.0.1 -->
<kf.ver>6.0.2</kf.ver>
<!-- Felix 4.x supports OSGi R4.3 -->
@@ -112,9 +112,7 @@
<scm>
<connection>scm:git:git//git.eclipse.org/gitroot/gemini.blueprint/org.eclipse.gemini.blueprint.git</connection>
- <developerConnection>
- ssh://{user.name}@git.eclipse.org/gitroot/gemini.blueprint/org.eclipse.gemini.blueprint.git
- </developerConnection>
+ <developerConnection>scm:git:ssh://{user.name}@git.eclipse.org/gitroot/gemini.blueprint/org.eclipse.gemini.blueprint.git</developerConnection>
</scm>
<developers>
@@ -600,9 +598,7 @@
<Bundle-SymbolicName>${spring.osgi.symbolic.name}.source</Bundle-SymbolicName>
<Bundle-Vendor>Eclipse Foundation</Bundle-Vendor>
<Bundle-DocURL>http://www.eclipse.org/gemini/blueprint/</Bundle-DocURL>
- <Bundle-License>http://www.opensource.org/licenses/eclipse-1.0.php,
- http://www.opensource.org/licenses/apache2.0.php
- </Bundle-License>
+ <Bundle-License>http://www.opensource.org/licenses/eclipse-1.0.php,http://www.opensource.org/licenses/apache2.0.php</Bundle-License>
<Implementation-Title>Eclipse Gemini Blueprint</Implementation-Title>
<Implementation-Version>${project.version}</Implementation-Version>
<Implementation-Vendor>Eclipse Foundation</Implementation-Vendor>
@@ -610,8 +606,7 @@
<Gemini-Blueprint-Version>${project.version}</Gemini-Blueprint-Version>
<Spring-Version>${spring.maven.artifact.version}</Spring-Version>
<Git-Revision>${git.commit.id.describe}</Git-Revision>
- <Eclipse-SourceBundle>${spring.osgi.symbolic.name};version="${project.version}";roots:="."
- </Eclipse-SourceBundle>
+ <Eclipse-SourceBundle>${spring.osgi.symbolic.name};version="${project.version}";roots:="."</Eclipse-SourceBundle>
</manifestEntries>
</archive>
</configuration>
@@ -774,7 +769,6 @@
</configuration>
</plugin>
-
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
@@ -1054,11 +1048,11 @@
<url>http://www.knopflerfish.org/maven2/</url>
</repository>
- <!--<repository>-->
- <!--<id>dmitry-local</id>-->
- <!--<name>Just Cause equinox 3.7.2 is not in central</name>-->
- <!--<url>http://localhost:9091/nexus/content/repositories/thirdparty/</url>-->
- <!--</repository>-->
+ <repository>
+ <id>dmitry-local</id>
+ <name>Just Cause equinox 3.7.2 is not in central</name>
+ <url>http://localhost:9091/nexus/content/repositories/thirdparty/</url>
+ </repository>
<repository>
<id>com.springsource.repository.bundles.release</id>
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractConfigurableBundleCreatorTests.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractConfigurableBundleCreatorTests.java
index c403729..830bdde 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractConfigurableBundleCreatorTests.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractConfigurableBundleCreatorTests.java
@@ -7,7 +7,7 @@
* http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0
* is available at http://www.opensource.org/licenses/apache2.0.php.
* You may elect to redistribute this code under either of these licenses.
- *
+ *
* Contributors:
* VMware Inc.
*****************************************************************************/
@@ -29,23 +29,23 @@
* builds on its super classes to allow full configuration of the underlying
* OSGi platform implementation, of the test bundle creation (including the
* manifest automatic generation).
- *
+ * <p/>
* <p/>This class follows the <em>traditional</em> Spring style of integration
* testing in which the test simply indicates the dependencies, leaving the rest
* of the work to be done by its super classes. Consider the following simple
* example:
- *
+ * <p/>
* <pre class="code">
* public class SimpleOsgiTest extends AbstractConfigurableBundleCreatorTests {
- *
- * public void testOsgiPlatformStarts() throws Exception {
- * System.out.println(bundleContext.getProperty(Constants.FRAMEWORK_VENDOR));
- * System.out.println(bundleContext.getProperty(Constants.FRAMEWORK_VERSION));
- * System.out.println(bundleContext.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT));
- * }
+ * <p/>
+ * public void testOsgiPlatformStarts() throws Exception {
+ * System.out.println(bundleContext.getProperty(Constants.FRAMEWORK_VENDOR));
+ * System.out.println(bundleContext.getProperty(Constants.FRAMEWORK_VERSION));
+ * System.out.println(bundleContext.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT));
+ * }
* }
* </pre>
- *
+ * <p/>
* <p/> The above class can be ran just like any other JUnit test. Equinox
* platform will be automatically started, the test will packed in an OSGi
* bundle (with its manifest created automatically) which will be deployed
@@ -54,9 +54,9 @@
* back to the running tool transparently. Please see the reference
* documentation for more examples, customization tips and help on how to do
* efficient and fast integration testing.
- *
+ * <p/>
* <p/> This class allows the test on-the-fly bundle (jar) can be configured
- * declaratively by indicating the locations for:
+ * declaratively by indicating the locations for:
* <ul>
* <li>root folder ({@value #ROOT_DIR}) - the starting point on which the
* resource patterns are applied</li>
@@ -72,153 +72,151 @@
* pattern "[testName]-bundle.properties", (i.e. /foo/bar/SomeTest will try to
* load file /foo/bar/SomeTest-bundle.properties). If no properties file is
* found, a set of defaults will be used.</li>
- *
+ * <p/>
* <li>overriding the default getXXX methods and providing an alternative
* implementation.</li>
* </ul>
- *
+ * <p/>
* <p/>Another useful functionality inherited from
* {@link AbstractOnTheFlyBundleCreatorTests} class is the ability to create a
* manifest for the test bundle on the fly, based on the classes present in the
* archive.
- *
+ * <p/>
* <p/><b>Note:</b> This class is the main testing framework entry point
- *
+ *
* @author Costin Leau
- *
* @see AbstractOnTheFlyBundleCreatorTests
*/
public abstract class AbstractConfigurableBundleCreatorTests extends AbstractOnTheFlyBundleCreatorTests {
- protected static final String ROOT_DIR = "root.dir";
+ protected static final String ROOT_DIR = "root.dir";
- protected static final String INCLUDE_PATTERNS = "include.patterns";
+ protected static final String INCLUDE_PATTERNS = "include.patterns";
- protected static final String LIBS = "libs";
+ protected static final String LIBS = "libs";
- protected static final String MANIFEST = "manifest";
+ protected static final String MANIFEST = "manifest";
- private static final Properties DEFAULT_SETTINGS = new Properties();
+ private static final Properties DEFAULT_SETTINGS = new Properties();
- static {
- DEFAULT_SETTINGS.setProperty(ROOT_DIR, Thread.currentThread().getContextClassLoader().getResource(".").toString());
- DEFAULT_SETTINGS.setProperty(INCLUDE_PATTERNS, JarCreator.EVERYTHING_PATTERN);
- DEFAULT_SETTINGS.setProperty(LIBS, "");
- DEFAULT_SETTINGS.setProperty(MANIFEST, "");
- }
+ static {
+ DEFAULT_SETTINGS.setProperty(ROOT_DIR, Thread.currentThread().getContextClassLoader().getResource(".").toString());
+ DEFAULT_SETTINGS.setProperty(INCLUDE_PATTERNS, JarCreator.EVERYTHING_PATTERN);
+ DEFAULT_SETTINGS.setProperty(LIBS, "");
+ DEFAULT_SETTINGS.setProperty(MANIFEST, "");
+ }
- /**
- * Settings for the jar creation. Static as it has to be cached between test
- * runs and it is being initialized once in
- * {@link #postProcessBundleContext(BundleContext)}.
- */
- private static Properties jarSettings;
+ /**
+ * Settings for the jar creation. Static as it has to be cached between test
+ * runs and it is being initialized once in
+ * {@link #postProcessBundleContext(BundleContext)}.
+ */
+ private static Properties jarSettings;
- protected String getRootPath() {
- return jarSettings.getProperty(ROOT_DIR);
- }
+ protected String getRootPath() {
+ return jarSettings.getProperty(ROOT_DIR);
+ }
- /**
- * {@inheritDoc}
- *
- * <p/>Ant-style patterns for identifying the resources added to the jar.The
- * patterns are considered from the root path when performing the search.
- *
- * <p/> By default, the content pattern is <code>**/*</code> which
- * includes all sources from the root. One can configure the pattern to
- * include specific files by using different patterns. For example, to
- * include just the classes, XML and properties files one can use the
- * following patterns:
- * <ol>
- * <li><code>**/*.class</code> for classes
- * <li><code>**/*.xml</code> for XML files
- * <li><code>**/*.properties</code> for properties files
- * </ol>
- *
- * @return array of Ant-style pattern
- */
- protected String[] getBundleContentPattern() {
- return StringUtils.commaDelimitedListToStringArray(jarSettings.getProperty(INCLUDE_PATTERNS));
- }
+ /**
+ * {@inheritDoc}
+ * <p/>
+ * <p/>Ant-style patterns for identifying the resources added to the jar.The
+ * patterns are considered from the root path when performing the search.
+ * <p/>
+ * <p/> By default, the content pattern is <code>**/*</code> which
+ * includes all sources from the root. One can configure the pattern to
+ * include specific files by using different patterns. For example, to
+ * include just the classes, XML and properties files one can use the
+ * following patterns:
+ * <ol>
+ * <li><code>**/*.class</code> for classes
+ * <li><code>**/*.xml</code> for XML files
+ * <li><code>**/*.properties</code> for properties files
+ * </ol>
+ *
+ * @return array of Ant-style pattern
+ */
+ protected String[] getBundleContentPattern() {
+ return StringUtils.commaDelimitedListToStringArray(jarSettings.getProperty(INCLUDE_PATTERNS));
+ }
- protected String getManifestLocation() {
- return jarSettings.getProperty(MANIFEST);
- }
+ protected String getManifestLocation() {
+ return jarSettings.getProperty(MANIFEST);
+ }
- /**
- * Returns the settings location (by default, the test name; i.e.
- * <code>foo.bar.SomeTest</code> will try to load
- * <code>foo/bar/SomeTest-bundle.properties</code>).
- *
- * @return settings location for this test
- */
- protected String getSettingsLocation() {
- return getClass().getName().replace('.', '/') + "-bundle.properties";
- }
+ /**
+ * Returns the settings location (by default, the test name; i.e.
+ * <code>foo.bar.SomeTest</code> will try to load
+ * <code>foo/bar/SomeTest-bundle.properties</code>).
+ *
+ * @return settings location for this test
+ */
+ protected String getSettingsLocation() {
+ return getClass().getName().replace('.', '/') + "-bundle.properties";
+ }
- /**
- * Returns the default settings used when creating the jar, in case no
- * customisations have been applied. Unless the base class is used as a
- * testing framework, consider using a properties file for specifying
- * specific properties for a test case.
- *
- * @return default settings for creating the jar
- * @see #getSettingsLocation()
- */
- protected Properties getDefaultSettings() {
- return DEFAULT_SETTINGS;
- }
+ /**
+ * Returns the default settings used when creating the jar, in case no
+ * customisations have been applied. Unless the base class is used as a
+ * testing framework, consider using a properties file for specifying
+ * specific properties for a test case.
+ *
+ * @return default settings for creating the jar
+ * @see #getSettingsLocation()
+ */
+ protected Properties getDefaultSettings() {
+ return DEFAULT_SETTINGS;
+ }
- /**
- * Returns the settings used for creating this jar. This method tries to
- * locate and load the settings from the location indicated by
- * {@link #getSettingsLocation()}. If no file is found, the default
- * settings will be used.
- *
- * <p/> A non-null properties object will always be returned.
- *
- * @return settings for creating the on the fly jar
- * @throws Exception if loading the settings file fails
- */
- protected Properties getSettings() throws Exception {
- Properties settings = new Properties(getDefaultSettings());
- // settings.setProperty(ROOT_DIR, getRootPath());
- Resource resource = new ClassPathResource(getSettingsLocation());
+ /**
+ * Returns the settings used for creating this jar. This method tries to
+ * locate and load the settings from the location indicated by
+ * {@link #getSettingsLocation()}. If no file is found, the default
+ * settings will be used.
+ * <p/>
+ * <p/> A non-null properties object will always be returned.
+ *
+ * @return settings for creating the on the fly jar
+ * @throws Exception if loading the settings file fails
+ */
+ protected Properties getSettings() throws Exception {
+ Properties settings = new Properties(getDefaultSettings());
+ // settings.setProperty(ROOT_DIR, getRootPath());
+ Resource resource = new ClassPathResource(getSettingsLocation());
- if (resource.exists()) {
- InputStream stream = resource.getInputStream();
- try {
- if (stream != null) {
- settings.load(stream);
- logger.debug("Loaded jar settings from " + getSettingsLocation());
- }
- }
- finally {
- IOUtils.closeStream(stream);
- }
- }
- else
- logger.info(getSettingsLocation() + " was not found; using defaults");
+ if (resource.exists()) {
+ InputStream stream = resource.getInputStream();
+ try {
+ if (stream != null) {
+ settings.load(stream);
+ logger.debug("Loaded jar settings from " + getSettingsLocation());
+ }
+ } finally {
+ IOUtils.closeStream(stream);
+ }
+ } else {
+ logger.info(getSettingsLocation() + " was not found; using defaults");
+ }
- return settings;
- }
+ return settings;
+ }
- /*
- * Loads the jar settings, first from the disk falling back to the default
- * settings, if none is found.
- */
- protected void postProcessBundleContext(BundleContext context) throws Exception {
- // hook in properties loading
+ /*
+ * Loads the jar settings, first from the disk falling back to the default
+ * settings, if none is found.
+ */
+ protected void postProcessBundleContext(BundleContext context) throws Exception {
+ // hook in properties loading
- // reset the settings (useful when running multiple tests)
- jarSettings = null;
- // load settings
- jarSettings = getSettings();
- // Somehow the JarCreator needs to get this
- jarCreator.setRootPath(getRootPath());
+ // reset the settings (useful when running multiple tests)
+ jarSettings = null;
+ // load settings
+ jarSettings = getSettings();
+ // Somehow the JarCreator needs to get this
+ jarCreator.setRootPath(getRootPath());
- super.postProcessBundleContext(context);
- }
+ super.postProcessBundleContext(context);
+ }
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractConfigurableOsgiTests.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractConfigurableOsgiTests.java
index 9dc9d55..e5b9dbe 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractConfigurableOsgiTests.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractConfigurableOsgiTests.java
@@ -81,26 +81,25 @@
if (ClassUtils.isPresent(platformClassName, currentCL)) {
Class<?> platformClass = ClassUtils.resolveClassName(platformClassName, currentCL);
if (OsgiPlatform.class.isAssignableFrom(platformClass)) {
- if (trace)
+ if (trace) {
logger.trace("Instantiating platform wrapper...");
+ }
+
try {
platform = (OsgiPlatform) platformClass.newInstance();
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
logger.warn("cannot instantiate class [" + platformClass + "]; using default");
}
- }
- else
+ } else {
logger.warn("Class [" + platformClass + "] does not implement " + OsgiPlatform.class.getName()
+ " interface; falling back to defaults");
- }
- else {
+ }
+ } else {
logger.warn("OSGi platform starter [" + platformClassName + "] not found; using default");
}
-
- }
- else
+ } else {
logger.trace("No platform specified; using default");
+ }
// fall back
if (platform == null)
@@ -108,8 +107,7 @@
Properties config = platform.getConfigurationProperties();
// add boot delegation
- config.setProperty(Constants.FRAMEWORK_BOOTDELEGATION,
- getBootDelegationPackageString());
+ config.setProperty(Constants.FRAMEWORK_BOOTDELEGATION, getBootDelegationPackageString());
return platform;
}
@@ -126,8 +124,9 @@
*/
protected String getPlatformName() {
String systemProperty = System.getProperty(OSGI_FRAMEWORK_SELECTOR);
- if (logger.isTraceEnabled())
+ if (logger.isTraceEnabled()) {
logger.trace("System property [" + OSGI_FRAMEWORK_SELECTOR + "] has value=" + systemProperty);
+ }
return (!StringUtils.hasText(systemProperty) ? Platforms.EQUINOX : systemProperty);
}
@@ -139,14 +138,12 @@
*/
private String getBootDelegationPackageString() {
StringBuilder buf = new StringBuilder();
-
- for (Iterator iter = getBootDelegationPackages().iterator(); iter.hasNext();) {
- buf.append(((String) iter.next()).trim());
+ for (Iterator<String> iter = getBootDelegationPackages().iterator(); iter.hasNext();) {
+ buf.append(iter.next().trim());
if (iter.hasNext()) {
buf.append(",");
}
}
-
return buf.toString();
}
@@ -158,8 +155,9 @@
* @return the list of strings representing the packages that the OSGi
* platform will delegate to the boot class path.
*/
- protected List getBootDelegationPackages() {
- List defaults = new ArrayList();
+ protected List<String> getBootDelegationPackages() {
+ List<String> defaults = new ArrayList<String>();
+
// javax packages
defaults.add("javax.*");
@@ -176,8 +174,7 @@
defaults.add("sun.*");
defaults.add("com.sun.*");
- // FIXME: the JAXP package (for 1.4 VMs) should be discovered in an OSGi
- // manner
+ // FIXME: the JAXP package (for 1.4 VMs) should be discovered in an OSGi manner
defaults.add("org.apache.xerces.jaxp.*");
return defaults;
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractDependencyManagerTests.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractDependencyManagerTests.java
index 2538559..03eabe8 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractDependencyManagerTests.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractDependencyManagerTests.java
@@ -46,7 +46,7 @@
*/
public abstract class AbstractDependencyManagerTests extends AbstractSynchronizedOsgiTests {
- private static final String TEST_FRRAMEWORK_BUNDLES_CONF_FILE = "/org/eclipse/gemini/blueprint/test/internal/boot-bundles.properties";
+ private static final String TEST_FRAMEWORK_BUNDLES_CONF_FILE = "/org/eclipse/gemini/blueprint/test/internal/boot-bundles.properties";
private static final String IGNORE = "ignore";
@@ -76,9 +76,7 @@
super(name);
}
-
private static final String GEMINI_BLUEPRINT_VERSION_PROP_KEY = "ignore.gemini.blueprint.version";
-
private static final String SPRING_VERSION_PROP_KEY = "ignore.spring.version";
/** uninitialised - read from the properties file */
@@ -124,8 +122,9 @@
}
});
}
- else
+ else {
return System.getProperty(name);
+ }
}
/**
@@ -169,14 +168,15 @@
// load properties file
Properties props = PropertiesUtil.loadAndExpand(getTestingFrameworkBundlesConfiguration());
- if (props == null)
- throw new IllegalArgumentException("cannot load default configuration from "
- + getTestingFrameworkBundlesConfiguration());
+ if (props == null) {
+ throw new IllegalArgumentException("cannot load default configuration from " + getTestingFrameworkBundlesConfiguration());
+ }
boolean trace = logger.isTraceEnabled();
- if (trace)
+ if (trace) {
logger.trace("Loaded properties " + props);
+ }
// pass properties to test instance running inside OSGi space
System.getProperties().put(GEMINI_BLUEPRINT_VERSION_PROP_KEY, props.get(GEMINI_BLUEPRINT_VERSION_PROP_KEY));
@@ -192,8 +192,9 @@
// sort the array (as the Properties file doesn't respect the order)
//bundles = StringUtils.sortStringArray(bundles);
- if (logger.isDebugEnabled())
+ if (logger.isDebugEnabled()) {
logger.debug("Default framework bundles :" + ObjectUtils.nullSafeToString(bundles));
+ }
return bundles;
}
@@ -204,8 +205,7 @@
* @return the location of the test framework bundles configuration
*/
protected Resource getTestingFrameworkBundlesConfiguration() {
- return new InputStreamResource(
- AbstractDependencyManagerTests.class.getResourceAsStream(TEST_FRRAMEWORK_BUNDLES_CONF_FILE));
+ return new InputStreamResource(AbstractDependencyManagerTests.class.getResourceAsStream(TEST_FRAMEWORK_BUNDLES_CONF_FILE));
}
/**
@@ -244,8 +244,9 @@
* @return an array of Spring resources for the given bundle indentifiers
*/
protected Resource[] locateBundles(String[] bundles) {
- if (bundles == null)
+ if (bundles == null) {
bundles = new String[0];
+ }
Resource[] res = new Resource[bundles.length];
for (int i = 0; i < bundles.length; i++) {
@@ -254,7 +255,6 @@
return res;
}
- // Set log4j property to avoid TCCL problems during startup
/**
* {@inheritDoc}
*
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOnTheFlyBundleCreatorTests.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOnTheFlyBundleCreatorTests.java
index d6f78ee..cd48554 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOnTheFlyBundleCreatorTests.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOnTheFlyBundleCreatorTests.java
@@ -80,6 +80,7 @@
/** field used for caching jar content */
private Map jarEntries;
+
/** discovered manifest */
private Manifest manifest;
@@ -188,13 +189,13 @@
// to resolve the patterns
jarEntries = jarCreator.resolveContent();
- for (Iterator iterator = jarEntries.entrySet().iterator(); iterator.hasNext();) {
- Map.Entry entry = (Map.Entry) iterator.next();
- if (META_INF_JAR_LOCATION.equals(entry.getKey())) {
- logger.info("Using Manifest from the test bundle content=[/META-INF/MANIFEST.MF]");
- manifest = createManifestFrom((Resource) entry.getValue());
- }
- }
+ for (Object o : jarEntries.entrySet()) {
+ Map.Entry entry = (Map.Entry) o;
+ if (META_INF_JAR_LOCATION.equals(entry.getKey())) {
+ logger.info("Using Manifest from the test bundle content=[/META-INF/MANIFEST.MF]");
+ manifest = createManifestFrom((Resource) entry.getValue());
+ }
+ }
// fallback to default manifest creation
if (manifest == null) {
@@ -259,8 +260,9 @@
// add Import-Package entry
addImportPackage(manifest);
- if (logger.isDebugEnabled())
+ if (logger.isDebugEnabled()) {
logger.debug("Created manifest:" + manifest.getMainAttributes().entrySet());
+ }
return manifest;
}
@@ -269,25 +271,26 @@
boolean trace = logger.isTraceEnabled();
- if (trace)
+ if (trace) {
logger.trace("Discovered raw imports " + ObjectUtils.nullSafeToString(rawImports));
+ }
Collection specialImportsOut = eliminateSpecialPackages(rawImports);
Collection imports = eliminatePackagesAvailableInTheJar(specialImportsOut);
- if (trace)
+ if (trace) {
logger.trace("Filtered imports are " + imports);
+ }
- manifest.getMainAttributes().putValue(Constants.IMPORT_PACKAGE,
- StringUtils.collectionToCommaDelimitedString(imports));
+ manifest.getMainAttributes().putValue(Constants.IMPORT_PACKAGE, StringUtils.collectionToCommaDelimitedString(imports));
}
/**
* Eliminate 'special' packages (java.*, test framework internal and the
* class declaring package)
*
- * @param rawImports
- * @return
+ * @param rawImports raw imports
+ * @return cleaned up imports
*/
private Collection eliminateSpecialPackages(String[] rawImports) {
String currentPckg = ClassUtils.classPackageAsResourcePath(getClass()).replace('/', '.');
@@ -298,14 +301,16 @@
for (int i = 0; i < rawImports.length; i++) {
String pckg = rawImports[i];
- if (!(pckg.startsWith("java.") || pckg.startsWith("org.eclipse.gemini.blueprint.test.internal") || pckg.equals(currentPckg)))
+ if (!(pckg.startsWith("java.") || pckg.startsWith("org.eclipse.gemini.blueprint.test.internal") || pckg.equals(currentPckg))) {
filteredImports.add(pckg);
- else
+ } else {
eliminatedImports.add(pckg);
+ }
}
- if (!eliminatedImports.isEmpty() && logger.isTraceEnabled())
+ if (!eliminatedImports.isEmpty() && logger.isTraceEnabled()) {
logger.trace("Eliminated special packages " + eliminatedImports);
+ }
return filteredImports;
}
@@ -319,8 +324,9 @@
*/
private Collection eliminatePackagesAvailableInTheJar(Collection imports) {
// no jar entry present, bail out.
- if (jarEntries == null || jarEntries.isEmpty())
+ if (jarEntries == null || jarEntries.isEmpty()) {
return imports;
+ }
Set filteredImports = new LinkedHashSet(imports.size());
Collection eliminatedImports = new LinkedHashSet(2);
@@ -328,10 +334,11 @@
Collection jarPackages = jarCreator.getContainedPackages();
for (Iterator iterator = imports.iterator(); iterator.hasNext();) {
String pckg = (String) iterator.next();
- if (jarPackages.contains(pckg))
+ if (jarPackages.contains(pckg)) {
eliminatedImports.add(pckg);
- else
+ } else {
filteredImports.add(pckg);
+ }
}
if (!eliminatedImports.isEmpty() && logger.isTraceEnabled())
logger.trace("Eliminated packages already present in the bundle " + eliminatedImports);
@@ -355,14 +362,12 @@
if (jarEntries == null || jarEntries.isEmpty()) {
logger.debug("No test jar content detected, generating bundle imports from the test class");
useTestClassOnly = true;
- }
-
- else if (createManifestOnlyFromTestClass()) {
+ } else if (createManifestOnlyFromTestClass()) {
logger.info("Using the test class for generating bundle imports");
useTestClassOnly = true;
- }
- else
+ } else {
logger.info("Using all classes in the jar for the generation of bundle imports");
+ }
// className, class resource
Map entries;
@@ -402,9 +407,9 @@
clazz = clazz.getSuperclass();
} while (!endPackage.equals(clazzPackage));
- }
- else
+ } else {
entries = jarEntries;
+ }
return determineImportsFor(entries);
@@ -426,31 +431,34 @@
// filter out the test hierarchy
if (resourceName.endsWith(ClassUtils.CLASS_FILE_SUFFIX)) {
- if (trace)
+ if (trace) {
logger.trace("Analyze imports for test bundle resource " + resourceName);
+ }
String classFileName = StringUtils.getFilename(resourceName);
- String className = classFileName.substring(0, classFileName.length()
- - ClassUtils.CLASS_FILE_SUFFIX.length());
- String classPkg = resourceName.substring(0, resourceName.length() - classFileName.length()).replace(
- '/', '.');
+ String className = classFileName.substring(0, classFileName.length() - ClassUtils.CLASS_FILE_SUFFIX.length());
+ String classPkg = resourceName.substring(0, resourceName.length() - classFileName.length()).replace('/', '.');
- if (classPkg.startsWith("."))
+ if (classPkg.startsWith(".")) {
classPkg = classPkg.substring(1);
+ }
- if (classPkg.endsWith("."))
+ if (classPkg.endsWith(".")) {
classPkg = classPkg.substring(0, classPkg.length() - 1);
+ }
// if we don't have the package, add it
if (validPackageCollection && StringUtils.hasText(classPkg) && !containedPackages.contains(classPkg)) {
- logger.trace("Package [" + classPkg + "] is NOT part of the test archive; adding an import for it");
+ if (trace) {
+ logger.trace("Package [" + classPkg + "] is NOT part of the test archive; adding an import for it");
+ }
cumulatedPackages.add(classPkg);
}
// otherwise parse the class byte-code
else {
- if (trace)
- logger.trace("Package [" + classPkg + "] is part of the test archive; parsing " + className
- + " bytecode to determine imports...");
+ if (trace) {
+ logger.trace("Package [" + classPkg + "] is part of the test archive; parsing " + className + " bytecode to determine imports...");
+ }
cumulatedPackages.addAll(determineImportsForClass(className, (Resource) entry.getValue()));
}
}
@@ -479,11 +487,11 @@
ClassReader reader;
try {
- if (trace)
+ if (trace) {
logger.trace("Visiting class " + className);
+ }
reader = new ClassReader(resource.getInputStream());
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
throw (RuntimeException) new IllegalArgumentException("Cannot read class " + className).initCause(ex);
}
reader.accept(visitor, false);
@@ -550,8 +558,9 @@
logger.debug(Constants.FRAMEWORK_BOOTDELEGATION + " = " + context.getProperty(Constants.FRAMEWORK_BOOTDELEGATION));
}
bundle.start();
- if (debug)
+ if (debug) {
logger.debug("Test bundle [" + bundleString + "] successfully started");
+ }
}
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOptionalDependencyInjectionTests.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOptionalDependencyInjectionTests.java
index f45ad7e..8faff3a 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOptionalDependencyInjectionTests.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOptionalDependencyInjectionTests.java
@@ -52,12 +52,8 @@
*
*/
// the disposable interface is added just so that byte code detect the org.springframework.beans.factory package
- private static class EmptyOsgiApplicationContext extends AbstractDelegatedExecutionApplicationContext implements
- DisposableBean {
-
- protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException, BeansException {
- }
-
+ private static class EmptyOsgiApplicationContext extends AbstractDelegatedExecutionApplicationContext implements DisposableBean {
+ protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException, BeansException {}
}
@@ -95,10 +91,11 @@
ConfigurableOsgiBundleApplicationContext context = null;
- if (ObjectUtils.isEmpty(locations))
+ if (ObjectUtils.isEmpty(locations)) {
context = new EmptyOsgiApplicationContext();
- else
+ } else {
context = new OsgiBundleXmlApplicationContext(locations);
+ }
context.setBundleContext(bundleContext);
context.refresh();
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOsgiTests.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOsgiTests.java
index 5421aa7..0c5614f 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOsgiTests.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractOsgiTests.java
@@ -7,7 +7,7 @@
* http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0
* is available at http://www.opensource.org/licenses/apache2.0.php.
* You may elect to redistribute this code under either of these licenses.
- *
+ *
* Contributors:
* VMware Inc.
*****************************************************************************/
@@ -41,491 +41,493 @@
/**
* Base test for OSGi environments. Takes care of configuring the chosen OSGi platform, starting it, installing a number
* of bundles and delegating the test execution to a test copy that runs inside OSGi.
- *
+ *
* @author Costin Leau
*/
public abstract class AbstractOsgiTests extends AbstractOptionalDependencyInjectionTests {
- private static final String UTF_8_CHARSET = "UTF-8";
+ private static final String UTF_8_CHARSET = "UTF-8";
- // JVM shutdown hook
- private static Thread shutdownHook;
+ // JVM shutdown hook
+ private static Thread shutdownHook;
- // the OSGi fixture
- private static OsgiPlatform osgiPlatform;
+ // the OSGi fixture
+ private static OsgiPlatform osgiPlatform;
- // OsgiPlatform bundle context
- private static BundleContext platformContext;
+ // OsgiPlatform bundle context
+ private static BundleContext platformContext;
- // JUnit Service
- private static Object service;
+ // JUnit Service
+ private static Object service;
- // JUnitService trigger
- private static Method serviceTrigger;
+ // JUnitService trigger
+ private static Method serviceTrigger;
- // the test results used by the triggering test runner
- private TestResult originalResult;
+ // the test results used by the triggering test runner
+ private TestResult originalResult;
- // OsgiResourceLoader
- protected ResourceLoader resourceLoader;
+ // OsgiResourceLoader
+ protected ResourceLoader resourceLoader;
- /**
- * Hook for JUnit infrastructures which can't reuse this class hierarchy. This instance represents the test which
- * will be executed by AbstractOsgiTests & co.
- */
- private TestCase osgiJUnitTest = this;
+ /**
+ * Hook for JUnit infrastructures which can't reuse this class hierarchy. This instance represents the test which
+ * will be executed by AbstractOsgiTests & co.
+ */
+ private TestCase osgiJUnitTest = this;
- private static final String ACTIVATOR_REFERENCE = "org.eclipse.gemini.blueprint.test.JUnitTestActivator";
+ private static final String ACTIVATOR_REFERENCE = "org.eclipse.gemini.blueprint.test.JUnitTestActivator";
- /**
- * Default constructor. Constructs a new <code>AbstractOsgiTests</code> instance.
- */
- public AbstractOsgiTests() {
- super();
- }
+ /**
+ * Default constructor. Constructs a new <code>AbstractOsgiTests</code> instance.
+ */
+ public AbstractOsgiTests() {
+ super();
+ }
- /**
- * Constructs a new <code>AbstractOsgiTests</code> instance.
- *
- * @param name test name
- */
- public AbstractOsgiTests(String name) {
- super(name);
- }
+ /**
+ * Constructs a new <code>AbstractOsgiTests</code> instance.
+ *
+ * @param name test name
+ */
+ public AbstractOsgiTests(String name) {
+ super(name);
+ }
- /**
- * Returns the test framework bundles (part of the test setup). Used by the test infrastructure. Override this
- * method <i>only</i> if you want to change the jars used by default, by the testing infrastructure.
- *
- * User subclasses should use {@link #getTestBundles()} instead.
- *
- * @return the array of test framework bundle resources
- */
- protected abstract Resource[] getTestFrameworkBundles();
+ /**
+ * Returns the test framework bundles (part of the test setup). Used by the test infrastructure. Override this
+ * method <i>only</i> if you want to change the jars used by default, by the testing infrastructure.
+ * <p/>
+ * User subclasses should use {@link #getTestBundles()} instead.
+ *
+ * @return the array of test framework bundle resources
+ */
+ protected abstract Resource[] getTestFrameworkBundles();
- /**
- * Returns the bundles required for the test execution.
- *
- * @return the array of bundles to install
- */
- protected abstract Resource[] getTestBundles();
+ /**
+ * Returns the bundles required for the test execution.
+ *
+ * @return the array of bundles to install
+ */
+ protected abstract Resource[] getTestBundles();
- /**
- * Creates (and configures) the OSGi platform.
- *
- * @return OSGi platform instance
- * @throws Exception if the platform creation fails
- */
- protected abstract OsgiPlatform createPlatform() throws Exception;
+ /**
+ * Creates (and configures) the OSGi platform.
+ *
+ * @return OSGi platform instance
+ * @throws Exception if the platform creation fails
+ */
+ protected abstract OsgiPlatform createPlatform() throws Exception;
- /**
- * Pre-processes the bundle context. This call back gives access to the platform bundle context before any bundles
- * have been installed. The method is invoked <b>after</b> starting the OSGi environment but <b>before</b> any
- * bundles are installed in the OSGi framework.
- *
- * <p/> Normally, this method is called only once during the lifecycle of a test suite.
- *
- * @param platformBundleContext the platform bundle context
- * @throws Exception if processing the bundle context fails
- * @see #postProcessBundleContext(BundleContext)
- *
- */
- protected void preProcessBundleContext(BundleContext platformBundleContext) throws Exception {
- }
+ /**
+ * Pre-processes the bundle context. This call back gives access to the platform bundle context before any bundles
+ * have been installed. The method is invoked <b>after</b> starting the OSGi environment but <b>before</b> any
+ * bundles are installed in the OSGi framework.
+ * <p/>
+ * <p/> Normally, this method is called only once during the lifecycle of a test suite.
+ *
+ * @param platformBundleContext the platform bundle context
+ * @throws Exception if processing the bundle context fails
+ * @see #postProcessBundleContext(BundleContext)
+ */
+ protected void preProcessBundleContext(BundleContext platformBundleContext) throws Exception {
+ }
- /**
- * Post-processes the bundle context. This call back gives access to the platform bundle context after the critical
- * test infrastructure bundles have been installed and started. The method is invoked <b>after</b> preparing the
- * OSGi environment for the test execution but <b>before</b> any test is executed.
- *
- * The given <code>BundleContext</code> belongs to the underlying OSGi framework.
- *
- * <p/> Normally, this method is called only one during the lifecycle of a test suite.
- *
- * @param platformBundleContext the platform bundle context
- * @see #preProcessBundleContext(BundleContext)
- */
- protected void postProcessBundleContext(BundleContext platformBundleContext) throws Exception {
- }
+ /**
+ * Post-processes the bundle context. This call back gives access to the platform bundle context after the critical
+ * test infrastructure bundles have been installed and started. The method is invoked <b>after</b> preparing the
+ * OSGi environment for the test execution but <b>before</b> any test is executed.
+ * <p/>
+ * The given <code>BundleContext</code> belongs to the underlying OSGi framework.
+ * <p/>
+ * <p/> Normally, this method is called only one during the lifecycle of a test suite.
+ *
+ * @param platformBundleContext the platform bundle context
+ * @see #preProcessBundleContext(BundleContext)
+ */
+ protected void postProcessBundleContext(BundleContext platformBundleContext) throws Exception {
+ }
- //
- // JUnit overridden methods.
- //
+ //
+ // JUnit overridden methods.
+ //
- /**
- * {@inheritDoc}
- *
- * <p/> Replacement run method. Gets a hold of the TestRunner used for running this test so it can populate it with
- * the results retrieved from OSGi.
- */
- public final void run(TestResult result) {
+ /**
+ * {@inheritDoc}
+ * <p/>
+ * <p/> Replacement run method. Gets a hold of the TestRunner used for running this test so it can populate it with
+ * the results retrieved from OSGi.
+ */
+ public final void run(TestResult result) {
- // get a hold of the test result
- originalResult = result;
+ // get a hold of the test result
+ originalResult = result;
- result.startTest(osgiJUnitTest);
- result.runProtected(osgiJUnitTest, new Protectable() {
+ result.startTest(osgiJUnitTest);
+ result.runProtected(osgiJUnitTest, new Protectable() {
- public void protect() throws Throwable {
- AbstractOsgiTests.this.runBare();
- }
- });
- result.endTest(osgiJUnitTest);
+ public void protect() throws Throwable {
+ AbstractOsgiTests.this.runBare();
+ }
+ });
+ result.endTest(osgiJUnitTest);
- // super.run(result);
- }
+ // super.run(result);
+ }
- public void runBare() throws Throwable {
- // add ConditionalTestCase behaviour
+ public void runBare() throws Throwable {
+ // add ConditionalTestCase behaviour
- // getName will return the name of the method being run
- if (isDisabledInThisEnvironment(getName())) {
- recordDisabled();
- logger.warn("**** " + getClass().getName() + "." + getName() + " disabled in this environment: "
- + "Total disabled tests=" + getDisabledTestCount());
- return;
- } else {
- prepareTestExecution();
- try {
- // invoke OSGi test run
- invokeOSGiTestExecution();
- readTestResult();
- } finally {
- // nothing to clean up
- }
- }
- }
+ // getName will return the name of the method being run
+ if (isDisabledInThisEnvironment(getName())) {
+ recordDisabled();
+ logger.warn("**** " + getClass().getName() + "." + getName() + " disabled in this environment: "
+ + "Total disabled tests=" + getDisabledTestCount());
+ } else {
+ prepareTestExecution();
+ // invoke OSGi test run
+ invokeOSGiTestExecution();
+ readTestResult();
- //
- // OSGi testing infrastructure setup.
- //
+ }
+ }
- /**
- * Starts the OSGi platform and install/start the bundles (happens once for the all test runs)
- *
- * @throws Exception
- */
- private void startup() throws Exception {
- if (osgiPlatform == null) {
+ //
+ // OSGi testing infrastructure setup.
+ //
- boolean debug = logger.isDebugEnabled();
+ /**
+ * Starts the OSGi platform and install/start the bundles (happens once for the all test runs)
+ *
+ * @throws Exception
+ */
+ private void startup() throws Exception {
+ if (osgiPlatform == null) {
- // make sure the platform is closed properly
- registerShutdownHook();
+ boolean debug = logger.isDebugEnabled();
- osgiPlatform = createPlatform();
- // start platform
- if (debug)
- logger.debug("About to start " + osgiPlatform);
- osgiPlatform.start();
- // platform context
- platformContext = osgiPlatform.getBundleContext();
+ // make sure the platform is closed properly
+ registerShutdownHook();
- // log platform name and version
- logPlatformInfo(platformContext);
+ osgiPlatform = createPlatform();
- // hook before the OSGi platform is setup but right after is has
- // been started
- preProcessBundleContext(platformContext);
+ // start platform
+ if (debug) {
+ logger.debug("About to start " + osgiPlatform);
+ }
- // install bundles (from the local system/classpath)
- Resource[] bundleResources = locateBundles();
+ osgiPlatform.start();
- Bundle[] bundles = new Bundle[bundleResources.length];
- for (int i = 0; i < bundles.length; i++) {
- bundles[i] = installBundle(bundleResources[i]);
- }
+ // platform context
+ platformContext = osgiPlatform.getBundleContext();
- // start bundles
- for (int i = 0; i < bundles.length; i++) {
- startBundle(bundles[i]);
- }
+ // log platform name and version
+ logPlatformInfo(platformContext);
- // hook after the OSGi platform has been setup
- postProcessBundleContext(platformContext);
+ // hook before the OSGi platform is setup but right after is has been started
+ preProcessBundleContext(platformContext);
- initializeServiceRunnerInvocationMethods();
- }
- }
+ // install bundles (from the local system/classpath)
+ Resource[] bundleResources = locateBundles();
- // concatenate bundles to install
- private Resource[] locateBundles() {
- Resource[] testFrameworkBundles = getTestFrameworkBundles();
- Resource[] testBundles = getTestBundles();
+ Bundle[] bundles = new Bundle[bundleResources.length];
+ for (int i = 0; i < bundles.length; i++) {
+ bundles[i] = installBundle(bundleResources[i]);
+ }
- if (testFrameworkBundles == null)
- testFrameworkBundles = new Resource[0];
- if (testBundles == null)
- testBundles = new Resource[0];
+ // start bundles
+ for (Bundle bundle : bundles) {
+ startBundle(bundle);
+ }
- Resource[] allBundles = new Resource[testFrameworkBundles.length + testBundles.length];
- System.arraycopy(testFrameworkBundles, 0, allBundles, 0, testFrameworkBundles.length);
- System.arraycopy(testBundles, 0, allBundles, testFrameworkBundles.length, testBundles.length);
- return allBundles;
- }
+ // hook after the OSGi platform has been setup
+ postProcessBundleContext(platformContext);
- /**
- * Logs the underlying OSGi information (which can be tricky).
- *
- */
- private void logPlatformInfo(BundleContext context) {
- StringBuilder platformInfo = new StringBuilder();
+ initializeServiceRunnerInvocationMethods();
+ }
+ }
- // add platform information
- platformInfo.append(osgiPlatform);
- platformInfo.append(" [");
- // Version
- platformInfo.append(OsgiPlatformDetector.getVersion(context));
- platformInfo.append("]");
- logger.info(platformInfo + " started");
- }
+ // concatenate bundles to install
+ private Resource[] locateBundles() {
+ Resource[] testFrameworkBundles = getTestFrameworkBundles();
+ Resource[] testBundles = getTestBundles();
- /**
- * Installs an OSGi bundle from the given location.
- *
- * @param location
- * @return
- * @throws Exception
- */
- private Bundle installBundle(Resource location) throws Exception {
- Assert.notNull(platformContext, "the OSGi platform is not set");
- Assert.notNull(location, "cannot install from a null location");
- if (logger.isDebugEnabled())
- logger.debug("Installing bundle from location " + location.getDescription());
+ if (testFrameworkBundles == null) {
+ testFrameworkBundles = new Resource[0];
+ }
+ if (testBundles == null) {
+ testBundles = new Resource[0];
+ }
- String bundleLocation;
+ Resource[] allBundles = new Resource[testFrameworkBundles.length + testBundles.length];
+ System.arraycopy(testFrameworkBundles, 0, allBundles, 0, testFrameworkBundles.length);
+ System.arraycopy(testBundles, 0, allBundles, testFrameworkBundles.length, testBundles.length);
+ return allBundles;
+ }
- try {
- bundleLocation = URLDecoder.decode(location.getURL().toExternalForm(), UTF_8_CHARSET);
- } catch (Exception ex) {
- // the URL cannot be created, fall back to the description
- bundleLocation = location.getDescription();
- }
+ /**
+ * Logs the underlying OSGi information (which can be tricky).
+ */
+ private void logPlatformInfo(BundleContext context) {
+ StringBuilder platformInfo = new StringBuilder();
- return platformContext.installBundle(bundleLocation, location.getInputStream());
- }
+ // add platform information
+ platformInfo.append(osgiPlatform);
+ platformInfo.append(" [");
+ // Version
+ platformInfo.append(OsgiPlatformDetector.getVersion(context));
+ platformInfo.append("]");
+ logger.info(platformInfo + " started");
+ }
- /**
- * Starts a bundle and prints a nice logging message in case of failure.
- *
- * @param bundle
- * @return
- * @throws BundleException
- */
- private void startBundle(Bundle bundle) throws BundleException {
- boolean debug = logger.isDebugEnabled();
- String info = "[" + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "|" + bundle.getLocation() + "]";
+ /**
+ * Installs an OSGi bundle from the given location.
+ *
+ * @param location - location bundle to install
+ * @return bundle instance
+ * @throws Exception
+ */
+ private Bundle installBundle(Resource location) throws Exception {
+ Assert.notNull(platformContext, "the OSGi platform is not set");
+ Assert.notNull(location, "cannot install from a null location");
+ if (logger.isDebugEnabled())
+ logger.debug("Installing bundle from location " + location.getDescription());
- if (!OsgiBundleUtils.isFragment(bundle)) {
- if (debug)
- logger.debug("Starting " + info);
- try {
- bundle.start();
- } catch (BundleException ex) {
- logger.error("cannot start bundle " + info, ex);
- throw ex;
- }
- } else {
+ String bundleLocation;
+
+ try {
+ bundleLocation = URLDecoder.decode(location.getURL().toExternalForm(), UTF_8_CHARSET);
+ } catch (Exception ex) {
+ // the URL cannot be created, fall back to the description
+ bundleLocation = location.getDescription();
+ }
+
+ return platformContext.installBundle(bundleLocation, location.getInputStream());
+ }
+
+ /**
+ * Starts a bundle and prints a nice logging message in case of failure.
+ *
+ * @param bundle to start
+ * @throws BundleException
+ */
+ private void startBundle(Bundle bundle) throws BundleException {
+ boolean debug = logger.isDebugEnabled();
+ String info = "[" + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "|" + bundle.getLocation() + "]";
+
+ if (!OsgiBundleUtils.isFragment(bundle)) {
+ if (debug)
+ logger.debug("Starting " + info);
+ try {
+ bundle.start();
+ } catch (BundleException ex) {
+ logger.error("cannot start bundle " + info, ex);
+ throw ex;
+ }
+ } else {
// if (!OsgiBundleUtils.isBundleResolved(bundle)) {
// logger.error("fragment not resolved: " + info);
// throw new BundleException("Unable to resolve fragment: " + info);
// } else if (debug)
- logger.debug(info + " is a fragment; start not invoked");
- }
- }
+ logger.debug(info + " is a fragment; start not invoked");
+ }
+ }
- //
- // Delegation methods for OSGi execution and initialization
- //
+ //
+ // Delegation methods for OSGi execution and initialization
+ //
- // runs outside OSGi
- /**
- * Prepares test execution - the OSGi platform will be started (if needed) and cached for the test suite execution.
- */
- private void prepareTestExecution() throws Exception {
+ // runs outside OSGi
- if (getName() == null)
- throw new IllegalArgumentException("no test specified");
+ /**
+ * Prepares test execution - the OSGi platform will be started (if needed) and cached for the test suite execution.
+ */
+ private void prepareTestExecution() throws Exception {
- // clear test results
- OsgiTestInfoHolder.INSTANCE.clearResults();
- // set test class
- OsgiTestInfoHolder.INSTANCE.setTestClassName(osgiJUnitTest.getClass().getName());
+ if (getName() == null) {
+ throw new IllegalArgumentException("no test specified");
+ }
- // start OSGi platform (the caching is done inside the method).
- try {
- startup();
- } catch (Exception e) {
- logger.debug("Caught exception starting up", e);
- throw e;
- }
+ // clear test results
+ OsgiTestInfoHolder.INSTANCE.clearResults();
+ // set test class
+ OsgiTestInfoHolder.INSTANCE.setTestClassName(osgiJUnitTest.getClass().getName());
- if (logger.isTraceEnabled())
- logger.trace("Writing test name [" + getName() + "] to OSGi");
+ // start OSGi platform (the caching is done inside the method).
+ try {
+ startup();
+ } catch (Exception e) {
+ logger.debug("Caught exception starting up", e);
+ throw e;
+ }
- // write test name to OSGi
- // set test method name
- OsgiTestInfoHolder.INSTANCE.setTestMethodName(getName());
- }
+ if (logger.isTraceEnabled())
+ logger.trace("Writing test name [" + getName() + "] to OSGi");
- /**
- * Delegates the test execution to the OSGi copy.
- *
- * @throws Exception
- */
- private void invokeOSGiTestExecution() throws Exception {
- Assert.notNull(serviceTrigger, "no executeTest() method found on: " + service.getClass());
- try {
- serviceTrigger.invoke(service, null);
- } catch (InvocationTargetException ex) {
- Throwable th = ex.getCause();
- if (th instanceof Exception)
- throw ((Exception) th);
- else
- throw ((Error) th);
- }
- }
+ // write test name to OSGi
+ // set test method name
+ OsgiTestInfoHolder.INSTANCE.setTestMethodName(getName());
+ }
- /**
- * Determines through reflection the methods used for invoking the TestRunnerService.
- *
- * @throws Exception
- */
- private void initializeServiceRunnerInvocationMethods() throws Exception {
- // get JUnit test service reference
- // this is a loose reference - update it if the JUnitTestActivator
- // class is
- // changed.
+ /**
+ * Delegates the test execution to the OSGi copy.
+ *
+ * @throws Exception
+ */
+ private void invokeOSGiTestExecution() throws Exception {
+ Assert.notNull(serviceTrigger, "no executeTest() method found on: " + service.getClass());
+ try {
+ serviceTrigger.invoke(service);
+ } catch (InvocationTargetException ex) {
+ Throwable th = ex.getCause();
+ if (th instanceof Exception) {
+ throw ((Exception) th);
+ } else {
+ throw ((Error) th);
+ }
+ }
+ }
- BundleContext ctx = getRuntimeBundleContext();
+ /**
+ * Determines through reflection the methods used for invoking the TestRunnerService.
+ *
+ * @throws Exception
+ */
+ private void initializeServiceRunnerInvocationMethods() throws Exception {
+ // get JUnit test service reference
+ // this is a loose reference - update it if the JUnitTestActivator class is changed.
- ServiceReference reference = ctx.getServiceReference(ACTIVATOR_REFERENCE);
- Assert.notNull(reference, "no OSGi service reference found at " + ACTIVATOR_REFERENCE);
+ BundleContext ctx = getRuntimeBundleContext();
- service = ctx.getService(reference);
- Assert.notNull(service, "no service found for reference: " + reference);
+ ServiceReference reference = ctx.getServiceReference(ACTIVATOR_REFERENCE);
+ Assert.notNull(reference, "no OSGi service reference found at " + ACTIVATOR_REFERENCE);
- serviceTrigger = service.getClass().getDeclaredMethod("executeTest", null);
- ReflectionUtils.makeAccessible(serviceTrigger);
- Assert.notNull(serviceTrigger, "no executeTest() method found on: " + service.getClass());
- }
+ service = ctx.getService(reference);
+ Assert.notNull(service, "no service found for reference: " + reference);
- /**
- * Tries to get the bundle context for spring-osgi-test-support bundle. This is useful on platform where the
- * platformContext or system BundleContext doesn't behave like a normal context.
- *
- * Will fallback to {@link #platformContext}.
- *
- * @return
- */
- private BundleContext getRuntimeBundleContext() {
+ serviceTrigger = service.getClass().getDeclaredMethod("executeTest", new Class[0]);
+ ReflectionUtils.makeAccessible(serviceTrigger);
+ Assert.notNull(serviceTrigger, "no executeTest() method found on: " + service.getClass());
+ }
- // read test bundle id property
- Long id = OsgiTestInfoHolder.INSTANCE.getTestBundleId();
+ /**
+ * Tries to get the bundle context for test-support bundle. This is useful on platform where the
+ * platformContext or system BundleContext doesn't behave like a normal context.
+ * <p/>
+ * Will fallback to {@link #platformContext}.
+ *
+ * @return BundleContext of test-support bundle
+ */
+ private BundleContext getRuntimeBundleContext() {
- BundleContext ctx = null;
- if (id != null)
- try {
- ctx = OsgiBundleUtils.getBundleContext(platformContext.getBundle(id.longValue()));
- } catch (RuntimeException ex) {
- logger.trace("cannot determine bundle context for bundle " + id, ex);
- }
+ // read test bundle id property
+ Long id = OsgiTestInfoHolder.INSTANCE.getTestBundleId();
- return (ctx == null ? platformContext : ctx);
- }
+ BundleContext ctx = null;
+ if (id != null) {
+ try {
+ ctx = OsgiBundleUtils.getBundleContext(platformContext.getBundle(id));
+ } catch (RuntimeException ex) {
+ logger.trace("cannot determine bundle context for bundle " + id, ex);
+ }
+ }
- // runs outside OSGi
- private void readTestResult() {
- if (logger.isTraceEnabled())
- logger.trace("Reading OSGi results for test [" + getName() + "]");
+ return (ctx == null ? platformContext : ctx);
+ }
- // copy results from OSGi into existing test result
- TestUtils.cloneTestResults(OsgiTestInfoHolder.INSTANCE, originalResult, osgiJUnitTest);
+ // runs outside OSGi
+ private void readTestResult() {
+ if (logger.isTraceEnabled()) {
+ logger.trace("Reading OSGi results for test [" + getName() + "]");
+ }
- if (logger.isTraceEnabled())
- logger.debug("Test[" + getName() + "]'s result read");
- }
+ // copy results from OSGi into existing test result
+ TestUtils.cloneTestResults(OsgiTestInfoHolder.INSTANCE, originalResult, osgiJUnitTest);
- /**
- * Special shutdown hook.
- */
- private void registerShutdownHook() {
- if (shutdownHook == null) {
- // No shutdown hook registered yet.
- shutdownHook = new Thread() {
+ if (logger.isTraceEnabled()) {
+ logger.debug("Test[" + getName() + "]'s result read");
+ }
+ }
- public void run() {
- shutdownTest();
- }
- };
- Runtime.getRuntime().addShutdownHook(shutdownHook);
- }
- }
+ /**
+ * Special shutdown hook.
+ */
+ private void registerShutdownHook() {
+ if (shutdownHook == null) {
+ // No shutdown hook registered yet.
+ shutdownHook = new Thread() {
- /**
- * Cleanup for the test suite.
- */
- private void shutdownTest() {
- logger.info("Shutting down OSGi platform");
- if (osgiPlatform != null) {
- try {
- osgiPlatform.stop();
- } catch (Exception ex) {
- // swallow
- logger.warn("Shutdown procedure threw exception " + ex);
- }
- osgiPlatform = null;
- }
- }
+ public void run() {
+ shutdownTest();
+ }
+ };
+ Runtime.getRuntime().addShutdownHook(shutdownHook);
+ }
+ }
- //
- // OsgiJUnitTest execution hooks. Used by the test framework.
- //
+ /**
+ * Cleanup for the test suite.
+ */
+ private void shutdownTest() {
+ logger.info("Shutting down OSGi platform");
+ if (osgiPlatform != null) {
+ try {
+ osgiPlatform.stop();
+ } catch (Exception ex) {
+ // swallow
+ logger.warn("Shutdown procedure threw exception " + ex);
+ }
+ osgiPlatform = null;
+ }
+ }
- /**
- * Set the bundle context to be used by this test.
- *
- * <p/> This method is called automatically by the test infrastructure after the OSGi platform is being setup.
- */
- private void injectBundleContext(BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- // instantiate ResourceLoader
- this.resourceLoader = new OsgiBundleResourceLoader(bundleContext.getBundle());
- }
+ //
+ // OsgiJUnitTest execution hooks. Used by the test framework.
+ //
- /**
- * Set the underlying OsgiJUnitTest used for the test delegation.
- *
- * <p/> This method is called automatically by the test infrastructure after the OSGi platform is being setup.
- *
- * @param test
- */
- private void injectOsgiJUnitTest(TestCase test) {
- this.osgiJUnitTest = test;
- }
+ /**
+ * Set the bundle context to be used by this test.
+ * <p/>
+ * <p/> This method is called automatically by the test infrastructure after the OSGi platform is being setup.
+ */
+ private void injectBundleContext(BundleContext bundleContext) {
+ this.bundleContext = bundleContext;
+ // instantiate ResourceLoader
+ this.resourceLoader = new OsgiBundleResourceLoader(bundleContext.getBundle());
+ }
- /**
- * the setUp version for the OSGi environment.
- *
- * @throws Exception
- */
- private void osgiSetUp() throws Exception {
- // call the normal onSetUp
- setUp();
- }
+ /**
+ * Set the underlying OsgiJUnitTest used for the test delegation.
+ * <p/>
+ * <p/> This method is called automatically by the test infrastructure after the OSGi platform is being setup.
+ *
+ * @param test
+ */
+ private void injectOsgiJUnitTest(TestCase test) {
+ this.osgiJUnitTest = test;
+ }
- private void osgiTearDown() throws Exception {
- // call the normal tearDown
- tearDown();
- }
+ /**
+ * the setUp version for the OSGi environment.
+ *
+ * @throws Exception
+ */
+ private void osgiSetUp() throws Exception {
+ // call the normal onSetUp
+ setUp();
+ }
- /**
- * Actual test execution (delegates to the superclass implementation).
- *
- * @throws Throwable
- */
- private void osgiRunTest() throws Throwable {
- super.runTest();
- }
+ private void osgiTearDown() throws Exception {
+ // call the normal tearDown
+ tearDown();
+ }
+
+ /**
+ * Actual test execution (delegates to the superclass implementation).
+ *
+ * @throws Throwable
+ */
+ private void osgiRunTest() throws Throwable {
+ super.runTest();
+ }
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractSynchronizedOsgiTests.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractSynchronizedOsgiTests.java
index 96008ad..8b6236d 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractSynchronizedOsgiTests.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/AbstractSynchronizedOsgiTests.java
@@ -14,6 +14,7 @@
package org.eclipse.gemini.blueprint.test;
+import java.net.URL;
import java.util.Enumeration;
import org.eclipse.gemini.blueprint.extender.internal.util.concurrent.Counter;
@@ -158,7 +159,8 @@
* @see #getDefaultWaitTime()
* @see #waitOnContextCreation(BundleContext, String, long)
*/
- protected void waitOnContextCreation(String forBundleWithSymbolicName) {
+ @SuppressWarnings("UnusedDeclaration")
+ protected void waitOnContextCreation(String forBundleWithSymbolicName) {
waitOnContextCreation(forBundleWithSymbolicName, getDefaultWaitTime());
}
@@ -202,29 +204,30 @@
if (shouldWaitForSpringBundlesContextCreation()) {
boolean debug = logger.isDebugEnabled();
boolean trace = logger.isTraceEnabled();
- if (debug)
+ if (debug) {
logger.debug("Looking for Spring/OSGi powered bundles to wait for...");
+ }
// determine Spring/OSGi bundles
Bundle[] bundles = platformBundleContext.getBundles();
- for (int i = 0; i < bundles.length; i++) {
- Bundle bundle = bundles[i];
- String bundleName = OsgiStringUtils.nullSafeSymbolicName(bundle);
- if (OsgiBundleUtils.isBundleActive(bundle)) {
- if (isSpringDMManaged(bundle) && ConfigUtils.getPublishContext(bundle.getHeaders())) {
- if (debug)
- logger.debug("Bundle [" + bundleName + "] triggers a context creation; waiting for it");
- // use platformBundleContext
- waitOnContextCreation(platformBundleContext, bundleName, getDefaultWaitTime());
- }
- else if (trace)
- logger.trace("Bundle [" + bundleName + "] does not trigger a context creation.");
- }
- else {
- if (trace)
- logger.trace("Bundle [" + bundleName + "] is not active (probably a fragment); ignoring");
- }
- }
+ for (Bundle bundle : bundles) {
+ String bundleName = OsgiStringUtils.nullSafeSymbolicName(bundle);
+ if (OsgiBundleUtils.isBundleActive(bundle)) {
+ if (isSpringDMManaged(bundle) && ConfigUtils.getPublishContext(bundle.getHeaders())) {
+ if (debug) {
+ logger.debug("Bundle [" + bundleName + "] triggers a context creation; waiting for it");
+ }
+ // use platformBundleContext
+ waitOnContextCreation(platformBundleContext, bundleName, getDefaultWaitTime());
+ } else if (trace) {
+ logger.trace("Bundle [" + bundleName + "] does not trigger a context creation.");
+ }
+ } else {
+ if (trace) {
+ logger.trace("Bundle [" + bundleName + "] is not active (probably a fragment); ignoring");
+ }
+ }
+ }
}
}
@@ -233,13 +236,15 @@
* is used at startup, for waiting on all Spring DM contexts to be properly
* started and published.
*
- * @param bundle
- * @return
+ * @param bundle bundle to check
+ * @return boolean true if spring managed or false.
*/
protected boolean isSpringDMManaged(Bundle bundle) {
- if (!ObjectUtils.isEmpty(ConfigUtils.getHeaderLocations(bundle.getHeaders())))
+ if (!ObjectUtils.isEmpty(ConfigUtils.getHeaderLocations(bundle.getHeaders()))) {
return true;
- Enumeration enm = bundle.findEntries("META-INF/spring", "*.xml", false);
+ }
+ // TODO: do we need to check for blueprint?
+ Enumeration<URL> enm = bundle.findEntries("META-INF/spring", "*.xml", false);
return (enm != null && enm.hasMoreElements());
}
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/JUnitTestActivator.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/JUnitTestActivator.java
index 2dc3bdb..8ef7f25 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/JUnitTestActivator.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/JUnitTestActivator.java
@@ -36,7 +36,7 @@
* the test execution. This class is used by the testing framework to run
* integration tests inside the OSGi framework.
*
- * <strong>Note:</strong> Programatic usage of this class is strongly
+ * <strong>Note:</strong> Programmatic usage of this class is strongly
* discouraged as its semantics might change in the future - in fact, the only
* reason this class is public is because the OSGi specification requires this.
*
@@ -47,21 +47,20 @@
private static final Log log = LogFactory.getLog(JUnitTestActivator.class);
private BundleContext context;
- private ServiceReference reference;
- private ServiceRegistration registration;
+ private ServiceReference<TestRunnerService> reference;
+ private ServiceRegistration<JUnitTestActivator> registration;
private TestRunnerService service;
public void start(BundleContext bc) throws Exception {
this.context = bc;
- reference = context.getServiceReference(TestRunnerService.class.getName());
- if (reference == null)
+ reference = context.getServiceReference(TestRunnerService.class);
+ if (reference == null) {
throw new IllegalArgumentException("cannot find service at " + TestRunnerService.class.getName());
- service = (TestRunnerService) context.getService(reference);
-
- registration = context.registerService(JUnitTestActivator.class.getName(), this, new Hashtable());
-
+ }
+ service = context.getService(reference);
+ registration = context.registerService(JUnitTestActivator.class, this, new Hashtable<String, Object>());
}
/**
@@ -100,6 +99,7 @@
public void stop(BundleContext bc) throws Exception {
OsgiServiceUtils.unregisterService(registration);
+ reference = null;
}
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/HolderLoader.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/HolderLoader.java
index b25f50c..ce2bc29 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/HolderLoader.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/HolderLoader.java
@@ -53,21 +53,19 @@
Class<?> clazz;
try {
clazz = appCL.loadClass(HOLDER_CLASS_NAME);
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
// if it's not found, then the class path is incorrectly constructed
- throw (RuntimeException) new IllegalStateException(
- "spring-osgi-test.jar is not available on the boot class path; are you deploying the test framework"
- + "as a bundle by any chance? ").initCause(ex);
+ throw new IllegalStateException(
+ "gemini-blueprint-test.jar is not available on the boot class path; are you deploying the test framework"
+ + "as a bundle by any chance? ", ex);
}
// get the static instance
Field field = ReflectionUtils.findField(clazz, INSTANCE_FIELD, clazz);
Object instance;
try {
instance = field.get(null);
- }
- catch (Exception ex) {
- throw (RuntimeException) new IllegalStateException("Cannot read property " + INSTANCE_FIELD).initCause(ex);
+ } catch (Exception ex) {
+ throw new IllegalStateException("Cannot read property " + INSTANCE_FIELD, ex);
}
// once the class is loaded return it wrapped through it's OSGi instance
holder = new ReflectionOsgiHolder(instance);
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/OsgiTestInfoHolder.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/OsgiTestInfoHolder.java
index 3a39e6b..7307f15 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/OsgiTestInfoHolder.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/OsgiTestInfoHolder.java
@@ -28,8 +28,8 @@
public class OsgiTestInfoHolder {
/** JUnit test problems */
- private List testFailures = new ArrayList(4);
- private List testErrors = new ArrayList(4);
+ private List<Throwable> testFailures = new ArrayList<Throwable>(4);
+ private List<Throwable> testErrors = new ArrayList<Throwable>(4);
/** test bundle id */
private Long testBundleId;
@@ -108,11 +108,11 @@
this.testMethodName = testMethodName;
}
- public List getTestFailures() {
+ public List<Throwable> getTestFailures() {
return testFailures;
}
- public List getTestErrors() {
+ public List<Throwable> getTestErrors() {
return testErrors;
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/ReflectionOsgiHolder.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/ReflectionOsgiHolder.java
index 5e282db..f1f2a86 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/ReflectionOsgiHolder.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/holder/ReflectionOsgiHolder.java
@@ -39,7 +39,7 @@
* given object and accessing it through reflection. This constructor is
* used for accessing the instance loaded outside OSGi, from within OSGi.
*
- * @param twinInstance
+ * @param twinInstance instance to wrap
*/
ReflectionOsgiHolder(Object twinInstance) {
Assert.notNull(twinInstance);
@@ -49,8 +49,8 @@
GET_TEST_CLASS_NAME = ReflectionUtils.findMethod(clazz, "getTestClassName");
GET_TEST_METHOD_NAME = ReflectionUtils.findMethod(clazz, "getTestMethodName");
- ADD_TEST_ERROR = ReflectionUtils.findMethod(clazz, "addTestError", new Class<?>[] { Throwable.class });
- ADD_TEST_FAILURE = ReflectionUtils.findMethod(clazz, "addTestFailure", new Class<?>[] { Throwable.class });
+ ADD_TEST_ERROR = ReflectionUtils.findMethod(clazz, "addTestError", Throwable.class);
+ ADD_TEST_FAILURE = ReflectionUtils.findMethod(clazz, "addTestFailure", Throwable.class);
}
@@ -67,11 +67,11 @@
}
public void addTestError(Throwable testProblem) {
- ReflectionUtils.invokeMethod(ADD_TEST_ERROR, instance, new Object[] { testProblem });
+ ReflectionUtils.invokeMethod(ADD_TEST_ERROR, instance, testProblem);
}
public void addTestFailure(Throwable testProblem) {
- ReflectionUtils.invokeMethod(ADD_TEST_FAILURE, instance, new Object[] { testProblem });
+ ReflectionUtils.invokeMethod(ADD_TEST_FAILURE, instance, testProblem);
}
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/support/Activator.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/support/Activator.java
index d332c85..7a71906 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/support/Activator.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/support/Activator.java
@@ -29,21 +29,22 @@
*/
public class Activator implements BundleActivator {
- private ServiceRegistration registration;
+ private ServiceRegistration<TestRunnerService> registration;
public void start(BundleContext context) throws Exception {
- registration = context.registerService(TestRunnerService.class.getName(), new OsgiJUnitService(), null);
+ registration = context.registerService(TestRunnerService.class, new OsgiJUnitService(), null);
// add also the bundle id so that AbstractOsgiTest can determine its BundleContext when used in an environment
// where the system bundle is treated as a special case.
- HolderLoader.INSTANCE.getHolder().setTestBundleId(new Long(context.getBundle().getBundleId()));
+ HolderLoader.INSTANCE.getHolder().setTestBundleId(context.getBundle().getBundleId());
}
public void stop(BundleContext context) throws Exception {
// unregister the service even though the framework should do this automatically
- if (registration != null)
+ if (registration != null) {
registration.unregister();
+ }
}
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/support/OsgiJUnitService.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/support/OsgiJUnitService.java
index 4d117b3..e61b417 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/support/OsgiJUnitService.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/support/OsgiJUnitService.java
@@ -7,7 +7,7 @@
* http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0
* is available at http://www.opensource.org/licenses/apache2.0.php.
* You may elect to redistribute this code under either of these licenses.
- *
+ *
* Contributors:
* VMware Inc.
*****************************************************************************/
@@ -29,88 +29,87 @@
/**
* OSGi service for executing JUnit tests.
- *
+ *
* @author Costin Leau
- *
*/
public class OsgiJUnitService implements TestRunnerService {
- private static final Log log = LogFactory.getLog(OsgiJUnitService.class);
+ private static final Log log = LogFactory.getLog(OsgiJUnitService.class);
- public void runTest(OsgiJUnitTest test) {
- try {
- executeTest(test);
- }
- catch (Exception ex) {
- if (ex instanceof RuntimeException) {
- throw (RuntimeException) ex;
- }
- throw new RuntimeException("cannot execute test:" + ex, ex);
- }
- }
+ public void runTest(OsgiJUnitTest test) {
+ try {
+ executeTest(test);
+ } catch (Exception ex) {
+ if (ex instanceof RuntimeException) {
+ throw (RuntimeException) ex;
+ }
+ throw new RuntimeException("cannot execute test:" + ex, ex);
+ }
+ }
- /**
- * Execute the JUnit test and publish results to the outside-OSGi world.
- *
- * @param test
- * @throws Exception
- */
- protected void executeTest(OsgiJUnitTest test) throws Exception {
- // create holder
- // since we're inside OSGi, we have to use the special loading procedure
- OsgiTestInfoHolder holder = HolderLoader.INSTANCE.getHolder();
+ /**
+ * Execute the JUnit test and publish results to the outside-OSGi world.
+ *
+ * @param test
+ * @throws Exception
+ */
+ protected void executeTest(OsgiJUnitTest test) throws Exception {
+ // create holder
+ // since we're inside OSGi, we have to use the special loading procedure
+ OsgiTestInfoHolder holder = HolderLoader.INSTANCE.getHolder();
- // read the test to be executed
- String testName = holder.getTestMethodName();
- if (log.isDebugEnabled())
- log.debug("Reading test [" + testName + "] for execution inside OSGi");
- // execute the test
- TestResult result = runTest(test, testName);
+ // read the test to be executed
+ String testName = holder.getTestMethodName();
+ if (log.isDebugEnabled()) {
+ log.debug("Reading test [" + testName + "] for execution inside OSGi");
+ }
+ // execute the test
+ TestResult result = runTest(test, testName);
- if (log.isDebugEnabled())
- log.debug("Sending test results from OSGi");
- // write result back to the outside world
- TestUtils.unpackProblems(result, holder);
- }
+ if (log.isDebugEnabled()) {
+ log.debug("Sending test results from OSGi");
+ }
+ // write result back to the outside world
+ TestUtils.unpackProblems(result, holder);
+ }
- /**
- * Run fixture setup, test from the given test case and fixture teardown.
- *
- * @param osgiTestExtensions
- * @param testName
- */
- protected TestResult runTest(final OsgiJUnitTest osgiTestExtensions, String testName) {
- if (log.isDebugEnabled())
- log.debug("Running test [" + testName + "] on testCase " + osgiTestExtensions);
- final TestResult result = new TestResult();
- TestCase rawTest = osgiTestExtensions.getTestCase();
+ /**
+ * Run fixture setup, test from the given test case and fixture teardown.
+ *
+ * @param osgiTestExtensions
+ * @param testName
+ */
+ protected TestResult runTest(final OsgiJUnitTest osgiTestExtensions, String testName) {
+ if (log.isDebugEnabled()) {
+ log.debug("Running test [" + testName + "] on testCase " + osgiTestExtensions);
+ }
- rawTest.setName(testName);
+ final TestResult result = new TestResult();
+ TestCase rawTest = osgiTestExtensions.getTestCase();
+ rawTest.setName(testName);
- try {
- osgiTestExtensions.osgiSetUp();
+ try {
+ osgiTestExtensions.osgiSetUp();
- try {
- // use TestResult method to bypass the setUp/tearDown methods
- result.runProtected(rawTest, new Protectable() {
+ try {
+ // use TestResult method to bypass the setUp/tearDown methods
+ result.runProtected(rawTest, new Protectable() {
- public void protect() throws Throwable {
- osgiTestExtensions.osgiRunTest();
- }
+ public void protect() throws Throwable {
+ osgiTestExtensions.osgiRunTest();
+ }
- });
- }
- finally {
- osgiTestExtensions.osgiTearDown();
- }
-
- }
- // exceptions thrown by osgiSetUp/osgiTearDown
- catch (Exception ex) {
- log.error("test exception threw exception ", ex);
- result.addError((Test) rawTest, ex);
- }
- return result;
- }
+ });
+ } finally {
+ osgiTestExtensions.osgiTearDown();
+ }
+ }
+ // exceptions thrown by osgiSetUp/osgiTearDown
+ catch (Exception ex) {
+ log.error("test exception threw exception ", ex);
+ result.addError(rawTest, ex);
+ }
+ return result;
+ }
}
\ No newline at end of file
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/DependencyVisitor.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/DependencyVisitor.java
index 085c2d2..d8d6b81 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/DependencyVisitor.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/DependencyVisitor.java
@@ -70,8 +70,7 @@
*
* @author Costin Leau
*/
-public class DependencyVisitor implements AnnotationVisitor, SignatureVisitor, ClassVisitor, FieldVisitor,
- MethodVisitor {
+public class DependencyVisitor implements AnnotationVisitor, SignatureVisitor, ClassVisitor, FieldVisitor, MethodVisitor {
private Set packages = new LinkedHashSet();
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/IOUtils.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/IOUtils.java
index c26cc52..fea9322 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/IOUtils.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/IOUtils.java
@@ -7,7 +7,7 @@
* http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0
* is available at http://www.opensource.org/licenses/apache2.0.php.
* You may elect to redistribute this code under either of these licenses.
- *
+ *
* Contributors:
* VMware Inc.
*****************************************************************************/
@@ -21,68 +21,67 @@
/**
* Utility class for IO operations.
- *
+ *
* @author Costin Leau
- *
*/
public abstract class IOUtils {
- public static interface IOCallback {
- void doWithIO() throws IOException;
- }
+ public static interface IOCallback {
+ void doWithIO() throws IOException;
+ }
- public static void doWithIO(IOCallback callback) {
- try {
- callback.doWithIO();
- }
- catch (IOException ioException) {
+ public static void doWithIO(IOCallback callback) {
+ try {
+ callback.doWithIO();
+ } catch (IOException ioException) {
+ // ???
+ }
+ }
- }
- }
+ public static void closeStream(InputStream stream) {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException ex) {
+ // ignore
+ }
+ }
+ }
- public static void closeStream(InputStream stream) {
- if (stream != null)
- try {
- stream.close();
- }
- catch (IOException ex) {
- // ignore
- }
- }
+ public static void closeStream(OutputStream stream) {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException ex) {
+ // ignore
+ }
+ }
+ }
- public static void closeStream(OutputStream stream) {
- if (stream != null)
- try {
- stream.close();
- }
- catch (IOException ex) {
- // ignore
- }
- }
+ /**
+ * Delete the given file (can be a simple file or a folder).
+ *
+ * @param file the file to be deleted
+ * @return if the deletion succeeded or not
+ */
+ public static boolean delete(File file) {
- /**
- * Delete the given file (can be a simple file or a folder).
- *
- * @param file the file to be deleted
- * @return if the deletion succeded or not
- */
- public static boolean delete(File file) {
+ // bail out quickly
+ if (file == null) {
+ return false;
+ }
- // bail out quickly
- if (file == null)
- return false;
+ // recursively delete children file
+ boolean success = true;
- // recursively delete children file
- boolean success = true;
+ if (file.isDirectory()) {
+ String[] children = file.list();
+ for (String aChildren : children) {
+ success &= delete(new File(file, aChildren));
+ }
+ }
- if (file.isDirectory()) {
- String[] children = file.list();
- for (int i = 0; i < children.length; i++) {
- success &= delete(new File(file, children[i]));
- }
- }
-
- // The directory is now empty so delete it
- return (success &= file.delete());
- }
+ // The directory is now empty so delete it
+ return (success &= file.delete());
+ }
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/PropertiesUtil.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/PropertiesUtil.java
index 7b198e6..a991c95 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/PropertiesUtil.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/PropertiesUtil.java
@@ -224,8 +224,9 @@
public static Properties loadAndExpand(Resource resource) {
Properties props = new OrderedProperties();
- if (resource == null)
+ if (resource == null) {
return props;
+ }
try {
props.load(resource.getInputStream());
@@ -243,8 +244,9 @@
* @return
*/
public static Properties filterKeysStartingWith(Properties properties, String prefix) {
- if (!StringUtils.hasText(prefix))
+ if (!StringUtils.hasText(prefix)) {
return EMPTY_PROPERTIES;
+ }
Assert.notNull(properties);
@@ -272,8 +274,9 @@
* @return
*/
public static Properties filterValuesStartingWith(Properties properties, String prefix) {
- if (!StringUtils.hasText(prefix))
+ if (!StringUtils.hasText(prefix)) {
return EMPTY_PROPERTIES;
+ }
Assert.notNull(properties);
Properties excluded = (properties instanceof OrderedProperties ? new OrderedProperties() : new Properties());
@@ -354,11 +357,10 @@
copy = copy.substring(stopIndex + 1);
// append the replacement for the token
result.append(properties.getProperty(token));
- }
-
- else
+ } else {
throw new IllegalArgumentException("cannot interpret property " + prop + " due of token [" + copy
+ "]");
+ }
} else {
hasPlaceholder = false;
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/TestUtils.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/TestUtils.java
index fbb9290..43da6e0 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/TestUtils.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/TestUtils.java
@@ -43,18 +43,17 @@
*/
public static TestResult cloneTestResults(OsgiTestInfoHolder source, TestResult destination, Test test) {
// get errors
- for (Iterator iter = source.getTestErrors().iterator(); iter.hasNext();) {
- destination.addError(test, (Throwable) iter.next());
- }
+ for (Throwable throwable : source.getTestErrors()) {
+ destination.addError(test, throwable);
+ }
// get failures
// since failures are a special JUnit error, we have to clone the stack
- for (Iterator iter = source.getTestFailures().iterator(); iter.hasNext();) {
- Throwable originalFailure = (Throwable) iter.next();
- AssertionFailedError clonedFailure = new AssertionFailedError(originalFailure.getMessage());
- clonedFailure.setStackTrace(originalFailure.getStackTrace());
- destination.addFailure(test, clonedFailure);
- }
+ for (Throwable originalFailure : source.getTestFailures()) {
+ AssertionFailedError clonedFailure = new AssertionFailedError(originalFailure.getMessage());
+ clonedFailure.setStackTrace(originalFailure.getStackTrace());
+ destination.addFailure(test, clonedFailure);
+ }
return destination;
}
@@ -68,14 +67,14 @@
* @param holder
*/
public static void unpackProblems(TestResult result, OsgiTestInfoHolder holder) {
- Enumeration errors = result.errors();
+ Enumeration<TestFailure> errors = result.errors();
while (errors.hasMoreElements()) {
- TestFailure failure = (TestFailure) errors.nextElement();
+ TestFailure failure = errors.nextElement();
holder.addTestError(failure.thrownException());
}
- Enumeration failures = result.failures();
+ Enumeration<TestFailure> failures = result.failures();
while (failures.hasMoreElements()) {
- TestFailure failure = (TestFailure) failures.nextElement();
+ TestFailure failure = failures.nextElement();
holder.addTestFailure(failure.thrownException());
}
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/AbstractOsgiPlatform.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/AbstractOsgiPlatform.java
index 66e44c3..00cb4c8 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/AbstractOsgiPlatform.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/AbstractOsgiPlatform.java
@@ -81,10 +81,11 @@
}
File createTempDir(String suffix) {
- if (suffix == null)
+ if (suffix == null) {
suffix = DEFAULT_SUFFIX;
- File tempFileName;
+ }
+ File tempFileName;
try {
tempFileName = File.createTempFile(TMP_PREFIX, suffix);
} catch (IOException ex) {
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/EquinoxPlatform.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/EquinoxPlatform.java
index 668d956..c3dd650 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/EquinoxPlatform.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/EquinoxPlatform.java
@@ -68,17 +68,18 @@
// Equinox 3.1.x returns void - use of reflection is required
// use main since in 3.1.x it sets up some system properties
- EclipseStarter.main(new String[0]);
+// EclipseStarter.main(new String[0]);
- final Field field = EclipseStarter.class.getDeclaredField("context");
+// final Field field = EclipseStarter.class.getDeclaredField("context");
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- field.setAccessible(true);
- return null;
- }
- });
- context = (BundleContext) field.get(null);
+// AccessController.doPrivileged(new PrivilegedAction<Object>() {
+// public Object run() {
+// field.setAccessible(true);
+// return null;
+// }
+// });
+// context = (BundleContext) field.get(null);
+ context = EclipseStarter.startup(new String[0], null);
}
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/FelixPlatform.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/FelixPlatform.java
index e9c9dec..2100b45 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/FelixPlatform.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/platform/FelixPlatform.java
@@ -81,7 +81,7 @@
private static final Constructor<Felix> CTOR;
static {
try {
- CTOR = Felix.class.getConstructor(new Class<?>[] { Map.class, List.class });
+ CTOR = Felix.class.getConstructor(Map.class, List.class);
} catch (NoSuchMethodException ex) {
throw new IllegalStateException("Cannot find Felix constructor", ex);
}
@@ -90,7 +90,7 @@
@Override
Felix createFelix(Map<Object, Object> configMap, List<?> activators) throws Exception {
- return CTOR.newInstance(new Object[] { configMap, activators });
+ return CTOR.newInstance(configMap, activators);
}
}
diff --git a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/provisioning/internal/LocalFileSystemMavenRepository.java b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/provisioning/internal/LocalFileSystemMavenRepository.java
index 14d7bf8..f3ec001 100644
--- a/test-support/src/main/java/org/eclipse/gemini/blueprint/test/provisioning/internal/LocalFileSystemMavenRepository.java
+++ b/test-support/src/main/java/org/eclipse/gemini/blueprint/test/provisioning/internal/LocalFileSystemMavenRepository.java
@@ -78,8 +78,9 @@
*/
private void init() {
// already discovered a repository home, bailing out
- if (repositoryHome != null)
+ if (repositoryHome != null) {
return;
+ }
boolean trace = log.isDebugEnabled();
@@ -96,20 +97,23 @@
String localRepository = sysProperties[0];
String userHome = sysProperties[1];
- if (trace)
+ if (trace) {
log.trace("M2 system property [" + SYS_PROPERTY + "] has value=" + localRepository);
+ }
if (localRepository == null) {
// if it's not present then check settings.xml local repository property
Resource settingsFile = new FileSystemResource(new File(userHome, M2_SETTINGS));
localRepository = getMavenSettingsLocalRepository(settingsFile);
- if (trace)
+ if (trace) {
log.trace("Falling back to M2 settings.xml [" + settingsFile + "]; found value=" + localRepository);
+ }
if (localRepository == null) {
// fall back to the default location
localRepository = new File(userHome, DEFAULT_DIR).getAbsolutePath();
- if (trace)
+ if (trace) {
log.trace("No custom setting found; using default M2 local repository=" + localRepository);
+ }
}
}
@@ -126,8 +130,9 @@
*/
String getMavenSettingsLocalRepository(Resource m2Settings) {
// no file found, return null to continue the discovery process
- if (!m2Settings.exists())
+ if (!m2Settings.exists()) {
return null;
+ }
try {
DocumentLoader docLoader = new DefaultDocumentLoader();
@@ -135,10 +140,8 @@
XmlValidationModeDetector.VALIDATION_NONE, false);
return (DomUtils.getChildElementValueByTagName(document.getDocumentElement(), LOCAL_REPOSITORY_ELEM));
- }
- catch (Exception ex) {
- throw (RuntimeException) new RuntimeException(new ParserConfigurationException("error parsing resource="
- + m2Settings).initCause(ex));
+ } catch (Exception ex) {
+ throw new RuntimeException(new ParserConfigurationException("error parsing resource=" + m2Settings).initCause(ex));
}
}
@@ -165,10 +168,9 @@
* @param artifactId - the artifact id of the bundle
* @param version - the version of the bundle
* @param type - the extension type of the artifact
- * @return
+ * @return located artifact
*/
- public Resource locateArtifact(final String groupId, final String artifactId, final String version,
- final String type) {
+ public Resource locateArtifact(final String groupId, final String artifactId, final String version, final String type) {
init();
return (Resource) AccessController.doPrivileged(new PrivilegedAction() {
@@ -181,14 +183,7 @@
catch (IllegalStateException illStateEx) {
Resource localMavenBundle = localMavenBundle(groupId, artifactId, version, type);
if (log.isDebugEnabled()) {
- StringBuilder buf = new StringBuilder();
- buf.append("[");
- buf.append(groupId);
- buf.append("|");
- buf.append(artifactId);
- buf.append("|");
- buf.append(version);
- buf.append("]");
+ String buf = "[" + groupId + "|" + artifactId + "|" + version + "]";
log.debug(buf
+ " local maven build artifact detection failed, falling back to local maven bundle "
+ localMavenBundle.getDescription());
@@ -209,16 +204,8 @@
*/
protected Resource localMavenBundle(String groupId, String artifact, String version, String type) {
StringBuilder location = new StringBuilder(groupId.replace('.', SLASH_CHAR));
- location.append(SLASH_CHAR);
- location.append(artifact);
- location.append(SLASH_CHAR);
- location.append(version);
- location.append(SLASH_CHAR);
- location.append(artifact);
- location.append('-');
- location.append(version);
- location.append(".");
- location.append(type);
+ location.append(SLASH_CHAR).append(artifact).append(SLASH_CHAR).append(version).append(SLASH_CHAR)
+ .append(artifact).append('-').append(version).append(".").append(type);
return new FileSystemResource(new File(repositoryHome, location.toString()));
}
@@ -234,12 +221,10 @@
*/
protected Resource localMavenBuildArtifact(String groupId, String artifactId, String version, String type) {
try {
- File found = new MavenPackagedArtifactFinder(groupId, artifactId, version, type).findPackagedArtifact(new File(
- "."));
+ File found = new MavenPackagedArtifactFinder(groupId, artifactId, version, type).findPackagedArtifact(new File("."));
Resource res = new FileSystemResource(found);
if (log.isDebugEnabled()) {
- log.debug("[" + artifactId + "|" + version + "] resolved to " + res.getDescription()
- + " as a local maven artifact");
+ log.debug("[" + artifactId + "|" + version + "] resolved to " + res.getDescription() + " as a local maven artifact");
}
return res;
}
diff --git a/test-support/src/test/java/org/eclipse/gemini/blueprint/test/JUnitTestActivatorTest.java b/test-support/src/test/java/org/eclipse/gemini/blueprint/test/JUnitTestActivatorTest.java
index 75e9230..51a3302 100644
--- a/test-support/src/test/java/org/eclipse/gemini/blueprint/test/JUnitTestActivatorTest.java
+++ b/test-support/src/test/java/org/eclipse/gemini/blueprint/test/JUnitTestActivatorTest.java
@@ -16,6 +16,7 @@
import java.lang.reflect.Field;
import java.util.Dictionary;
+import java.util.Hashtable;
import junit.framework.TestCase;
@@ -85,9 +86,9 @@
ServiceReference ref = new MockServiceReference();
- expect(ctx.getServiceReference(TestRunnerService.class.getName())).andReturn(ref);
+ expect(ctx.getServiceReference(TestRunnerService.class)).andReturn(ref);
expect(ctx.getService(ref)).andReturn(runner);
- expect(ctx.registerService(anyString(), anyObject(), anyObject(Dictionary.class))).andReturn(null);
+ expect(ctx.registerService(eq(JUnitTestActivator.class), eq(activator), eq(new Hashtable<String, Object>()))).andReturn(null);
replay(ctx, runner);
activator.start(ctx);
@@ -120,8 +121,7 @@
try {
activator.executeTest();
fail("should have thrown exception");
- }
- catch (RuntimeException ex) {
+ } catch (RuntimeException ex) {
// expected
}