diff options
Diffstat (limited to 'java/sca/contrib/modules/node-launcher-equinox')
22 files changed, 2689 insertions, 0 deletions
diff --git a/java/sca/contrib/modules/node-launcher-equinox/LICENSE b/java/sca/contrib/modules/node-launcher-equinox/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/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/java/sca/contrib/modules/node-launcher-equinox/NOTICE b/java/sca/contrib/modules/node-launcher-equinox/NOTICE new file mode 100644 index 0000000000..1325efd8bf --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/NOTICE @@ -0,0 +1,6 @@ +${pom.name}
+Copyright (c) 2005 - 2008 The Apache Software Foundation
+
+This product includes software developed by
+The Apache Software Foundation (http://www.apache.org/).
+
diff --git a/java/sca/contrib/modules/node-launcher-equinox/pom.xml b/java/sca/contrib/modules/node-launcher-equinox/pom.xml new file mode 100644 index 0000000000..04b165b157 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/pom.xml @@ -0,0 +1,125 @@ +<?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>2.0-SNAPSHOT</version> + <relativePath>../pom.xml</relativePath> + </parent> + + <artifactId>tuscany-node-launcher-equinox</artifactId> + <name>Apache Tuscany SCA Node Equinox OSGi Launcher</name> + + <dependencies> + <dependency> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + <version>2.5</version> <!-- To be compatible with Jetty 6 --> + <scope>provided</scope> + </dependency> + + <dependency> + <groupId>org.eclipse</groupId> + <artifactId>osgi</artifactId> + <version>3.3.0-v20070530</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.eclipse.core</groupId> + <artifactId>runtime</artifactId> + <version>3.3.100-v20070530</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-implementation-node-runtime</artifactId> + <version>2.0-SNAPSHOT</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-extensibility-equinox</artifactId> + <version>2.0-SNAPSHOT</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-domain-manager</artifactId> + <version>2.0-SNAPSHOT</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-binding-http-runtime</artifactId> + <version>2.0-SNAPSHOT</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-implementation-java-runtime</artifactId> + <version>2.0-SNAPSHOT</version> + <scope>test</scope> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-jar-plugin</artifactId> + <configuration> + <archive> + <manifest> + <mainClass>org.apache.tuscany.sca.node.equinox.launcher.NodeMain</mainClass> + </manifest> + </archive> + </configuration> + </plugin> + + <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.node.launcher.equinox</Bundle-SymbolicName> + <Bundle-Description>${pom.name}</Bundle-Description> + <!-- + <Bundle-Activator>org.apache.tuscany.sca.node.equinox.launcher.LauncherBundleActivator</Bundle-Activator> + --> + <Export-Package>org.apache.tuscany.sca.node.equinox.launcher*</Export-Package> + <Eclipse-AutoStart>true</Eclipse-AutoStart> + </instructions> + </configuration> + </plugin> + </plugins> + </build> + +</project> diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/Contribution.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/Contribution.java new file mode 100644 index 0000000000..892412b395 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/Contribution.java @@ -0,0 +1,48 @@ +/* + * 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.node.equinox.launcher; + +/** + * Represents an SCA contribution uri + location. + * + * @version $Rev$ $Date$ + */ +public final class Contribution { + private String uri; + private String location; + + /** + * Constructs a new SCA contribution. + * + * @param uri + * @param location + */ + public Contribution(String uri, String location) { + this.uri = uri; + this.location = location; + } + + public String getURI() { + return uri; + } + + public String getLocation() { + return location; + } +}
\ No newline at end of file diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/DomainManagerLauncher.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/DomainManagerLauncher.java new file mode 100644 index 0000000000..61187eecac --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/DomainManagerLauncher.java @@ -0,0 +1,172 @@ +/* + * 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.node.equinox.launcher; + +import static org.apache.tuscany.sca.node.equinox.launcher.NodeLauncherUtil.domainManager; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Simple launcher for the SCA domain manager. + * + * @version $Rev$ $Date$ + */ +public class DomainManagerLauncher { + + static final Logger logger = Logger.getLogger(DomainManagerLauncher.class.getName()); + + /** + * Constructs a new DomainManagerLauncher. + */ + private DomainManagerLauncher() { + } + + /** + * Returns a new launcher instance. + * + * @return a new launcher instance + */ + public static DomainManagerLauncher newInstance() { + return new DomainManagerLauncher(); + } + + /** + * Creates a new DomainManager. + * + * @return a new DomainManager + * @throws LauncherException + */ + public <T> T createDomainManager() throws LauncherException { + return (T)domainManager("."); + } + + /** + * Creates a new DomainManager. + * + * @param rootDirectory the domain's root configuration directory + * + * @return a new DomainManager + * @throws LauncherException + */ + public <T> T createDomainManager(String rootDirectory) throws LauncherException { + return (T)domainManager(rootDirectory); + } + + public static void main(String[] args) throws Exception { + logger.info("Apache Tuscany SCA Domain Manager is starting..."); + + // Create a launcher + DomainManagerLauncher launcher = newInstance(); + + EquinoxHost equinox = null; + Object domainManager = null; + ShutdownThread shutdown = null; + try { + + // Start the OSGi host + equinox = new EquinoxHost(); + equinox.start(); + + // Start the domain manager + domainManager = launcher.createDomainManager(); + try { + domainManager.getClass().getMethod("start").invoke(domainManager); + } catch (Exception e) { + logger.log(Level.SEVERE, "SCA Domain Manager could not be started", e); + throw e; + } + logger.info("SCA Domain Manager is now started."); + + // Install a shutdown hook + ShutdownThread hook = new ShutdownThread(domainManager, equinox); + Runtime.getRuntime().addShutdownHook(hook); + + logger.info("Press enter to shutdown."); + try { + System.in.read(); + } catch (IOException e) { + + // Wait forever + Object lock = new Object(); + synchronized(lock) { + lock.wait(); + } + } + + } finally { + + // Remove the shutdown hook + if (shutdown != null) { + Runtime.getRuntime().removeShutdownHook(shutdown); + } + + // Stop the domain manager and OSGi host + if (domainManager != null) { + stopDomainManager(domainManager); + } + if (equinox != null) { + equinox.stop(); + } + } + } + + + /** + * Stop the given domain manager. + * + * @param domainManager + * @throws Exception + */ + private static void stopDomainManager(Object domainManager) throws Exception { + try { + domainManager.getClass().getMethod("stop").invoke(domainManager); + logger.info("SCA Domain Manager is now stopped."); + } catch (Exception e) { + logger.log(Level.SEVERE, "SCA Domain Manager could not be stopped", e); + throw e; + } + } + + private static class ShutdownThread extends Thread { + private Object domainManager; + private EquinoxHost equinox; + + public ShutdownThread(Object domainManager, EquinoxHost equinox) { + super(); + this.domainManager = domainManager; + this.equinox = equinox; + } + + public void run() { + try { + stopDomainManager(domainManager); + } catch (Exception e) { + // Ignore + } + try { + equinox.stop(); + } catch (Exception e) { + // Ignore + } + } + } +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHookConfigurator.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHookConfigurator.java new file mode 100644 index 0000000000..efe4d7bf8a --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHookConfigurator.java @@ -0,0 +1,72 @@ +/* + * 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.node.equinox.launcher; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.jar.Manifest; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.eclipse.osgi.baseadaptor.HookConfigurator; +import org.eclipse.osgi.baseadaptor.HookRegistry; + +/** + * Hook Configurator for Equinox. + * + * @version $Rev: $ $Date: $ + */ +public class EquinoxHookConfigurator implements HookConfigurator { + private static Logger logger = Logger.getLogger(HookConfigurator.class.getName()); + + private String[] jarFiles; + private Manifest manifest; + + public EquinoxHookConfigurator() { + + // Get the list of JAR files to install + String jarFilesProperty = System.getProperty("org.apache.tuscany.sca.node.launcher.equinox.jarFiles"); + jarFiles = jarFilesProperty.split(";"); + + // Create a single 'library' bundle for them + long libraryStart = System.currentTimeMillis(); + manifest = NodeLauncherUtil.libraryManifest(jarFiles); + + if (logger.isLoggable(Level.FINE)) { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + manifest.write(bos); + bos.close(); + logger.fine(new String(bos.toByteArray())); + } catch (IOException e) { + } + } + + logger.info("Third-party library manifest generated in " + (System.currentTimeMillis() - libraryStart) + " ms"); + + } + + public void addHooks(HookRegistry registry) { + + // Register our BundleFileFactory hook + registry.addBundleFileFactoryHook(new LibrariesBundleFileFactoryHook(manifest)); + } + +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHost.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHost.java new file mode 100644 index 0000000000..63313b6f39 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHost.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.node.equinox.launcher; + +import static org.apache.tuscany.sca.node.equinox.launcher.NodeLauncherUtil.bundleLocation; +import static org.apache.tuscany.sca.node.equinox.launcher.NodeLauncherUtil.string; +import static org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.eclipse.core.runtime.adaptor.EclipseStarter; +import org.eclipse.core.runtime.adaptor.LocationManager; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +/** + * Wraps the Equinox runtime. + */ +public class EquinoxHost { + private static Logger logger = Logger.getLogger(EquinoxHost.class.getName()); + + private BundleContext bundleContext; + private Bundle launcherBundle; + private EquinoxLauncherBundleHelper launcherActivator; + + private final static 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, " + // Force the classes to be imported from the system bundle + // + "javax.xml.stream, " + // + "javax.xml.stream.util, " + + "javax.sql," + + "org.w3c.dom, " + + "org.xml.sax, " + + "org.xml.sax.ext, " + + "org.xml.sax.helpers, " + + "javax.security.auth, " + + "javax.security.cert, " + + "javax.security.auth.login, " + + "javax.security.auth.callback, " + + "javax.naming, " + + "javax.naming.spi, " + + "javax.naming.directory, " + + "javax.management, " + + "javax.imageio, " + + "sun.misc, " + + "javax.net, " + + "javax.net.ssl, " + + "javax.crypto, " + + "javax.rmi, " + + "javax.transaction, " + + "javax.transaction.xa"; + + public BundleContext start() { + try { + // Configure Eclipse properties + Map<Object, Object> props = new HashMap<Object, Object>(); + + // Set system packages + props.put("org.osgi.framework.system.packages", systemPackages); + + // Use the boot classloader as the parent classloader + props.put("osgi.contextClassLoaderParent", "boot"); + + // Set the extension bundle + props.put("osgi.framework.extensions", "org.apache.tuscany.sca.node.launcher.equinox"); + + // Set startup properties + props.put(EclipseStarter.PROP_CLEAN, "true"); + + if (logger.isLoggable(Level.FINE)) { + props.put("osgi.console", "8085"); + } + + // Set location properties + // FIXME Use proper locations + props.put(LocationManager.PROP_INSTANCE_AREA, new File("target/workspace").toURI().toString()); + props.put(LocationManager.PROP_INSTALL_AREA, new File("target/eclipse/install").toURI().toString()); + props.put(LocationManager.PROP_CONFIG_AREA, new File("target/eclipse/config").toURI().toString()); + props.put(LocationManager.PROP_USER_AREA, new File("target/eclipse/user").toURI().toString()); + + // Find the Tuscany JARs + File tuscanyInstallDir = findTuscanyInstallDir(); + List<URL> urls; + if (tuscanyInstallDir != null) { + urls = JarFileFinder.findJarFiles(tuscanyInstallDir, new JarFileFinder.StandAloneJARFileNameFilter()); + } else { + urls = JarFileFinder.getClassPathEntries(JarFileFinder.class.getClassLoader(), false); + } + + // Sort out which are bundles (and not already installed) and which are just + // regular JARs + StringBuffer bundleFiles = new StringBuffer(); + StringBuffer bundleNames = new StringBuffer(); + StringBuffer jarFiles = new StringBuffer(); + for (URL url : urls) { + File file = NodeLauncherUtil.file(url); + String bundleName = getBundleName(file); + if (bundleName != null) { + bundleFiles.append(url.toString() + ";"); + bundleNames.append(bundleName + ";"); + } else { + if (file.isFile()) { + jarFiles.append(url.toString() + ";"); + } + } + } + props.put("org.apache.tuscany.sca.node.launcher.equinox.bundleFiles", bundleFiles.toString()); + props.put("org.apache.tuscany.sca.node.launcher.equinox.bundleNames", bundleNames.toString()); + props.put("org.apache.tuscany.sca.node.launcher.equinox.jarFiles", jarFiles.toString()); + + EclipseStarter.setInitialProperties(props); + + // Start Eclipse + bundleContext = EclipseStarter.startup(new String[]{}, null); + + // Install the launcher bundle + String bundleLocation = bundleLocation(); + logger.info("Installing launcher bundle: " + bundleLocation); + launcherBundle = bundleContext.installBundle(bundleLocation); + logger.info("Starting bundle: " + string(launcherBundle, false)); + launcherBundle.start(); + + // Manually call the LauncherBundleActivator for now + launcherActivator = new EquinoxLauncherBundleHelper(); + launcherActivator.start(launcherBundle.getBundleContext()); + + // Start all bundles for now to help diagnose any class loading issues + long activateStart = System.currentTimeMillis(); + for (Bundle bundle: bundleContext.getBundles()) { + if ((bundle.getState() & Bundle.ACTIVE) == 0) { + logger.info("Starting bundle: " + string(bundle, false)); + try { + bundle.start(); + } catch (Exception e) { + logger.log(Level.SEVERE, e.getMessage(), e); + } + logger.info("Bundle: " + string(bundle, false)); + } + } + logger.info("Tuscany bundles are started in " + (System.currentTimeMillis() - activateStart) + " ms."); + return bundleContext; + + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + public void stop() { + try { + + // Uninstall the launcher bundle + if (launcherActivator != null) { + launcherActivator.stop(launcherBundle.getBundleContext()); + } + if (launcherBundle != null) { + logger.info("Uninstalling bundle: " + string(launcherBundle, false)); + launcherBundle.uninstall(); + } + + // Shutdown Eclipse + EclipseStarter.shutdown(); + + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static File findTuscanyInstallDir() throws IOException { + String tuscanyDirName = JarFileFinder.getProperty(JarFileFinder.TUSCANY_HOME); + if (tuscanyDirName != null) { + File tuscanyInstallDir = new File(tuscanyDirName); + if (tuscanyInstallDir.exists() && tuscanyInstallDir.isDirectory()) + return tuscanyInstallDir; + } + return null; + } + + /** + * Returns the name of a bundle, or null if the given file is not a bundle. + * + * @param file + * @return + * @throws IOException + */ + private static String getBundleName(File file) throws IOException { + if (!file.exists()) { + return null; + } + String bundleName = null; + if (file.isDirectory()) { + File mf = new File(file, "META-INF/MANIFEST.MF"); + if (mf.isFile()) { + Manifest manifest = new Manifest(new FileInputStream(mf)); + bundleName = manifest.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME); + } + } else { + JarFile jar = new JarFile(file, false); + Manifest manifest = jar.getManifest(); + bundleName = manifest.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME); + jar.close(); + } + if (bundleName == null) { + return bundleName; + } + int sc = bundleName.indexOf(';'); + if (sc != -1) { + bundleName = bundleName.substring(0, sc); + } + return bundleName; + } + +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxLauncherBundleHelper.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxLauncherBundleHelper.java new file mode 100644 index 0000000000..97cc094f2b --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxLauncherBundleHelper.java @@ -0,0 +1,105 @@ +package org.apache.tuscany.sca.node.equinox.launcher; + +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleEvent; +import org.osgi.framework.BundleListener; + +/** + * Bundle activator which installs Tuscany modules into an OSGi runtime. + * + */ +public class EquinoxLauncherBundleHelper implements BundleListener { + private static Logger logger = Logger.getLogger(EquinoxLauncherBundleHelper.class.getName()); + + private List<Bundle> installedBundles = new ArrayList<Bundle>(); + private BundleContext bundleContext; + + public EquinoxLauncherBundleHelper() { + super(); + } + + public void start(BundleContext bundleContext) throws Exception { + this.bundleContext = bundleContext; + this.bundleContext.addBundleListener(this); + + // Install the Tuscany bundles + long start = System.currentTimeMillis(); + + // FIXME: SDO bundles dont have the correct dependencies + System.setProperty("commonj.sdo.impl.HelperProvider", "org.apache.tuscany.sdo.helper.HelperProviderImpl"); + + // Get the list of JAR files to install + String jarFilesProperty = System.getProperty("org.apache.tuscany.sca.node.launcher.equinox.jarFiles"); + String[] jarFiles = jarFilesProperty.split(";"); + + // Create a single 'library' bundle for them + long libraryStart = System.currentTimeMillis(); + //InputStream library = NodeLauncherUtil.libraryBundle(jarFiles); + Bundle libraryBundle = bundleContext.installBundle("org.apache.tuscany.sca.node.launcher.equinox.libraries", new ByteArrayInputStream(new byte[0])); + logger.info("Third-party library bundle installed in " + (System.currentTimeMillis() - libraryStart) + " ms: " + NodeLauncherUtil.string(libraryBundle, false)); + installedBundles.add(libraryBundle); + + // Get the set of already installed bundles + Set<String> alreadyInstalledBundleNames = new HashSet<String>(); + for (Bundle bundle: bundleContext.getBundles()) { + alreadyInstalledBundleNames.add(bundle.getSymbolicName()); + } + + // Get the list of bundle files and names to install + String bundleFilesProperty = System.getProperty("org.apache.tuscany.sca.node.launcher.equinox.bundleFiles"); + String[] bundleFiles = bundleFilesProperty.split(";"); + String bundleNamesProperty = System.getProperty("org.apache.tuscany.sca.node.launcher.equinox.bundleNames"); + String[] bundleNames = bundleNamesProperty.split(";"); + + // Install all the bundles that are not already installed + for (int i =0, n = bundleFiles.length; i < n; i++) { + String bundleFile = bundleFiles[i]; + String bundleName = bundleNames[i]; + if (!alreadyInstalledBundleNames.contains(bundleName)) { + if (bundleName.contains("org.eclipse.jdt.junit")) { + continue; + } + long installStart = System.currentTimeMillis(); + Bundle bundle = bundleContext.installBundle(bundleFile); + logger.info("Bundle installed in " + (System.currentTimeMillis() - installStart) + " ms: " + NodeLauncherUtil.string(bundle, false)); + installedBundles.add(bundle); + } + } + + long end = System.currentTimeMillis(); + logger.info("Tuscany bundles are installed in " + (end - start) + " ms."); + } + + public void stop(BundleContext bundleContext) throws Exception { + + // Uninstall all the bundles we've installed + for (int i = installedBundles.size() -1; i >= 0; i--) { + Bundle bundle = installedBundles.get(i); + try { + //if (logger.isLoggable(Level.FINE)) { + logger.info("Uninstalling bundle: " + NodeLauncherUtil.string(bundle, false)); + //} + bundle.uninstall(); + } catch (Exception e) { + logger.log(Level.SEVERE, e.getMessage(), e); + } + } + installedBundles.clear(); + + this.bundleContext.removeBundleListener(this); + this.bundleContext = null; + } + + public void bundleChanged(BundleEvent event) { + } + +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/JarFileFinder.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/JarFileFinder.java new file mode 100644 index 0000000000..0f595df758 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/JarFileFinder.java @@ -0,0 +1,373 @@ +/* + * 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.node.equinox.launcher; + +import static org.apache.tuscany.sca.node.equinox.launcher.NodeLauncherUtil.file; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FilenameFilter; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLClassLoader; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +/** + * + */ +public class JarFileFinder { + /** + * A file name filter used to filter JAR files. + */ + static class StandAloneJARFileNameFilter implements FilenameFilter { + + public boolean accept(File dir, String name) { + name = name.toLowerCase(); + + // Exclude tuscany-sca-all and tuscany-sca-manifest as they duplicate + // code in the individual runtime module JARs + if (name.startsWith("tuscany-sca-all")) { + return false; + } + if (name.startsWith("tuscany-sca-manifest")) { + return false; + } + + // Filter out the Tomcat and Webapp hosts + if (name.startsWith("tuscany-host-tomcat") || name.startsWith("tuscany-host-webapp")) { + //FIXME This is temporary + return false; + } + + // Include JAR and MAR files + if (name.endsWith(".jar")) { + return true; + } + if (name.endsWith(".mar")) { + return true; + } + return false; + } + } + + /** + * A file name filter used to filter JAR files. + */ + static class WebAppJARFileNameFilter extends StandAloneJARFileNameFilter { + + public boolean accept(File dir, String name) { + if (!super.accept(dir, name)) { + return false; + } + name = name.toLowerCase(); + + // Exclude servlet-api JARs + if (name.startsWith("servlet-api")) { + return false; + } + + // Exclude the Tomcat and Jetty hosts + if (name.startsWith("tuscany-host-tomcat") || name.startsWith("tuscany-host-jetty")) { + //FIXME This is temporary + return false; + } + + return true; + } + } + + private static final Logger logger = Logger.getLogger(JarFileFinder.class.getName()); + + static final String TUSCANY_HOME = "TUSCANY_HOME"; + private static final String TUSCANY_PATH = "TUSCANY_PATH"; + + /** + * Collect JAR files in the given directory + * @param directory + * @param urls + * @param filter + * @throws MalformedURLException + */ + private static void collectJARFiles(File directory, List<URL> urls, FilenameFilter filter) + throws MalformedURLException { + String[] files = directory.list(filter); + if (files != null) { + URL directoryURL = new URL(directory.toURI().toString() + "/"); + int count = 0; + for (String file : files) { + URL url = new URL(directoryURL, file); + urls.add(url); + count++; + } + if (count != 0) { + logger.fine("Runtime classpath: " + count + + " JAR" + + (count > 1 ? "s" : "") + + " from " + + directory.toString()); + } + } + } + + /** + * Collect JAR files under the given directory. + * + * @param directory + * @param jarDirectoryURLs + * @param jarURLs + * @param filter + * @throws MalformedURLException + */ + private static void collectJARFiles(String directory, + Set<URL> jarDirectoryURLs, + List<URL> jarURLs, + FilenameFilter filter) throws MalformedURLException { + File directoryFile = new File(directory); + URL directoryURL = directoryFile.toURI().toURL(); + if (!jarDirectoryURLs.contains(directoryURL) && directoryFile.exists()) { + + // Collect files under $TUSCANY_HOME + jarDirectoryURLs.add(directoryURL); + collectJARFiles(directoryFile, jarURLs, filter); + + // Collect files under $TUSCANY_HOME/modules + File modulesDirectory = new File(directoryFile, "modules"); + URL modulesDirectoryURL = modulesDirectory.toURI().toURL(); + if (!jarDirectoryURLs.contains(modulesDirectoryURL) && modulesDirectory.exists()) { + jarDirectoryURLs.add(modulesDirectoryURL); + collectJARFiles(modulesDirectory, jarURLs, filter); + } + + // Collect files under $TUSCANY_HOME/lib + File libDirectory = new File(directoryFile, "lib"); + URL libDirectoryURL = libDirectory.toURI().toURL(); + if (!jarDirectoryURLs.contains(libDirectoryURL) && libDirectory.exists()) { + jarDirectoryURLs.add(libDirectoryURL); + collectJARFiles(libDirectory, jarURLs, filter); + } + } + } + + /** + * Returns a ClassLoader for the Tuscany runtime JARs. + * + * @param parentClassLoader + * @param filter + * + * @return + */ + public static List<URL> findJarFiles(File root, FilenameFilter filter) throws FileNotFoundException, + URISyntaxException, MalformedURLException { + + // Build list of runtime JARs + Set<URL> jarDirectoryURLs = new HashSet<URL>(); + List<URL> jarURLs = new ArrayList<URL>(); + + URL url = null; + if (root != null) { + url = root.toURI().toURL(); + } else { + // First determine the path to the launcher class + String resource = JarFileFinder.class.getName().replace('.', '/') + ".class"; + url = JarFileFinder.class.getClassLoader().getResource(resource); + if (url == null) { + throw new FileNotFoundException(resource); + } + + url = getContainer(url, resource); + } + URI uri = url.toURI(); + + // If the launcher class is in a JAR, add all runtime JARs from directory containing + // that JAR (e.g. the Tuscany modules directory) as well as the ../modules and + // ../lib directories + if (url != null && "file".equals(url.getProtocol())) { + + File file = new File(uri); + if (file.exists()) { + File jarDirectory = file.getParentFile(); + if (jarDirectory != null && jarDirectory.exists()) { + + // Collect JAR files from the directory containing the input JAR + // (e.g. the Tuscany modules directory) + URL jarDirectoryURL = jarDirectory.toURI().toURL(); + jarDirectoryURLs.add(jarDirectoryURL); + collectJARFiles(jarDirectory, jarURLs, filter); + + File homeDirectory = jarDirectory.getParentFile(); + if (homeDirectory != null && homeDirectory.exists()) { + + // Collect JARs from the ../modules directory + File modulesDirectory = new File(homeDirectory, "modules"); + URL modulesDirectoryURL = modulesDirectory.toURI().toURL(); + if (!jarDirectoryURLs.contains(modulesDirectoryURL) && modulesDirectory.exists()) { + jarDirectoryURLs.add(modulesDirectoryURL); + collectJARFiles(modulesDirectory, jarURLs, filter); + } + + // Collect JARs from the ../lib directory + File libDirectory = new File(homeDirectory, "lib"); + URL libDirectoryURL = libDirectory.toURI().toURL(); + if (!jarDirectoryURLs.contains(libDirectoryURL) && libDirectory.exists()) { + jarDirectoryURLs.add(libDirectoryURL); + collectJARFiles(libDirectory, jarURLs, filter); + } + } + } + } + } + + // Look for a TUSCANY_HOME system property or environment variable + // Add all the JARs found under $TUSCANY_HOME, $TUSCANY_HOME/modules + // and $TUSCANY_HOME/lib + String home = getProperty(TUSCANY_HOME); + if (home != null && home.length() != 0) { + logger.fine(TUSCANY_HOME + ": " + home); + collectJARFiles(home, jarDirectoryURLs, jarURLs, filter); + } + + // Look for a TUSCANY_PATH system property or environment variable + // Add all the JARs found under $TUSCANY_PATH, $TUSCANY_PATH/modules + // and $TUSCANY_PATH/lib + String ext = getProperty(TUSCANY_PATH); + if (ext != null && ext.length() != 0) { + logger.fine(TUSCANY_PATH + ": " + ext); + String separator = getProperty("path.separator"); + for (StringTokenizer tokens = new StringTokenizer(ext, separator); tokens.hasMoreTokens();) { + collectJARFiles(tokens.nextToken(), jarDirectoryURLs, jarURLs, filter); + } + } + + return jarURLs; + + } + + + /** + * Returns contribution JARs available on the classpath. + * + * @return + */ + static List<URL> getClassPathEntries(ClassLoader classLoader, boolean recursive) { + Set<URL> entries = new HashSet<URL>(); + list(entries, classLoader, recursive); + return new ArrayList<URL>(entries); + } + + /** + * Collect JARs on the classpath of a URLClassLoader + * @param urls + * @param cl + */ + private static void list(Set<URL> urls, ClassLoader cl, boolean recursive) { + if (cl == null) { + return; + } + + // Collect JARs from the URLClassLoader's classpath + if (cl instanceof URLClassLoader) { + URL[] jarURLs = ((URLClassLoader)cl).getURLs(); + if (jarURLs != null) { + for (URL jarURL : jarURLs) { + urls.add(jarURL); + } + } + } + + // Collect JARs from the parent ClassLoader + if (recursive) { + list(urls, cl.getParent(), recursive); + } + } + + + static String getProperty(final String prop) { + return AccessController.doPrivileged(new PrivilegedAction<String>() { + public String run() { + String value = System.getProperty(prop); + if (value == null || value.length() == 0) { + return System.getenv(prop); + } else { + return value; + } + } + }); + } + + private static URL getContainer(URL resourceURL, String resourceName) { + URL root = null; + // "jar:file://....../something.jar!/a/b/c/app.composite" + try { + String url = resourceURL.toExternalForm(); + String protocol = resourceURL.getProtocol(); + if ("file".equals(protocol)) { + // directory contribution + if (url.endsWith("/" + resourceName)) { + final String location = url.substring(0, url.length() - resourceName.length() - 1); + // workaround from evil URL/URI form Maven + // contributionURL = FileHelper.toFile(new URL(location)).toURI().toURL(); + // Allow privileged access to open URL stream. Add FilePermission to added to + // security policy file. + try { + root = AccessController.doPrivileged(new PrivilegedExceptionAction<URL>() { + public URL run() throws IOException { + return file(new URL(location)).toURI().toURL(); + } + }); + } catch (PrivilegedActionException e) { + throw (MalformedURLException)e.getException(); + } + } + + } else if ("jar".equals(protocol)) { + // jar contribution + String location = url.substring(4, url.lastIndexOf("!/")); + // workaround for evil URL/URI from Maven + root = file(new URL(location)).toURI().toURL(); + + } else if ("wsjar".equals(protocol)) { + // See https://issues.apache.org/jira/browse/TUSCANY-2219 + // wsjar contribution + String location = url.substring(6, url.lastIndexOf("!/")); + // workaround for evil url/uri from maven + root = file(new URL(location)).toURI().toURL(); + + } else if (protocol != null && (protocol.equals("bundle") || protocol.equals("bundleresource"))) { + root = new URL(resourceURL.getProtocol(), resourceURL.getHost(), resourceURL.getPort(), "/"); + } + } catch (MalformedURLException mfe) { + throw new IllegalArgumentException(mfe); + } + return root; + } + +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/LauncherException.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/LauncherException.java new file mode 100644 index 0000000000..b9bb70b5d7 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/LauncherException.java @@ -0,0 +1,55 @@ +/* + * 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.node.equinox.launcher; + + +/** + * Denotes an error launching an SCA domain manager or node. + * + * @version $Rev$ $Date$ + */ +public class LauncherException extends Exception { + private static final long serialVersionUID = 4581189418849190567L; + + public LauncherException() { + super(); + } + + /** + * @param message + * @param cause + */ + public LauncherException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @param message + */ + public LauncherException(String message) { + super(message); + } + + /** + * @param cause + */ + public LauncherException(Throwable cause) { + super(cause); + } +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/LibrariesBundleFileFactoryHook.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/LibrariesBundleFileFactoryHook.java new file mode 100644 index 0000000000..4ff93ea84b --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/LibrariesBundleFileFactoryHook.java @@ -0,0 +1,148 @@ +/* + * 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.node.equinox.launcher; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Enumeration; +import java.util.jar.Manifest; + +import org.eclipse.osgi.baseadaptor.BaseData; +import org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry; +import org.eclipse.osgi.baseadaptor.bundlefile.BundleFile; + +/** + * A bundle file factory hook that. + * + * @version $Rev: $ $Date: $ +*/ +public class LibrariesBundleFileFactoryHook implements org.eclipse.osgi.baseadaptor.hooks.BundleFileFactoryHook { + + private Manifest manifest; + + private static class LibrariesBundleFile extends BundleFile { + + private static class ManifestBundleEntry extends BundleEntry { + + private byte[] bytes; + + public ManifestBundleEntry(Manifest manifest) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + manifest.write(bos); + bytes = bos.toByteArray(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + @Override + public URL getFileURL() { + return null; + } + + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(bytes); + } + + @Override + public URL getLocalURL() { + return null; + } + + @Override + public String getName() { + return "META-INF/MANIFEST.MF"; + } + + @Override + public long getSize() { + return bytes.length; + } + + @Override + public long getTime() { + return -1; + } + + @Override + public byte[] getBytes() throws IOException { + return bytes; + } + } + + private Manifest manifest; + + public LibrariesBundleFile(Object baseFile, Manifest manifest) { + super((File)baseFile); + this.manifest = manifest; + } + + @Override + public void close() throws IOException { + } + + @Override + public boolean containsDir(String dir) { + return false; + } + + @Override + public BundleEntry getEntry(String path) { + if ("META-INF/MANIFEST.MF".equals(path)) { + return new ManifestBundleEntry(manifest); + } + return null; + } + + @Override + public Enumeration getEntryPaths(String path) { + return null; + } + + @Override + public File getFile(String path, boolean nativeCode) { + return null; + } + + @Override + public void open() throws IOException { + } + } + + public LibrariesBundleFileFactoryHook(Manifest manifest) { + this.manifest = manifest; + } + + public BundleFile createBundleFile(Object content, BaseData data, boolean base) throws IOException { + // Equinox will resolve external classpath against the base bundle + if ("org.apache.tuscany.sca.node.launcher.equinox.libraries".equals(data.getLocation()) && base) { + return new LibrariesBundleFile(content, manifest); + } else { + return null; + } + } + +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeDaemonLauncher.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeDaemonLauncher.java new file mode 100644 index 0000000000..b77382d6a0 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeDaemonLauncher.java @@ -0,0 +1,159 @@ +/* + * 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.node.equinox.launcher; + +import static org.apache.tuscany.sca.node.equinox.launcher.NodeLauncherUtil.nodeDaemon; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * A launcher for the SCA Node daemon. + * + * @version $Rev$ $Date$ + */ +public class NodeDaemonLauncher { + + static final Logger logger = Logger.getLogger(NodeDaemonLauncher.class.getName()); + + /** + * Constructs a new node daemon launcher. + */ + private NodeDaemonLauncher() { + } + + /** + * Returns a new launcher instance. + * + * @return a new launcher instance + */ + public static NodeDaemonLauncher newInstance() { + return new NodeDaemonLauncher(); + } + + /** + * Creates a new node daemon. + * + * @param + * @return a new node daemon + * @throws LauncherException + */ + public <T> T createNodeDaemon() throws LauncherException { + return (T)nodeDaemon(); + } + + public static void main(String[] args) throws Exception { + logger.info("Apache Tuscany SCA Node Daemon is starting..."); + + // Create a node launcher + NodeDaemonLauncher launcher = newInstance(); + + EquinoxHost equinox = null; + Object node = null; + ShutdownThread shutdown = null; + try { + + // Start the OSGi host + equinox = new EquinoxHost(); + equinox.start(); + + // Start the node + node = launcher.createNodeDaemon(); + try { + node.getClass().getMethod("start").invoke(node); + } catch (Exception e) { + logger.log(Level.SEVERE, "SCA Node Daemon could not be started", e); + throw e; + } + logger.info("SCA Node Daemon is now started."); + + // Install a shutdown hook + shutdown = new ShutdownThread(node, equinox); + Runtime.getRuntime().addShutdownHook(shutdown); + + logger.info("Press enter to shutdown."); + try { + System.in.read(); + } catch (IOException e) { + + // Wait forever + Object lock = new Object(); + synchronized(lock) { + lock.wait(); + } + } + } finally { + + // Remove the shutdown hook + if (shutdown != null) { + Runtime.getRuntime().removeShutdownHook(shutdown); + } + + // Stop the node + if (node != null) { + stopNode(node); + } + if (equinox != null) { + equinox.stop(); + } + } + } + + /** + * Stop the given node. + * + * @param node + * @throws Exception + */ + private static void stopNode(Object node) throws Exception { + try { + node.getClass().getMethod("stop").invoke(node); + logger.info("SCA Node Daemon is now stopped."); + } catch (Exception e) { + logger.log(Level.SEVERE, "SCA Node Daemon could not be stopped", e); + throw e; + } + } + + private static class ShutdownThread extends Thread { + private Object node; + private EquinoxHost equinox; + + public ShutdownThread(Object node, EquinoxHost equinox) { + super(); + this.node = node; + this.equinox = equinox; + } + + public void run() { + try { + stopNode(node); + } catch (Exception e) { + // Ignore + } + try { + equinox.stop(); + } catch (Exception e) { + // Ignore + } + } + } +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncher.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncher.java new file mode 100644 index 0000000000..f3bb8c04ae --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncher.java @@ -0,0 +1,232 @@ +/* + * 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.node.equinox.launcher; + +import static org.apache.tuscany.sca.node.equinox.launcher.NodeLauncherUtil.node; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.osgi.framework.BundleContext; + +/** + * A launcher for SCA nodes. + * + * @version $Rev$ $Date$ + */ +public class NodeLauncher { + + static final Logger logger = Logger.getLogger(NodeLauncher.class.getName()); + private EquinoxHost host; + private BundleContext bundleContext; + + /** + * Constructs a new node launcher. + */ + private NodeLauncher() { + host = new EquinoxHost(); + bundleContext = host.start(); + } + + /** + * Returns a new launcher instance. + * + * @return a new launcher instance + */ + public static NodeLauncher newInstance() { + return new NodeLauncher(); + } + + /** + * Creates a new SCA node from the configuration URL + * + * @param configurationURL the URL of the node configuration which is the ATOM feed + * that contains the URI of the composite and a collection of URLs for the contributions + * + * @return a new SCA node. + * @throws LauncherException + */ + public <T> T createNodeFromURL(String configurationURL) throws LauncherException { + return (T)node(configurationURL, null, null, null, null, bundleContext); + } + + /** + * Creates a new SCA OSGi Node. + * + * @param compositeURI the URI of the composite to use + * @param contributions the URI of the contributions that provides the composites and related + * artifacts. If the list is empty, then we will use the thread context classloader to discover + * the contribution on the classpath + * + * @return a new SCA node. + * @throws LauncherException + */ + public <T> T createNode(String compositeURI, Contribution... contributions) throws LauncherException { + return (T)node(null, compositeURI, null, contributions, null, bundleContext); + } + + /** + * Creates a new SCA OSGi Node. + * + * @param compositeURI the URI of the composite to use + * @param compositeContent the XML content of the composite to use + * @param contributions the URI of the contributions that provides the composites and related artifacts + * @return a new SCA node. + * @throws LauncherException + */ + public <T> T createNode(String compositeURI, String compositeContent, Contribution... contributions) + throws LauncherException { + return (T)node(null, compositeURI, compositeContent, contributions, null, bundleContext); + } + + /** + * Create a SCA node based on the discovery of the contribution on the classpath for the + * given classloader. This method should be treated a convenient shortcut with the following + * assumptions: + * <ul> + * <li>This is a standalone application and there is a deployable composite file on the classpath. + * <li>There is only one contribution which contains the deployable composite file physically in its packaging hierarchy. + * </ul> + * + * @param compositeURI The URI of the composite file relative to the root of the enclosing contribution + * @param classLoader The ClassLoader used to load the composite file as a resource. If the value is null, + * then thread context classloader will be used + * @return A newly created SCA node + */ + public <T> T createNodeFromClassLoader(String compositeURI, ClassLoader classLoader) throws LauncherException { + return (T)node(null, compositeURI, null, null, classLoader, bundleContext); + } + + public static void main(String[] args) throws Exception { + logger.info("Apache Tuscany SCA Node is starting..."); + + // Create a node launcher + NodeLauncher launcher = newInstance(); + + EquinoxHost equinox = launcher.host; + Object node = null; + ShutdownThread shutdown = null; + try { + + if (args.length ==1) { + + // Create a node from a configuration URI + String configurationURI = args[0]; + logger.info("SCA Node configuration: " + configurationURI); + node = launcher.createNodeFromURL(configurationURI); + } else { + + // Create a node from a composite URI and a contribution location + String compositeURI = args[0]; + String contributionLocation = args[1]; + logger.info("SCA composite: " + compositeURI); + logger.info("SCA contribution: " + contributionLocation); + node = launcher.createNode(compositeURI, new Contribution("default", contributionLocation)); + } + + // Start the node + try { + node.getClass().getMethod("start").invoke(node); + } catch (Exception e) { + logger.log(Level.SEVERE, "SCA Node could not be started", e); + throw e; + } + logger.info("SCA Node is now started."); + + // Install a shutdown hook + shutdown = new ShutdownThread(node, equinox); + Runtime.getRuntime().addShutdownHook(shutdown); + + logger.info("Press enter to shutdown."); + try { + System.in.read(); + } catch (IOException e) { + + // Wait forever + Object lock = new Object(); + synchronized(lock) { + lock.wait(); + } + } + } finally { + + // Remove the shutdown hook + if (shutdown != null) { + Runtime.getRuntime().removeShutdownHook(shutdown); + } + + // Stop the node + if (node != null) { + stopNode(node); + } + if (equinox != null) { + equinox.stop(); + } + } + } + + public void destroy() { + if (host != null) { + host.stop(); + bundleContext = null; + } + } + + /** + * Stop the given node. + * + * @param node + * @throws Exception + */ + private static void stopNode(Object node) throws Exception { + try { + node.getClass().getMethod("stop").invoke(node); + logger.info("SCA Node is now stopped."); + } catch (Exception e) { + logger.log(Level.SEVERE, "SCA Node could not be stopped", e); + throw e; + } + } + + private static class ShutdownThread extends Thread { + private Object node; + private EquinoxHost equinox; + + public ShutdownThread(Object node, EquinoxHost equinox) { + super(); + this.node = node; + this.equinox = equinox; + } + + public void run() { + try { + stopNode(node); + } catch (Exception e) { + // Ignore + } + try { + equinox.stop(); + } catch (Exception e) { + // Ignore + } + } + } +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherUtil.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherUtil.java new file mode 100644 index 0000000000..b422651244 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherUtil.java @@ -0,0 +1,374 @@ +/* + * 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.node.equinox.launcher; + +import static org.osgi.framework.Constants.BUNDLE_CLASSPATH; +import static org.osgi.framework.Constants.BUNDLE_MANIFESTVERSION; +import static org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME; +import static org.osgi.framework.Constants.DYNAMICIMPORT_PACKAGE; +import static org.osgi.framework.Constants.EXPORT_PACKAGE; +import static org.osgi.framework.Constants.IMPORT_PACKAGE; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.HashSet; +import java.util.Set; +import java.util.jar.Attributes; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +/** + * Common functions and constants used by the admin components. + * + * @version $Rev$ $Date$ + */ +final class NodeLauncherUtil { + + private static final String LAUNCHER_EQUINOX_LIBRARIES = "org.apache.tuscany.sca.node.launcher.equinox.libraries"; + + private static final String SCANODE_FACTORY = "org.apache.tuscany.sca.node.SCANodeFactory"; + + private static final String DOMAIN_MANAGER_LAUNCHER_BOOTSTRAP = + "org.apache.tuscany.sca.domain.manager.launcher.DomainManagerLauncherBootstrap"; + + private static final String NODE_IMPLEMENTATION_DAEMON_BOOTSTRAP = + "org.apache.tuscany.sca.implementation.node.launcher.NodeImplementationDaemonBootstrap"; + + private static final String NODE_IMPLEMENTATION_LAUNCHER_BOOTSTRAP = + "org.apache.tuscany.sca.implementation.node.launcher.NodeImplementationLauncherBootstrap"; + + /** + * Collect JAR files under the given directory. + * @param contributions + * @param bundleContext TODO + * @throws LauncherException + */ + static Object node(String configurationURI, + String compositeURI, + String compositeContent, + Contribution[] contributions, + ClassLoader contributionClassLoader, BundleContext bundleContext) throws LauncherException { + try { + Bundle bundle = null; + for (Bundle b : bundleContext.getBundles()) { + if ("org.apache.tuscany.sca.implementation.node.runtime".equals(b.getSymbolicName())) { + bundle = b; + break; + } + } + if (bundle == null) { + throw new IllegalStateException( + "Bundle org.apache.tuscany.sca.implementation.node.runtime is not installed"); + } + // Use Java reflection to create the node as only the runtime class + // loader knows the runtime classes required by the node + Class<?> bootstrapClass = bundle.loadClass(NODE_IMPLEMENTATION_LAUNCHER_BOOTSTRAP); + + Object bootstrap; + if (configurationURI != null) { + + // Construct the node with a configuration URI + bootstrap = bootstrapClass.getConstructor(String.class).newInstance(configurationURI); + + } else if (contributionClassLoader != null) { + + // Construct the node with a compositeURI and a classloader + Constructor<?> constructor = bootstrapClass.getConstructor(String.class, ClassLoader.class); + bootstrap = constructor.newInstance(compositeURI, contributionClassLoader); + + } else if (compositeContent != null) { + + // Construct the node with a composite URI, the composite content and + // the URIs and locations of a list of contributions + Constructor<?> constructor = + bootstrapClass.getConstructor(String.class, String.class, String[].class, String[].class); + String[] uris = new String[contributions.length]; + String[] locations = new String[contributions.length]; + for (int i = 0; i < contributions.length; i++) { + uris[i] = contributions[i].getURI(); + locations[i] = contributions[i].getLocation(); + } + bootstrap = constructor.newInstance(compositeURI, compositeContent, uris, locations); + + } else { + + // Construct the node with a composite URI and the URIs and + // locations of a list of contributions + Constructor<?> constructor = + bootstrapClass.getConstructor(String.class, String[].class, String[].class); + String[] uris = new String[contributions.length]; + String[] locations = new String[contributions.length]; + for (int i = 0; i < contributions.length; i++) { + uris[i] = contributions[i].getURI(); + locations[i] = contributions[i].getLocation(); + } + bootstrap = constructor.newInstance(compositeURI, uris, locations); + } + + Object node = bootstrapClass.getMethod("getNode").invoke(bootstrap); + try { + Class<?> type = Class.forName(SCANODE_FACTORY); + type = type.getDeclaredClasses()[0]; + return type.getMethod("createProxy", Class.class, Object.class).invoke(null, type, node); + } catch (ClassNotFoundException e) { + // Ignore + } + return node; + + } catch (Exception e) { + NodeLauncher.logger.log(Level.SEVERE, "SCA Node could not be created", e); + throw new LauncherException(e); + } + } + + /** + * Creates a new node daemon. + * + * @throws LauncherException + */ + static Object nodeDaemon() throws LauncherException { + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + try { + + // Use Java reflection to create the node daemon as only the runtime class + // loader knows the runtime classes required by the node + String className = NODE_IMPLEMENTATION_DAEMON_BOOTSTRAP; + Class<?> bootstrapClass; + bootstrapClass = Class.forName(className, false, tccl); + Object bootstrap = bootstrapClass.getConstructor().newInstance(); + + Object nodeDaemon = bootstrapClass.getMethod("getNode").invoke(bootstrap); + return nodeDaemon; + + } catch (Exception e) { + NodeDaemonLauncher.logger.log(Level.SEVERE, "SCA Node Daemon could not be created", e); + throw new LauncherException(e); + } finally { + Thread.currentThread().setContextClassLoader(tccl); + } + } + + /** + * Creates a new domain manager. + * + * @throws LauncherException + */ + static Object domainManager(String rootDirectory) throws LauncherException { + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + try { + + // Use Java reflection to create the node daemon as only the runtime class + // loader knows the runtime classes required by the node + String className = DOMAIN_MANAGER_LAUNCHER_BOOTSTRAP; + Class<?> bootstrapClass; + bootstrapClass = Class.forName(className, false, tccl); + Constructor<?> constructor = bootstrapClass.getConstructor(String.class); + Object bootstrap = constructor.newInstance(rootDirectory); + + Object domainManager = bootstrapClass.getMethod("getNode").invoke(bootstrap); + return domainManager; + + } catch (Exception e) { + DomainManagerLauncher.logger.log(Level.SEVERE, "SCA Domain Manager could not be created", e); + throw new LauncherException(e); + } finally { + Thread.currentThread().setContextClassLoader(tccl); + } + } + + static File file(URL url) { + if (url == null || !url.getProtocol().equals("file")) { + return null; + } else { + String filename = url.getFile().replace('/', File.separatorChar); + int pos = 0; + while ((pos = filename.indexOf('%', pos)) >= 0) { + if (pos + 2 < filename.length()) { + String hexStr = filename.substring(pos + 1, pos + 3); + char ch = (char)Integer.parseInt(hexStr, 16); + filename = filename.substring(0, pos) + ch + filename.substring(pos + 3); + } + } + return new File(filename); + } + } + + static Pattern pattern = Pattern.compile("-([0-9.]+)"); + + private static String version(String jarFile) { + Matcher matcher = pattern.matcher(jarFile); + String version = "1.0.0"; + if (matcher.find()) { + version = matcher.group(); + if (version.endsWith(".")) { + version = version.substring(1, version.length() - 1); + } else { + version = version.substring(1); + } + } + return version; + } + + private static void addPackages(String jarFile, Set<String> packages) throws IOException { + String version = ";version=" + version(jarFile); + ZipInputStream is = new ZipInputStream(new FileInputStream(file(new URL(jarFile)))); + ZipEntry entry; + while ((entry = is.getNextEntry()) != null) { + String entryName = entry.getName(); + if (!entry.isDirectory() && entryName != null + && entryName.length() > 0 + && !entryName.startsWith(".") + && entryName.endsWith(".class") // Exclude resources from Export-Package + && entryName.lastIndexOf("/") > 0) { + String pkg = entryName.substring(0, entryName.lastIndexOf("/")).replace('/', '.') + version; + packages.add(pkg); + } + } + is.close(); + } + + static Manifest libraryManifest(String[] jarFiles) throws IllegalStateException { + try { + + // List exported packages and bundle classpath entries + StringBuffer classpath = new StringBuffer(); + StringBuffer exports = new StringBuffer(); + StringBuffer imports = new StringBuffer(); + Set<String> packages = new HashSet<String>(); + for (String jarFile : jarFiles) { + addPackages(jarFile, packages); + classpath.append("\"external:"); + classpath.append(file(new URL(jarFile)).getPath().replace(File.separatorChar, '/')); + classpath.append("\","); + } + + Set<String> importPackages = new HashSet<String>(); + for (String pkg : packages) { + exports.append(pkg); + exports.append(','); + + String importPackage = pkg; + int index = pkg.indexOf(';'); + if (index != -1) { + importPackage = pkg.substring(0, index); + } + if (!importPackages.contains(importPackage)) { + imports.append(importPackage); + imports.append(','); + importPackages.add(importPackage); + } + } + + // Create a manifest + Manifest manifest = new Manifest(); + Attributes attributes = manifest.getMainAttributes(); + attributes.putValue("Manifest-Version", "1.0"); + attributes.putValue(BUNDLE_MANIFESTVERSION, "2"); + attributes.putValue(BUNDLE_SYMBOLICNAME, LAUNCHER_EQUINOX_LIBRARIES); + attributes.putValue(EXPORT_PACKAGE, exports.substring(0, exports.length() - 1)); + attributes.putValue(IMPORT_PACKAGE, imports.substring(0, imports.length() - 1)); + attributes.putValue(BUNDLE_CLASSPATH, classpath.substring(0, classpath.length() - 1)); + attributes.putValue(DYNAMICIMPORT_PACKAGE, "*"); + + return manifest; + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + static byte[] generateBundle(Manifest mf) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + JarOutputStream jos = new JarOutputStream(bos, mf); + jos.close(); + return bos.toByteArray(); + } + + /** + * Returns the location of this bundle. + * + * @return + * @throws IOException + */ + static String bundleLocation() throws IOException, URISyntaxException { + String resource = NodeLauncherUtil.class.getName().replace('.', '/') + ".class"; + URL url = NodeLauncherUtil.class.getClassLoader().getResource(resource); + if (url == null) { + throw new FileNotFoundException(resource); + } + URI uri = url.toURI(); + + String scheme = uri.getScheme(); + if (scheme.equals("jar")) { + String path = uri.toString().substring(4); + int i = path.indexOf("!/"); + path = path.substring(0, i); + return path; + } else { + String path = uri.toString(); + path = path.substring(0, path.length() - resource.length()); + return path; + } + } + + static String string(Bundle b, boolean verbose) { + StringBuffer sb = new StringBuffer(); + sb.append(b.getBundleId()).append(" ").append(b.getSymbolicName()); + int s = b.getState(); + if ((s & Bundle.UNINSTALLED) != 0) { + sb.append(" UNINSTALLED"); + } + if ((s & Bundle.INSTALLED) != 0) { + sb.append(" INSTALLED"); + } + if ((s & Bundle.RESOLVED) != 0) { + sb.append(" RESOLVED"); + } + if ((s & Bundle.STARTING) != 0) { + sb.append(" STARTING"); + } + if ((s & Bundle.STOPPING) != 0) { + sb.append(" STOPPING"); + } + if ((s & Bundle.ACTIVE) != 0) { + sb.append(" ACTIVE"); + } + + if (verbose) { + sb.append(" ").append(b.getLocation()); + sb.append(" ").append(b.getHeaders()); + } + return sb.toString(); + } +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeMain.java b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeMain.java new file mode 100644 index 0000000000..17172dbd5e --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeMain.java @@ -0,0 +1,44 @@ +/* + * 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.node.equinox.launcher; + + +/** + * Main class for this JAR. + * With no arguments this class launches the SCA Node Daemon. + * With a "domain" argument it launches the SCA domain admin node. + * With any other argument it launches an SCA Node. + * + * @version $Rev$ $Date$ + */ +public class NodeMain { + + public static void main(String[] args) throws Exception { + if (args.length != 0) { + if (args[0].equals("domain")) { + DomainManagerLauncher.main(args); + } else { + NodeLauncher.main(args); + } + } else { + NodeDaemonLauncher.main(args); + } + } +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/main/resources/hookconfigurators.properties b/java/sca/contrib/modules/node-launcher-equinox/src/main/resources/hookconfigurators.properties new file mode 100644 index 0000000000..cf9c0f74df --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/main/resources/hookconfigurators.properties @@ -0,0 +1,16 @@ +# 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. +hook.configurators=org.apache.tuscany.sca.node.equinox.launcher.EquinoxHookConfigurator
\ No newline at end of file diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/test/java/hello/HelloWorld.java b/java/sca/contrib/modules/node-launcher-equinox/src/test/java/hello/HelloWorld.java new file mode 100644 index 0000000000..2f519cb81d --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/test/java/hello/HelloWorld.java @@ -0,0 +1,30 @@ +/* + * 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 hello; + +import org.osoa.sca.annotations.Remotable; + +/** + * HelloWorld interface + */ +@Remotable +public interface HelloWorld { + String hello(String name); +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/test/java/hello/HelloWorldClient.java b/java/sca/contrib/modules/node-launcher-equinox/src/test/java/hello/HelloWorldClient.java new file mode 100644 index 0000000000..11e008619c --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/test/java/hello/HelloWorldClient.java @@ -0,0 +1,50 @@ +/* + * 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 hello; + +import org.osoa.sca.annotations.EagerInit; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Reference; +import org.osoa.sca.annotations.Scope; + +/** + * This client program shows how to create an SCA runtime, start it, + * and locate and invoke a SCA component + */ +@Scope("COMPOSITE") +@EagerInit +public class HelloWorldClient { + + private HelloWorld hw; + + @Reference + public void setHelloWorld(HelloWorld hw) { + this.hw = hw; + } + + @Init + public void hello() { + // Say hello + System.out.println("Contribution ClassLoader: " + getClass().getClassLoader()); + System.out.println("SCA API ClassLoader: " + Reference.class.getClassLoader()); + System.out.println(hw.hello("Equinox")); + } + +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/test/java/hello/HelloWorldImpl.java b/java/sca/contrib/modules/node-launcher-equinox/src/test/java/hello/HelloWorldImpl.java new file mode 100644 index 0000000000..e51d3c79d9 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/test/java/hello/HelloWorldImpl.java @@ -0,0 +1,30 @@ +/* + * 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 hello; + +/** + * HelloWorldImpl + */ +public class HelloWorldImpl implements HelloWorld { + public String hello(String name) { + System.out.println("Name: " + name); + return "Hello, " + name; + } +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/test/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxOSGiHostTestCase.java b/java/sca/contrib/modules/node-launcher-equinox/src/test/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxOSGiHostTestCase.java new file mode 100644 index 0000000000..da0ab774a3 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/test/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxOSGiHostTestCase.java @@ -0,0 +1,95 @@ +/* + * 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.node.equinox.launcher; + +import java.util.Dictionary; +import java.util.Enumeration; + +import junit.framework.Assert; + +import org.junit.Test; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + + +/** + * + */ +public class EquinoxOSGiHostTestCase { + @Test + public void testStartThenStop() { + EquinoxHost host = new EquinoxHost(); + BundleContext context = host.start(); + Assert.assertNotNull(context); + for (Bundle b : context.getBundles()) { + System.out.println(toString(b, false)); + } + host.stop(); + } + + @Test + public void testStartTwice() { + EquinoxHost host = new EquinoxHost(); + host.start(); + try { + host.start(); + Assert.fail(); + } catch (IllegalStateException e) { + Assert.assertTrue(IllegalStateException.class.isInstance(e.getCause())); + } finally { + host.stop(); + } + } + + public static String toString(Bundle b, boolean verbose) { + StringBuffer sb = new StringBuffer(); + sb.append(b.getBundleId()).append(" ").append(b.getSymbolicName()); + int s = b.getState(); + if ((s & Bundle.UNINSTALLED) != 0) { + sb.append(" UNINSTALLED"); + } + if ((s & Bundle.INSTALLED) != 0) { + sb.append(" INSTALLED"); + } + if ((s & Bundle.RESOLVED) != 0) { + sb.append(" RESOLVED"); + } + if ((s & Bundle.STARTING) != 0) { + sb.append(" STARTING"); + } + if ((s & Bundle.STOPPING) != 0) { + sb.append(" STOPPING"); + } + if ((s & Bundle.ACTIVE) != 0) { + sb.append(" ACTIVE"); + } + + sb.append(" ").append(b.getLocation()); + if (verbose) { + Dictionary<Object, Object> dict = b.getHeaders(); + Enumeration<Object> keys = dict.keys(); + while (keys.hasMoreElements()) { + Object key = keys.nextElement(); + sb.append(" ").append(key).append("=").append(dict.get(key)); + } + } + return sb.toString(); + } +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/test/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherTestCase.java b/java/sca/contrib/modules/node-launcher-equinox/src/test/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherTestCase.java new file mode 100644 index 0000000000..b16045a103 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/test/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherTestCase.java @@ -0,0 +1,64 @@ +/* + * 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.node.equinox.launcher; + +import org.apache.tuscany.sca.node.SCANode; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +/** + * + */ +public class NodeLauncherTestCase { + private static NodeLauncher launcher; + + @BeforeClass + public static void setUp() { + try { + launcher = NodeLauncher.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @AfterClass + public static void tearDown() { + if (launcher != null) { + launcher.destroy(); + } + + } + + @Test + public void testLaunch() throws Exception { + SCANode node = launcher.createNodeFromClassLoader("HelloWorld.composite", getClass().getClassLoader()); + node.start(); + node.stop(); + } + + @Test + @Ignore("contribution-osgi issue") + public void testLaunchDomain() throws Exception { + DomainManagerLauncher.main(new String[] {}); + } + +} diff --git a/java/sca/contrib/modules/node-launcher-equinox/src/test/resources/HelloWorld.composite b/java/sca/contrib/modules/node-launcher-equinox/src/test/resources/HelloWorld.composite new file mode 100644 index 0000000000..0608e70ca5 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-equinox/src/test/resources/HelloWorld.composite @@ -0,0 +1,34 @@ +<?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.
+-->
+<composite xmlns="http://www.osoa.org/xmlns/sca/1.0"
+ xmlns:tuscany="http://tuscany.apache.org/xmlns/sca/1.0"
+ targetNamespace="http://sample/composite"
+ xmlns:sc="http://sample/composite"
+ name="HelloWorld">
+
+ <component name="HelloWorld">
+ <implementation.java class="hello.HelloWorldImpl" />
+ </component>
+ <component name="HelloWorldClient">
+ <implementation.java class="hello.HelloWorldClient" />
+ <reference name="helloWorld" target="HelloWorld"></reference>
+ </component>
+
+</composite>
|