diff options
Diffstat (limited to 'sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main')
13 files changed, 2068 insertions, 0 deletions
diff --git a/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/Contribution.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/DomainManagerLauncher.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHookConfigurator.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHost.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxLauncherBundleHelper.java b/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxLauncherBundleHelper.java new file mode 100644 index 0000000000..90d682a74b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxLauncherBundleHelper.java @@ -0,0 +1,123 @@ +/* + * 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.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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/JarFileFinder.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/LauncherException.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/LibrariesBundleFileFactoryHook.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeDaemonLauncher.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncher.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherUtil.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeMain.java b/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/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/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/resources/hookconfigurators.properties b/sca-java-1.x/branches/sca-java-1.4/modules/node-launcher-equinox/src/main/resources/hookconfigurators.properties new file mode 100644 index 0000000000..cf9c0f74df --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.4/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 |