Run OSGi based on modular distribution
authorMathieu Baudier <mbaudier@argeo.org>
Sat, 3 Jan 2015 11:43:21 +0000 (11:43 +0000)
committerMathieu Baudier <mbaudier@argeo.org>
Sat, 3 Jan 2015 11:43:21 +0000 (11:43 +0000)
git-svn-id: https://svn.argeo.org/slc/trunk@7617 4cfe0d0a-d680-48aa-b62c-e0a02a3f76cc

plugins/org.argeo.slc.client.ui.dist/plugin.xml
plugins/org.argeo.slc.client.ui.dist/src/main/java/org/argeo/slc/client/ui/dist/commands/RunInOsgi.java
plugins/org.argeo.slc.client.ui.dist/src/main/java/org/argeo/slc/client/ui/dist/views/DistributionsView.java

index 19f5ddbb48dba8a3c47c98b07c34e0fe02b730be..6e3f6d531b440bcd1eda2c6102e97c11dd935880 100644 (file)
                        id="workspaceName"
                        name="Workspace Name">
                        </commandParameter>
+            <commandParameter
+                  id="modulePath"
+                  name="Module Path"
+                  optional="true">
+            </commandParameter>
        </command>
        <command
             id="org.argeo.slc.client.ui.dist.refreshDistributionsView"
index 238e819d009c3fbceb2f33393d9b7c58abbaa614..37a89712a1bddfd3236632b6ea4a5afc1ac12e8c 100644 (file)
 package org.argeo.slc.client.ui.dist.commands;
 
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.FileWriter;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.Writer;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.net.URL;
 
 import javax.jcr.Node;
 import javax.jcr.NodeIterator;
-import javax.jcr.Property;
 import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
 import javax.jcr.Session;
-import javax.jcr.query.QueryManager;
-import javax.jcr.query.QueryResult;
-import javax.jcr.query.qom.Ordering;
-import javax.jcr.query.qom.QueryObjectModel;
-import javax.jcr.query.qom.QueryObjectModelFactory;
-import javax.jcr.query.qom.Selector;
 
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.IOUtils;
@@ -49,12 +37,17 @@ import org.argeo.slc.SlcException;
 import org.argeo.slc.client.ui.dist.DistPlugin;
 import org.argeo.slc.core.execution.tasks.JvmProcess;
 import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.slc.repo.maven.MavenConventionsUtils;
 import org.eclipse.core.commands.AbstractHandler;
 import org.eclipse.core.commands.ExecutionEvent;
 import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
 import org.eclipse.jface.resource.ImageDescriptor;
