summaryrefslogtreecommitdiffstats
path: root/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime
diff options
context:
space:
mode:
Diffstat (limited to 'sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime')
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/LICENSE205
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/NOTICE6
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/pom.xml70
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/EquinoxRuntime.java117
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/FelixRuntime.java253
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/KnopflerfishRuntime.java168
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiBundleActivator.java252
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntime.java275
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntimeModuleActivator.java47
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator18
-rw-r--r--sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/test/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntimeTestCase.java78
11 files changed, 1489 insertions, 0 deletions
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/LICENSE b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/LICENSE
new file mode 100644
index 0000000000..6e529a25c4
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/LICENSE
@@ -0,0 +1,205 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/NOTICE b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/NOTICE
new file mode 100644
index 0000000000..9ddba06a32
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/NOTICE
@@ -0,0 +1,6 @@
+${pom.name}
+Copyright (c) 2005 - 2010 The Apache Software Foundation
+
+This product includes software developed by
+The Apache Software Foundation (http://www.apache.org/).
+
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/pom.xml b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/pom.xml
new file mode 100644
index 0000000000..b9c0e88c00
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/pom.xml
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+-->
+<project>
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.tuscany.sca</groupId>
+ <artifactId>tuscany-modules</artifactId>
+ <version>1.6.1-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+ <artifactId>tuscany-osgi-runtime</artifactId>
+ <name>Apache Tuscany SCA OSGi Runtime Helper Library</name>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.main</artifactId>
+ <version>1.0.4</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tuscany.sca</groupId>
+ <artifactId>tuscany-core-spi</artifactId>
+ <version>1.6.1-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tuscany.sca</groupId>
+ <artifactId>tuscany-extensibility-osgi</artifactId>
+ <version>1.6.1-SNAPSHOT</version>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <configuration>
+ <instructions>
+ <Bundle-Version>${tuscany.version}</Bundle-Version>
+ <Bundle-SymbolicName>org.apache.tuscany.sca.osgi.runtime
+ </Bundle-SymbolicName>
+ <Bundle-Description>${pom.name}</Bundle-Description>
+ <Export-Package>org.apache.tuscany.sca.osgi.runtime*
+ </Export-Package>
+ <Bundle-Activator>org.apache.tuscany.sca.osgi.runtime.OSGiBundleActivator
+ </Bundle-Activator>
+ <DynamicImport-Package>org.apache.felix.main,org.eclipse.core.runtime.adaptor
+ </DynamicImport-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/EquinoxRuntime.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/EquinoxRuntime.java
new file mode 100644
index 0000000000..43101b14c9
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/EquinoxRuntime.java
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.osgi.runtime;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+
+import org.osgi.framework.BundleContext;
+
+/**
+ * Implementation of an OSGi Runtime using Equinox.
+ *
+ * @version $Rev$ $Date$
+ */
+public class EquinoxRuntime extends OSGiRuntime {
+
+
+ private static BundleContext bundleContext;
+
+ private static EquinoxRuntime instance;
+
+ private static Class<?> eclipseStarterClass;
+
+ public static OSGiRuntime getInstance() throws Exception {
+ if (instance == null) {
+ eclipseStarterClass = EquinoxRuntime.class.getClassLoader().loadClass("org.eclipse.core.runtime.adaptor.EclipseStarter");
+ EquinoxRuntime runtime = new EquinoxRuntime();
+ instance = runtime;
+ }
+ return instance;
+ }
+
+ @Override
+ protected BundleContext startRuntime(boolean tuscanyRunningInOSGiContainer) throws Exception {
+
+ if (bundleContext != null)
+ return bundleContext;
+
+ Method startupMethod = eclipseStarterClass.getMethod("startup", String [].class, Runnable.class);
+
+ // Equinox version 3.2 upwards have a startup method which returns BundleContext
+ if (startupMethod.getReturnType() == BundleContext.class) {
+ bundleContext = (BundleContext) startupMethod.invoke(null, new String[] {"-clean", "-console"}, null );
+ }
+ else {
+
+ // Older versions of Equinox don't have a public method to obtain system bundlecontext
+ // Extract bundleContext from the private field 'context'. We are assuming that
+ // there is no access restriction
+ Method mainMethod = eclipseStarterClass.getMethod("main", String [].class);
+ mainMethod.invoke(null, (Object)new String[] {"-clean", "-console"});
+
+ Field contextField = eclipseStarterClass.getDeclaredField("context");
+ contextField.setAccessible(true);
+ bundleContext = (BundleContext) contextField.get(null);
+
+ }
+
+
+ return bundleContext;
+
+ }
+
+ @Override
+ public BundleContext getBundleContext() {
+ return bundleContext;
+ }
+
+ @Override
+ protected void setBundleContext(BundleContext bundleContext) {
+ super.setBundleContext(bundleContext);
+ EquinoxRuntime.bundleContext = bundleContext;
+ }
+
+ @Override
+ public void shutdown() throws Exception {
+
+ if (bundleContext == null)
+ return;
+ bundleContext = null;
+ instance = null;
+ if (eclipseStarterClass != null) {
+ Method shutdownMethod = eclipseStarterClass.getMethod("shutdown");
+ try {
+ shutdownMethod.invoke(eclipseStarterClass);
+ } catch (Exception e) {
+ // Ignore errors.
+ }
+ }
+ super.shutdown();
+ }
+
+
+ @Override
+ public boolean supportsBundleFragments() {
+ return false;
+ }
+
+
+
+}
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/FelixRuntime.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/FelixRuntime.java
new file mode 100644
index 0000000000..f8b56c88d6
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/FelixRuntime.java
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.osgi.runtime;
+
+import java.io.File;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+/**
+ * Implementation of an OSGi Runtime using Felix.
+ *
+ * @version $Rev$ $Date$
+ */
+public class FelixRuntime extends OSGiRuntime implements BundleActivator {
+
+ private static BundleContext bundleContext;
+
+ private static FelixRuntime instance;
+
+ private static Class<?> felixMainClass;
+ private static Class<?> felixClass;
+ private static Object felix;
+
+ public static OSGiRuntime getInstance() throws Exception {
+ if (instance == null) {
+ felixMainClass = FelixRuntime.class.getClassLoader().loadClass("org.apache.felix.main.Main");
+ FelixRuntime runtime = new FelixRuntime();
+ instance = runtime;
+ }
+ return instance;
+ }
+
+
+ private static void deleteDirectory(File dir) {
+
+ File[] files = dir.listFiles();
+ for (int i = 0; i < files.length; i++) {
+ if (files[i].isDirectory())
+ deleteDirectory(files[i]);
+ else
+ files[i].delete();
+ }
+ dir.delete();
+
+ }
+
+ @Override
+ protected BundleContext startRuntime(boolean tuscanyRunningInOSGiContainer) throws Exception {
+
+ if (bundleContext != null)
+ return bundleContext;
+
+
+ ClassLoader cl = FelixRuntime.class.getClassLoader();
+
+ felixClass = cl.loadClass("org.apache.felix.framework.Felix");
+ Method propsMethod = felixMainClass.getMethod("loadConfigProperties");
+ Properties props = (Properties)propsMethod.invoke(null);
+
+ String profileDirName = ".felix";
+ File targetDir = new File("target");
+ if (targetDir.exists() && targetDir.isDirectory())
+ profileDirName = "target/" + profileDirName;
+ File profileDir = new File(profileDirName);
+ if (profileDir.isDirectory())
+ deleteDirectory(profileDir);
+ else
+ profileDir.delete();
+ profileDir.mkdir();
+ profileDir.deleteOnExit();
+
+ props.put("felix.cache.profiledir", profileDir.getAbsolutePath());
+ props.put("felix.embedded.execution", "true");
+
+ String systemPackages =
+ "org.osgi.framework; version=1.3.0," +
+ "org.osgi.service.packageadmin; version=1.2.0, " +
+ "org.osgi.service.startlevel; version=1.0.0, " +
+ "org.osgi.service.url; version=1.0.0, " +
+ "org.osgi.util.tracker; version=1.3.2, " +
+ "javax.xml, " +
+ "javax.xml.datatype, " +
+ "javax.xml.namespace, " +
+ "javax.xml.parsers, " +
+ "javax.xml.transform, " +
+ "javax.xml.transform.dom, " +
+ "javax.xml.transform.sax, " +
+ "javax.xml.transform.stream, " +
+ "javax.xml.validation, " +
+ "javax.xml.xpath, " +
+ "org.apache.xerces.jaxp.datatype, " +
+ "org.w3c.dom, " +
+ "org.xml.sax, " +
+ "org.xml.sax.ext, " +
+ "org.xml.sax.helpers, " +
+ "javax.security.auth, " +
+ "javax.naming, " +
+ "javax.naming.spi, " +
+ "javax.naming.directory, " +
+ "javax.management, " +
+ "sun.misc";
+
+
+ if (!tuscanyRunningInOSGiContainer) {
+ systemPackages = systemPackages + ", org.osoa.sca.annotations, org.osoa.sca";
+ systemPackages = systemPackages + ", commonj.sdo, commonj.sdo.helper, org.apache.tuscany.sdo.helper, org.apache.tuscany.sdo.impl, org.apache.tuscany.sdo.model, org.apache.tuscany.sdo.model.impl";
+ systemPackages = systemPackages + ", org.eclipse.emf.ecore, org.eclipse.emf.ecore.util, org.eclipse.emf.ecore.impl";
+ }
+ props.put("org.osgi.framework.system.packages", systemPackages);
+
+ try {
+ Constructor felixConstructor = felixClass.getConstructor(Map.class, List.class);
+ List<BundleActivator> activators = new ArrayList<BundleActivator>();
+
+ Class<?> autoActivatorClass = cl.loadClass("org.apache.felix.main.AutoActivator");
+ Constructor autoActivatorConstructor = autoActivatorClass.getConstructor(Map.class);
+ BundleActivator autoActivator = (BundleActivator)autoActivatorConstructor.newInstance(props);
+ activators.add(autoActivator);
+
+ felix = felixConstructor.newInstance(props, activators);
+ ((Bundle)felix).start();
+ bundleContext = ((Bundle)felix).getBundleContext();
+
+
+ } catch (Exception e) {
+
+ // This is the older Felix API which has been retained temporarily to avoid build break
+ // TODO: Remove these once Felix 1.0.0 is released.
+
+ Class<?> propertyResolverClass = cl.loadClass("org.apache.felix.framework.util.MutablePropertyResolver");
+ Class<?> propertyResolverImplClass = cl.loadClass("org.apache.felix.framework.util.MutablePropertyResolverImpl");
+
+ Constructor implConstructor = propertyResolverImplClass.getConstructor(Map.class);
+ Object mutableProps = implConstructor.newInstance(props);
+
+
+ try {
+ Constructor felixConstructor = felixClass.getConstructor(propertyResolverClass, List.class);
+ List<BundleActivator> activators = new ArrayList<BundleActivator>();
+ felix = felixConstructor.newInstance(mutableProps, activators);
+ ((Bundle)felix).start();
+ bundleContext = ((Bundle)felix).getBundleContext();
+ } catch (Exception e1) {
+
+
+ felix = felixClass.newInstance();
+ Method startMethod = felixClass.getMethod("start", propertyResolverClass, List.class);
+ List<BundleActivator> activators = new ArrayList<BundleActivator>();
+ BundleActivator activator = new FelixRuntime();
+ activators.add(activator);
+ startMethod.invoke(felix, mutableProps, activators);
+
+ synchronized (activator) {
+ int retries = 0;
+ while (bundleContext == null && retries++ < 10) {
+ activator.wait(1000);
+ }
+ }
+ }
+ }
+
+ return bundleContext;
+
+ }
+
+ public void start(BundleContext context) throws Exception {
+
+ bundleContext = context;
+ synchronized (this) {
+ this.notify();
+ }
+ }
+
+ public void stop(BundleContext context) throws Exception {
+ bundleContext = null;
+ }
+
+
+
+ @Override
+ public BundleContext getBundleContext() {
+ return bundleContext;
+ }
+
+ @Override
+ protected void setBundleContext(BundleContext bundleContext) {
+ super.setBundleContext(bundleContext);
+ FelixRuntime.bundleContext = bundleContext;
+ }
+
+
+ @Override
+ public void shutdown() throws Exception {
+
+ if (bundleContext == null)
+ return;
+ bundleContext = null;
+ instance = null;
+
+ // We could potentially use Felix.stopAndWait, but use timed wait for now because
+ // stopAndWait hangs with Felix 1.0.0
+ if (felix instanceof Bundle) {
+ Bundle felixBundle = (Bundle)felix;
+ felixBundle.stop();
+ int retries = 50;
+ synchronized (felix) {
+ while (retries-- > 0 && felixBundle.getState() != Bundle.UNINSTALLED) {
+ felix.wait(100);
+ }
+ }
+ }
+ else if (felix != null) {
+ Method shutdownMethod = felixClass.getMethod("shutdown");
+ try {
+ shutdownMethod.invoke(felix);
+ } catch (Exception e) {
+ // Ignore errors
+ }
+ felix = null;
+ }
+ super.shutdown();
+ }
+
+ @Override
+ public boolean supportsBundleFragments() {
+ return false;
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/KnopflerfishRuntime.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/KnopflerfishRuntime.java
new file mode 100644
index 0000000000..19041daf50
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/KnopflerfishRuntime.java
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.osgi.runtime;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.util.Hashtable;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleException;
+
+/**
+ * Implementation of an OSGi Runtime using Knopflerfish.
+ *
+ * @version $Rev$ $Date$
+ */
+public class KnopflerfishRuntime extends OSGiRuntime {
+
+ private static BundleContext bundleContext;
+
+ private static KnopflerfishRuntime instance;
+
+
+ private static Class<?> frameworkClass;
+
+ private static Object framework;
+
+ public static OSGiRuntime getInstance() throws Exception {
+ if (instance == null) {
+ frameworkClass = KnopflerfishRuntime.class.getClassLoader().loadClass("org.knopflerfish.framework.Framework");
+ KnopflerfishRuntime runtime = new KnopflerfishRuntime();
+ instance = runtime;
+ }
+ return instance;
+ }
+
+
+
+ // FIXME: Knopflerfish does not expose the methods used for configuration as public methods
+ // It may be worth using the private methods in org.knopflerfish.framework.Main for
+ // configuring using reflection if security policies allow it.
+ // For now, a simple configuration routine reads sca.xargs from the directory in
+ // the classpath which contains framework.jar. The entries in init.xargs starting with
+ // -install are assumed to be single-line entries with full bundle location.
+ //
+ @Override
+ protected BundleContext startRuntime(boolean tuscanyRunningInOSGiContainer) throws Exception {
+
+ if (bundleContext != null)
+ return bundleContext;
+
+
+
+ System.setProperty("org.knopflerfish.framework.bundlestorage", "memory");
+
+ Constructor frameworkConstructor = frameworkClass.getConstructor(Object.class);
+ framework = frameworkConstructor.newInstance(new KnopflerfishRuntime());
+ Method launchMethod = frameworkClass.getMethod("launch", long.class);
+ launchMethod.invoke(framework, 0);
+ Method getContextMethod = frameworkClass.getMethod("getSystemBundleContext");
+ bundleContext = (BundleContext)getContextMethod.invoke(framework);
+
+ System.setProperty("com.gatespace.bundle.cm.store", "knopflerfish.store");
+ File xargsFile = null;
+ String classpath = System.getProperty("java.class.path");
+ String[] classpathEntries = classpath.split(System.getProperty("path.separator"));
+ for (int i = 0; i < classpathEntries.length; i++) {
+ if (classpathEntries[i].endsWith("framework.jar")) {
+ String path = classpathEntries[i].substring(0, classpathEntries[i].length() - "framework.jar".length());
+ path = path + "sca.xargs";
+ xargsFile = new File(path);
+ if (!xargsFile.exists())
+ xargsFile = null;
+ break;
+ }
+ }
+ if (xargsFile != null) {
+ BufferedReader reader = new BufferedReader(new FileReader(xargsFile));
+ String line;
+ Hashtable<String, Bundle> bundles = new Hashtable<String, Bundle>();
+ while ((line = reader.readLine()) != null) {
+ line = line.trim();
+ if (line.startsWith("-install")) {
+ try {
+
+ String bundleLocation = line.substring("-install".length()).trim();
+ Bundle bundle = bundleContext.installBundle(bundleLocation);
+ bundles.put(bundleLocation, bundle);
+
+ } catch (BundleException e) {
+ e.printStackTrace();
+ }
+
+ }
+ if (line.startsWith("-start")) {
+
+ try {
+ String bundleLocation = line.substring("-start".length()).trim();
+ Bundle bundle = bundles.get(bundleLocation);
+ bundle.start();
+ } catch (BundleException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+
+
+ return bundleContext;
+
+ }
+
+ @Override
+ public BundleContext getBundleContext() {
+ return bundleContext;
+ }
+
+ @Override
+ protected void setBundleContext(BundleContext bundleContext) {
+ super.setBundleContext(bundleContext);
+ KnopflerfishRuntime.bundleContext = bundleContext;
+ }
+
+ @Override
+ public void shutdown() throws Exception {
+
+ if (bundleContext == null)
+ return;
+ bundleContext = null;
+ instance = null;
+ if (framework != null) {
+ Method shutdownMethod = frameworkClass.getMethod("shutdown");
+ try {
+ shutdownMethod.invoke(framework);
+ } catch (Exception e) {
+ // Ignore errors
+ }
+ framework = null;
+ }
+ super.shutdown();
+
+ }
+
+ @Override
+ public boolean supportsBundleFragments() {
+ return true;
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiBundleActivator.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiBundleActivator.java
new file mode 100644
index 0000000000..b87f70deef
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiBundleActivator.java
@@ -0,0 +1,252 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.osgi.runtime;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
+
+import org.apache.tuscany.sca.extensibility.ServiceDiscovery;
+import org.apache.tuscany.sca.extensibility.osgi.OSGiServiceDiscoverer;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.BundleListener;
+
+/**
+ * OSGi bundle activator, which is run when Tuscany is run inside an OSGi runtime.
+ *
+ * @version $Rev$ $Date$
+ */
+public class OSGiBundleActivator implements BundleActivator, BundleListener {
+
+ private static final String TUSCANY_SCA_BUNDLE_PREFIX = "org.apache.tuscany.sca";
+ private static final String TUSCANY_3RD_PARTY_BUNDLE_PREFIX = "org.apache.tuscany.sca.3rdparty";
+ private OSGiRuntime runtime;
+ /*
+ private ConcurrentHashMap<Bundle, ClassLoader> serviceDiscoveryClassLoaders =
+ new ConcurrentHashMap<Bundle, ClassLoader>();
+ */
+ private BundleClassLoader threadContextClassLoader;
+ private ClassLoader origTCCL;
+ private Bundle thisBundle;
+
+ public void start(BundleContext bundleContext) throws Exception {
+
+ initializeTuscanyClassLoaders(bundleContext);
+
+ runtime = OSGiRuntime.findRuntime();
+ runtime.setBundleContext(bundleContext);
+ runtime.setContextClassLoader(threadContextClassLoader);
+ runtime.initialize();
+
+ }
+
+ public void stop(BundleContext bundleContext) throws Exception {
+
+ // runtime.shutdown();
+
+ if (Thread.currentThread().getContextClassLoader() == threadContextClassLoader)
+ Thread.currentThread().setContextClassLoader(origTCCL);
+ }
+
+ /**
+ * Create a bundle ClassLoader which has visibility of all Tuscany related
+ * bundles. Use this ClassLoader as TCCL, and the Tuscany service discovery
+ * ClassLoader.
+ *
+ * @param bundleContext
+ */
+ private void initializeTuscanyClassLoaders(BundleContext bundleContext) {
+
+ OSGiServiceDiscoverer discoverer = new OSGiServiceDiscoverer(bundleContext);
+ ServiceDiscovery.getInstance().setServiceDiscoverer(discoverer);
+ thisBundle = bundleContext.getBundle();
+
+ origTCCL = Thread.currentThread().getContextClassLoader();
+
+ threadContextClassLoader = new BundleClassLoader(thisBundle, origTCCL);
+
+ Thread.currentThread().setContextClassLoader(threadContextClassLoader);
+
+ ClassLoader cl = new BundleClassLoader(thisBundle, null);
+ // ServiceDiscovery.getInstance().registerClassLoader(cl);
+ // serviceDiscoveryClassLoaders.put(thisBundle, cl);
+
+ Bundle[] bundles = bundleContext.getBundles();
+ for (Bundle bundle : bundles) {
+ updateBundleClassLoader(bundle);
+ }
+ bundleContext.addBundleListener(this);
+
+ }
+
+ /**
+ * Add an installed bundle to the list of bundles in the service discovery classpath
+ * if the installed bundle is a Tuscany bundle using the same Core-SPI bundle.
+ * Since the bundle containing this activator is in Tuscany Runtime, this bundle
+ * will provide access to Runtime and its dependencies (SPI, SCA-API). Third party
+ * bundles don't need to be in the service discovery classpath, since they will be automatically
+ * imported by bundles which require them. That leaves Tuscany extension bundles,
+ * which are added to the service discovery classpath here.
+ *
+ * 3rd party bundle should be explicitly added to TCCL since classes from these
+ * bundles use TCCL to load other classes from the bundle.
+ *
+ * Load one class from the bundle to check if the new bundle matches this runtime bundle.
+ *
+ * @param bundle
+ */
+ private void updateBundleClassLoader(Bundle bundle) {
+
+ if (bundle.getSymbolicName().startsWith(TUSCANY_SCA_BUNDLE_PREFIX)) {
+
+ // This may be the third party bundle.
+ if (bundle.getSymbolicName().startsWith(TUSCANY_3RD_PARTY_BUNDLE_PREFIX)) {
+
+ threadContextClassLoader.addBundle(bundle);
+ } else {
+
+ String thisBundleVersion = (String)thisBundle.getHeaders().get("Bundle-Version");
+ String bundleVersion = (String)bundle.getHeaders().get("Bundle-Version");
+
+ if (thisBundleVersion == null || bundleVersion == null || thisBundleVersion.equals(bundleVersion)) {
+
+ if (!threadContextClassLoader.bundles.contains(bundle)) {
+ ClassLoader cl = new BundleClassLoader(bundle, null);
+ // ServiceDiscovery.getInstance().registerClassLoader(cl);
+ // serviceDiscoveryClassLoaders.put(bundle, cl);
+ threadContextClassLoader.addBundle(bundle);
+ }
+ }
+ }
+ } else {
+ threadContextClassLoader.addBundle(bundle);
+ }
+ }
+
+ /**
+ * Handle bundle install/uninstall events
+ */
+ public void bundleChanged(BundleEvent event) {
+
+ Bundle bundle = event.getBundle();
+ if (event.getType() == BundleEvent.UNINSTALLED) {
+// ClassLoader cl = serviceDiscoveryClassLoaders.get(bundle);
+// if (cl != null) {
+// ServiceDiscovery.getInstance().unregisterClassLoader(cl);
+// }
+ threadContextClassLoader.removeBundle(bundle);
+ } else if (event.getType() == BundleEvent.INSTALLED) {
+ updateBundleClassLoader(bundle);
+ }
+ }
+
+ /**
+ * Bundle ClassLoader that searches a bundle classpath consisting of
+ * a list of bundles. The parent ClassLoader is searched only if a class
+ * cannot be loaded from the bundle classpath. Tuscany bundles are
+ * dynamically added and removed from the bundle classpath when the bundles
+ * are installed and uninstalled.
+ *
+ * No ordering of bundles is maintained at the moment.
+ *
+ */
+ private static class BundleClassLoader extends ClassLoader {
+
+ private HashSet<Bundle> bundles;
+
+ BundleClassLoader(Bundle bundle, ClassLoader parent) {
+ super(parent);
+ this.bundles = new HashSet<Bundle>();
+ bundles.add(bundle);
+ }
+
+ private synchronized void addBundle(Bundle bundle) {
+ bundles.add(bundle);
+ }
+
+ private synchronized void removeBundle(Bundle bundle) {
+ if (bundles.contains(bundle))
+ bundles.remove(bundle);
+ }
+
+ @Override
+ protected Class<?> findClass(String className) throws ClassNotFoundException {
+ Class<?> clazz = null;
+ synchronized (this) {
+ for (Bundle bundle : bundles) {
+ try {
+ clazz = bundle.loadClass(className);
+ break;
+ } catch (ClassNotFoundException e) {
+ } catch (NoClassDefFoundError e) {
+ }
+
+ }
+ }
+ if (clazz != null) {
+ return clazz;
+ }
+ return super.findClass(className);
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public Enumeration<URL> getResources(String resName) throws IOException {
+ HashSet<URL> urlSet = new HashSet<URL>();
+ Enumeration<URL> urls = null;
+ synchronized (this) {
+ for (Bundle bundle : bundles) {
+ urls = bundle.getResources(resName);
+ if (urls != null) {
+ while (urls.hasMoreElements()) {
+ urlSet.add(urls.nextElement());
+ }
+ }
+ }
+ }
+ if (urlSet.size() > 0)
+ return Collections.enumeration(urlSet);
+ return super.getResources(resName);
+ }
+
+ @Override
+ public URL getResource(String resName) {
+ URL url = null;
+ synchronized (this) {
+ for (Bundle bundle : bundles) {
+ url = bundle.getResource(resName);
+ if (url != null)
+ return url;
+ }
+ }
+ return super.getResource(resName);
+ }
+
+ @Override
+ public String toString() {
+ return "Tuscany BundleClassLoader " + bundles.iterator().next();
+ }
+
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntime.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntime.java
new file mode 100644
index 0000000000..79b1c0a5f4
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntime.java
@@ -0,0 +1,275 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.osgi.runtime;
+
+import java.io.InputStream;
+import java.lang.reflect.Method;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleException;
+import org.osgi.service.packageadmin.PackageAdmin;
+
+/**
+ * Base OSGiRuntime implementation.
+ *
+ * @version $Rev$ $Date$
+ */
+public abstract class OSGiRuntime {
+ private static final Logger logger = Logger.getLogger(OSGiRuntime.class.getName());
+
+ public abstract BundleContext getBundleContext();
+
+ public abstract boolean supportsBundleFragments();
+
+ protected abstract BundleContext startRuntime(boolean tuscanyRunningInOSGiContainer) throws Exception;
+
+ private static OSGiRuntime instance;
+
+ private BundleContext bundleContext;
+
+ private PackageAdmin packageAdmin;
+
+ private boolean tuscanyRunningInOSGiContainer;
+
+ private ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+
+ /**
+ * System property org.apache.tuscany.implementation.osgi.runtime.OSGiRuntime can be set to the
+ * name of the OSGiRuntime class (eg. EquinoxRuntime). If set, start this runtime and return the
+ * system bundlecontext. If not set, start Equinox/Felix/Knopflerfish (in that order) from the
+ * classpath.
+ *
+ * @throws BundleException
+ */
+ public static synchronized OSGiRuntime findRuntime() throws Exception {
+
+ if (instance != null) {
+
+ return instance;
+ }
+ String runtimeClassName = System.getProperty(OSGiRuntime.class.getName());
+
+
+ if (runtimeClassName != null) {
+ try {
+ Class<?> runtimeClass = OSGiRuntime.class.getClassLoader().loadClass(runtimeClassName);
+ Method method = runtimeClass.getMethod("getInstance");
+ instance = (OSGiRuntime) method.invoke(null);
+ return instance;
+
+ } catch (Exception e) {
+ throw new BundleException("Could not start OSGi runtime " + runtimeClassName, e);
+ }
+ }
+
+ try {
+
+ instance = EquinoxRuntime.getInstance();
+ return instance;
+
+ } catch (ClassNotFoundException e) {
+ // Ignore
+ } catch (Throwable e) {
+ logger.log(Level.SEVERE, e.getMessage(), e);
+ }
+
+ try {
+
+ instance = FelixRuntime.getInstance();
+ return instance;
+
+ } catch (ClassNotFoundException e) {
+ // Ignore
+ } catch (Throwable e) {
+ logger.log(Level.SEVERE, e.getMessage(), e);
+ }
+
+ try {
+
+ instance = KnopflerfishRuntime.getInstance();
+ return instance;
+
+ } catch (ClassNotFoundException e) {
+ // Ignore
+ } catch (Throwable e) {
+ logger.log(Level.SEVERE, e.getMessage(), e);
+ }
+
+ throw new BundleException("Could not start OSGi runtime from the classpath");
+ }
+
+
+ public static synchronized OSGiRuntime getRuntime() throws Exception {
+ return getRuntime(false);
+ }
+
+ public static synchronized OSGiRuntime getRuntime(boolean tuscanyRunningInOSGiContainer) throws Exception {
+
+ instance = findRuntime();
+
+ if (instance != null) {
+
+ if (instance.bundleContext == null) {
+ instance.tuscanyRunningInOSGiContainer = tuscanyRunningInOSGiContainer;
+ instance.startRuntime(tuscanyRunningInOSGiContainer);
+ instance.initialize();
+ }
+ return instance;
+ }
+ return instance;
+ }
+
+
+ public void shutdown() throws Exception {
+
+ bundleContext = null;
+ packageAdmin = null;
+ }
+
+ protected void setBundleContext(BundleContext bundleContext) {
+ instance.tuscanyRunningInOSGiContainer = true;
+ this.bundleContext = bundleContext;
+ }
+
+
+
+ public ClassLoader getContextClassLoader() {
+ return contextClassLoader;
+ }
+
+ protected void setContextClassLoader(ClassLoader contextClassLoader) {
+ this.contextClassLoader = contextClassLoader;
+ }
+
+ protected void initialize() {
+
+ bundleContext = getBundleContext();
+
+ if (bundleContext != null) {
+
+ org.osgi.framework.ServiceReference packageAdminReference =
+ bundleContext.getServiceReference("org.osgi.service.packageadmin.PackageAdmin");
+ if (packageAdminReference != null) {
+
+ packageAdmin = (PackageAdmin)bundleContext.getService(packageAdminReference);
+ }
+ }
+
+ }
+
+ public Bundle findBundle(String bundleSymbolicName, String bundleVersion) {
+
+ if (bundleContext != null) {
+ Bundle[] installedBundles = bundleContext.getBundles();
+ for (Bundle bundle : installedBundles) {
+ if (bundleSymbolicName.equals(bundle.getSymbolicName()) && (bundleVersion == null || bundleVersion
+ .equals(bundle.getHeaders().get("Bundle-Version"))))
+ return bundle;
+ }
+
+ }
+ return null;
+ }
+
+ public static synchronized Bundle findInstalledBundle(String bundleLocation) {
+ if (instance != null) {
+ if (bundleLocation.startsWith("bundle:")||bundleLocation.startsWith("bundleresource:")) {
+ try {
+ return findInstalledBundle(new URL(bundleLocation));
+ } catch (MalformedURLException e) {
+ // ignore
+ }
+ } else {
+ return instance.findBundle(bundleLocation);
+ }
+ }
+ return null;
+ }
+
+ public static synchronized Bundle findInstalledBundle(URL bundleURL) {
+ if (instance != null) {
+ if (instance.bundleContext != null) {
+ Bundle[] installedBundles = instance.bundleContext.getBundles();
+ for (Bundle bundle : installedBundles) {
+ try {
+ if (bundle.getEntry("/").getHost().equals(bundleURL.getHost()))
+ return bundle;
+ } catch (Exception e) {
+ // Ignore exception
+ }
+ }
+ }
+ return null;
+ }
+ return null;
+ }
+
+ public Bundle findBundle(String bundleLocation) {
+
+ if (bundleContext != null) {
+ Bundle[] installedBundles = bundleContext.getBundles();
+ for (Bundle bundle : installedBundles) {
+ if (bundle.getLocation().equals(bundleLocation))
+ return bundle;
+ }
+
+ }
+ return null;
+ }
+
+ public Bundle installBundle(String bundleLocation, InputStream inputStream) {
+
+ try {
+ if (bundleContext != null) {
+ Bundle bundle = findBundle(bundleLocation);
+ if (bundle != null)
+ return bundle;
+ if (inputStream == null)
+ bundle = bundleContext.installBundle(bundleLocation);
+ else
+ bundle = bundleContext.installBundle(bundleLocation, inputStream);
+
+ if (bundle != null && packageAdmin != null)
+ packageAdmin.refreshPackages(null);
+
+ return bundle;
+ }
+ } catch (BundleException e) {
+ }
+ return null;
+ }
+
+ /**
+ * Stops the OSGi instance.
+ *
+ * @throws Exception Failed to shutdown the OSGi instance.
+ */
+ public static synchronized void stop() throws Exception {
+ if (instance != null && !instance.tuscanyRunningInOSGiContainer) {
+ instance.shutdown();
+ instance = null;
+ }
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntimeModuleActivator.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntimeModuleActivator.java
new file mode 100644
index 0000000000..1dbe75f431
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntimeModuleActivator.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.osgi.runtime;
+
+import org.apache.tuscany.sca.core.ExtensionPointRegistry;
+import org.apache.tuscany.sca.core.ModuleActivator;
+
+/**
+ * @version $Rev$ $Date$
+ */
+public class OSGiRuntimeModuleActivator implements ModuleActivator {
+
+ /**
+ * @see org.apache.tuscany.sca.core.ModuleActivator#start(org.apache.tuscany.sca.core.ExtensionPointRegistry)
+ */
+ public void start(ExtensionPointRegistry registry) {
+ }
+
+ /**
+ * @see org.apache.tuscany.sca.core.ModuleActivator#stop(org.apache.tuscany.sca.core.ExtensionPointRegistry)
+ */
+ public void stop(ExtensionPointRegistry registry) {
+ try {
+ OSGiRuntime.stop();
+ } catch (Throwable e) {
+ // Ignore the exception
+ }
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator
new file mode 100644
index 0000000000..bd3fd72280
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# Implementation class for the ModuleActivator
+org.apache.tuscany.sca.osgi.runtime.OSGiRuntimeModuleActivator
diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/test/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntimeTestCase.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/test/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntimeTestCase.java
new file mode 100644
index 0000000000..7ce3f6c18f
--- /dev/null
+++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/osgi-runtime/src/test/java/org/apache/tuscany/sca/osgi/runtime/OSGiRuntimeTestCase.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.osgi.runtime;
+
+import junit.framework.TestCase;
+
+import org.osgi.framework.BundleContext;
+
+/**
+ * Test OSGi runtime.
+ *
+ * @version $Rev$ $Date$
+ */
+public class OSGiRuntimeTestCase extends TestCase {
+ private OSGiRuntime runtime;
+
+ /**
+ * @see junit.framework.TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ try {
+ this.runtime = OSGiRuntime.getRuntime();
+ } catch ( Throwable e ) {
+ System.out.println( "DOB: OSGiRuntimeTestCase.setUp error=" + e );
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @see junit.framework.TestCase#tearDown()
+ */
+ @Override
+ protected void tearDown() throws Exception {
+ OSGiRuntime.stop();
+ }
+
+ public void testRuntime() throws Exception {
+
+ BundleContext bc1 = runtime.getBundleContext();
+
+ assertNotNull(bc1);
+
+ BundleContext bc2 = runtime.getBundleContext();
+
+ assertNotNull(bc2);
+
+ assertTrue(bc1 == bc2);
+
+ OSGiRuntime.stop();
+ runtime = OSGiRuntime.getRuntime();
+
+ BundleContext bc3 = runtime.getBundleContext();
+
+ assertNotNull(bc3);
+
+ assertTrue(bc1 != bc3);
+
+ }
+
+}