-import org.osgi.framework.Bundle;
+import org.sonatype.aether.artifact.Artifact;
 
 /** <b>UNDER DEVELOPMENT</b>. Download and prepare an OSGi runtime */
 public class RunInOsgi extends AbstractHandler implements SlcNames {
@@ -66,6 +59,7 @@ public class RunInOsgi extends AbstractHandler implements SlcNames {
                        .getImageDescriptor("icons/runInOsgi.gif");
 
        public final static String PARAM_WORKSPACE_NAME = "workspaceName";
+       public final static String PARAM_MODULE_PATH = "modulePath";
 
        /* DEPENDENCY INJECTION */
        private Repository repository;
@@ -73,95 +67,140 @@ public class RunInOsgi extends AbstractHandler implements SlcNames {
        public Object execute(ExecutionEvent event) throws ExecutionException {
 
                String workspace = event.getParameter(PARAM_WORKSPACE_NAME);
+               String modulePath = event.getParameter(PARAM_MODULE_PATH);
+               String port = System.getProperty("argeo.server.port.http");
+               // String localMavenBase = System.getProperty("user.home")
+               // + "/.m2/repository";
 
                InputStream jarStream = null;
                OutputStream out = null;
                Writer writer = null;
                Session session = null;
                try {
-                       // Target directory
-                       Bundle distPluginBundle = DistPlugin.getDefault().getBundle();
-                       File baseDirectory = distPluginBundle.getBundleContext()
-                                       .getDataFile("runInOSGi");
-                       if (baseDirectory.exists())
-                               FileUtils.deleteDirectory(baseDirectory);
-                       File targetDirectory = new File(baseDirectory, "lib");
-                       targetDirectory.mkdirs();
-                       File confDir = new File(baseDirectory, "configuration");
+                       // Bundle distPluginBundle = DistPlugin.getDefault().getBundle();
+                       // File baseDir = distPluginBundle.getBundleContext().getDataFile(
+                       // "runInOSGi");
+                       File baseDir = new File(System.getProperty("java.io.tmpdir")
+                                       + "/runInOSGi-" + System.getProperty("user.name"));
+                       if (baseDir.exists())
+                               FileUtils.deleteDirectory(baseDir);
+                       File libDir = new File(baseDir, "lib");
+                       libDir.mkdirs();
+                       File confDir = new File(baseDir, "configuration");
                        confDir.mkdirs();
-                       File dataDir = new File(baseDirectory, "data");
+                       File dataDir = new File(baseDir, "data");
                        dataDir.mkdirs();
 
                        session = repository.login(workspace);
-                       NodeIterator bundles = listBundleArtifacts(session);
-
-                       if (log.isDebugEnabled())
-                               log.debug("## Copying to " + targetDirectory);
-
-                       File equinoxJar = null;
-                       List<File> files = new ArrayList<File>();
-                       bundles: while (bundles.hasNext()) {
-                               Node bundleNode = bundles.nextNode();
-                               String symbolicName = JcrUtils.get(bundleNode,
-                                               SLC_SYMBOLIC_NAME);
-
-                               // skip sources
-                               if (symbolicName.endsWith(".source"))
-                                       continue bundles;
-                               // skip eclipse
-                               if (symbolicName.startsWith("org.eclipse")
-                                               && !symbolicName.equals("org.eclipse.osgi"))
-                                       continue bundles;
-                               if (symbolicName.equals("org.polymap.openlayers.rap.widget"))
-                                       continue bundles;
-
-                               File targetFile = new File(targetDirectory,
-                                               bundleNode.getName());
-                               out = new FileOutputStream(targetFile);
-                               jarStream = bundleNode.getNode(Node.JCR_CONTENT)
-                                               .getProperty(Property.JCR_DATA).getBinary().getStream();
-                               IOUtils.copy(jarStream, out);
-                               if (symbolicName.equals("org.eclipse.osgi"))
-                                       equinoxJar = targetFile;
-                               else
-                                       files.add(targetFile);
-                               if (log.isDebugEnabled())
-                                       log.debug("Copied " + targetFile.getName());
 
-                               IOUtils.closeQuietly(out);
-                               IOUtils.closeQuietly(jarStream);
-                       }
+                       // NodeIterator bundles = listBundleArtifacts(session);
+                       // if (log.isDebugEnabled())
+                       // log.debug("## Copying to " + libDir);
+                       //
+                       // File equinoxJar = null;
+                       // List<File> files = new ArrayList<File>();
+                       // bundles: while (bundles.hasNext()) {
+                       // Node bundleNode = bundles.nextNode();
+                       // String symbolicName = JcrUtils.get(bundleNode,
+                       // SLC_SYMBOLIC_NAME);
+                       //
+                       // // skip sources
+                       // if (symbolicName.endsWith(".source"))
+                       // continue bundles;
+                       // // skip eclipse
+                       // if (symbolicName.startsWith("org.eclipse")
+                       // && !symbolicName.equals("org.eclipse.osgi"))
+                       // continue bundles;
+                       // if (symbolicName.equals("org.polymap.openlayers.rap.widget"))
+                       // continue bundles;
+                       //
+                       // File targetFile = new File(libDir, bundleNode.getName());
+                       // out = new FileOutputStream(targetFile);
+                       // jarStream = bundleNode.getNode(Node.JCR_CONTENT)
+                       // .getProperty(Property.JCR_DATA).getBinary().getStream();
+                       // IOUtils.copy(jarStream, out);
+                       // if (symbolicName.equals("org.eclipse.osgi"))
+                       // equinoxJar = targetFile;
+                       // else
+                       // files.add(targetFile);
+                       // if (log.isDebugEnabled())
+                       // log.debug("Copied " + targetFile.getName());
+                       //
+                       // IOUtils.closeQuietly(out);
+                       // IOUtils.closeQuietly(jarStream);
+                       // }
+                       //
+                       // StringBuffer osgiBundles = new StringBuffer("osgi.bundles=");
+                       // for (int i = 0; i < files.size(); i++) {
+                       // if (i != 0)
+                       // osgiBundles.append(',');
+                       // osgiBundles.append(files.get(i).getName());
+                       // }
 
-                       StringBuffer osgiBundles = new StringBuffer("osgi.bundles=");
-                       for (int i = 0; i < files.size(); i++) {
-                               if (i != 0)
-                                       osgiBundles.append(',');
-                               osgiBundles.append(files.get(i).getName());
+                       String equinoxJar = null;
+
+                       Node distModule = session.getNode(modulePath);
+                       NodeIterator coordinates = distModule.getNode(SLC_MODULES)
+                                       .getNodes();
+                       StringBuilder conf = new StringBuilder(1024 * 1024);
+                       conf.append("osgi.clean=true\n");
+                       conf.append("osgi.console=7777\n");
+                       conf.append("osgi.console.enable.builtin=true\n");
+
+                       conf.append("osgi.bundles=");
+                       coords: while (coordinates.hasNext()) {
+                               Node coord = coordinates.nextNode();
+                               // String category =
+                               // coord.getProperty(SLC_CATEGORY).getString();
+                               String name = coord.getProperty(SLC_NAME).getString();
+                               String version = coord.getProperty(SLC_VERSION).getString();
+                               Artifact artifact = RepoUtils.asArtifact(coord);
+                               String path = MavenConventionsUtils.artifactPath("", artifact);
+                               String url = "http://localhost:" + port + "/data/public/java/"
+                                               + workspace + path;
+                               if (log.isDebugEnabled())
+                                       log.debug(url);
+                               File f = new File(libDir, name + "-" + version + ".jar");
+                               FileUtils.copyURLToFile(new URL(url), f);
+                               if (name.equals("org.eclipse.osgi")) {
+                                       // File f = new File(localMavenBase + path);
+                                       // if (!f.exists())
+                                       // FileUtils.copyURLToFile(new URL(url), f);
+                                       equinoxJar = f.getCanonicalPath();
+                                       continue coords;
+                               }
+                               conf.append(f.getName());
+                               if (coordinates.hasNext())
+                                       conf.append(",\\\n");
                        }
 
                        File confIni = new File(confDir, "config.ini");
                        writer = new FileWriter(confIni);
-                       writer.write(osgiBundles.toString());
+                       writer.write(conf.toString());
                        IOUtils.closeQuietly(writer);
 
-                       Map<String, String> configuration = new HashMap<String, String>();
-                       configuration.put("osgi.configuration.area",
-                                       confDir.getCanonicalPath());
-                       configuration.put("osgi.instance.area", dataDir.getCanonicalPath());
-                       // Do clean
-                       configuration.put("osgi.clean", "true");
+                       // Map<String, String> configuration = new HashMap<String,
+                       // String>();
+                       // configuration.put("osgi.configuration.area",
+                       // confDir.getCanonicalPath());
+                       // configuration.put("osgi.instance.area",
+                       // dataDir.getCanonicalPath());
+                       // // Do clean
+                       // configuration.put("osgi.clean", "true");
 
                        JvmProcess osgiRuntime = new JvmProcess();
-                       osgiRuntime.setExecDir(baseDirectory.getCanonicalPath());
+                       osgiRuntime.setExecDir(baseDir.getCanonicalPath());
                        if (equinoxJar == null)
                                throw new SlcException("Cannot find OSGi runtime.");
-                       osgiRuntime.setMainJar(equinoxJar.getCanonicalPath());
-                       osgiRuntime.arg("-configuration", confDir.getCanonicalPath())
-                                       .arg("-data", dataDir.getCanonicalPath())
-                                       .arg("-console", "7777").arg("-clean");
+                       osgiRuntime.setMainJar(equinoxJar);
+                       osgiRuntime.arg("-configuration", confDir.getCanonicalPath()).arg(
+                                       "-data", dataDir.getCanonicalPath());
+                       // .arg("-console", "7777").arg("-clean");
                        osgiRuntime.setLogCommand(true);
                        osgiRuntime.afterPropertiesSet();
-                       osgiRuntime.run();
+                       Job job = new RunInOsgiJob(osgiRuntime);
+                       job.schedule();
+                       // osgiRuntime.run();
 
                        // Map<String, String> configuration = new HashMap<String,
                        // String>();
@@ -203,24 +242,56 @@ public class RunInOsgi extends AbstractHandler implements SlcNames {
                return null;
        }
 
-       static NodeIterator listBundleArtifacts(Session session)
-                       throws RepositoryException {
-               QueryManager queryManager = session.getWorkspace().getQueryManager();
-               QueryObjectModelFactory factory = queryManager.getQOMFactory();
+       // private NodeIterator listBundleArtifacts(Session session)
+       // throws RepositoryException {
+
+       // QueryManager queryManager = session.getWorkspace().getQueryManager();
+       // QueryObjectModelFactory factory = queryManager.getQOMFactory();
+       //
+       // final String bundleArtifactsSelector = "bundleArtifacts";
+       // Selector source = factory.selector(SlcTypes.SLC_BUNDLE_ARTIFACT,
+       // bundleArtifactsSelector);
+       //
+       // Ordering order = factory.ascending(factory.propertyValue(
+       // bundleArtifactsSelector, SlcNames.SLC_SYMBOLIC_NAME));
+       // Ordering[] orderings = { order };
+       //
+       // QueryObjectModel query = factory.createQuery(source, null, orderings,
+       // null);
+       //
+       // QueryResult result = query.execute();
+       // return result.getNodes();
+       // }
 
-               final String bundleArtifactsSelector = "bundleArtifacts";
-               Selector source = factory.selector(SlcTypes.SLC_BUNDLE_ARTIFACT,
-                               bundleArtifactsSelector);
+       private class RunInOsgiJob extends Job {
+               final JvmProcess osgiRuntime;
 
-               Ordering order = factory.ascending(factory.propertyValue(
-                               bundleArtifactsSelector, SlcNames.SLC_SYMBOLIC_NAME));
-               Ordering[] orderings = { order };
+               public RunInOsgiJob(JvmProcess osgiRuntime) {
+                       super("OSGi Test");
+                       this.osgiRuntime = osgiRuntime;
+               }
 
-               QueryObjectModel query = factory.createQuery(source, null, orderings,
-                               null);
+               @Override
+               protected IStatus run(IProgressMonitor monitor) {
+                       osgiRuntime.setSynchronous(false);
+                       osgiRuntime.run();
+                       while (!monitor.isCanceled()) {
+                               try {
+                                       Thread.sleep(500);
+                               } catch (InterruptedException e) {
+                                       // silent
+                               }
+
+                               if (monitor.isCanceled()) {
+                                       osgiRuntime.kill();
+                                       return Status.CANCEL_STATUS;
+                               }
+                               if (!osgiRuntime.isRunning())
+                                       break;
+                       }
+                       return Status.OK_STATUS;
+               }
 
-               QueryResult result = query.execute();
-               return result.getNodes();
        }
 
        public void setRepository(Repository repository) {
index 677bed994e0036b8962a03ad30c08eb54ffbdecf..37bd1f246f515438ac6b5f853acddb0417f4e6d1 100644 (file)
@@ -47,6 +47,7 @@ import org.argeo.slc.client.ui.dist.controllers.DistTreeDoubleClickListener;
 import org.argeo.slc.client.ui.dist.controllers.DistTreeLabelProvider;
 import org.argeo.slc.client.ui.dist.model.DistParentElem;
 import org.argeo.slc.client.ui.dist.model.ModularDistVersionBaseElem;
+import org.argeo.slc.client.ui.dist.model.ModularDistVersionElem;
 import org.argeo.slc.client.ui.dist.model.RepoElem;
 import org.argeo.slc.client.ui.dist.model.WkspGroupElem;
 import org.argeo.slc.client.ui.dist.model.WorkspaceElem;
@@ -143,6 +144,7 @@ public class DistributionsView extends ViewPart implements SlcNames, ArgeoNames
 
                                String targetRepoPath = null, workspaceName = null, workspacePrefix = null;
                                String modularDistBasePath = null;
+                               String modularDistPath = null;
                                // String targetRepoUri = null;
                                // Build conditions depending on element type
                                boolean isDistribElem = false, isModularDistVersionBaseElem = false, isRepoElem = false, isDistribGroupElem = false;
@@ -176,6 +178,14 @@ public class DistributionsView extends ViewPart implements SlcNames, ArgeoNames
                                        isReadOnly = re.isReadOnly();
                                        workspaceName = mdbe.getWkspElem().getWorkspaceName();
                                        modularDistBasePath = mdbe.getModularDistBase().getPath();
+                               } else if (firstElement instanceof ModularDistVersionElem) {
+                                       ModularDistVersionElem mdbe = (ModularDistVersionElem) firstElement;
+                                       re = mdbe.getWorkspaceElem().getRepoElem();
+                                       isLocal = re.inHome();
+                                       isReadOnly = re.isReadOnly();
+                                       workspaceName = mdbe.getWorkspaceElem().getWorkspaceName();
+                                       modularDistPath = mdbe.getModularDistVersionNode()
+                                                       .getPath();
                                }
 
                                if (re != null) {
@@ -309,11 +319,12 @@ public class DistributionsView extends ViewPart implements SlcNames, ArgeoNames
 
                                // Run in OSGi
                                params = new HashMap<String, String>();
+                               params.put(RunInOsgi.PARAM_MODULE_PATH, modularDistPath);
                                params.put(RunInOsgi.PARAM_WORKSPACE_NAME, workspaceName);
                                CommandUtils.refreshParametrizedCommand(submenu, window,
                                                RunInOsgi.ID, RunInOsgi.DEFAULT_LABEL,
-                                               RunInOsgi.DEFAULT_ICON, isDistribElem && singleElement
-                                                               && isLocal, params);
+                                               RunInOsgi.DEFAULT_ICON, modularDistPath!=null
+                                                               && singleElement && isLocal, params);
 
                                // Open generate binaries
                                params = new HashMap<String, String>();