@SuppressWarnings("unchecked")
  private <T> T getService(Class<T> serviceType, String filter, long timeout)
      throws TestContainerException {
    assert m_framework != null : "Framework should be up";
    assert serviceType != null : "serviceType not be null";

    final Long start = System.currentTimeMillis();

    LOG.info("Aquiring Service " + serviceType.getName() + " " + (filter != null ? filter : ""));

    do {
      try {
        ServiceReference[] reference =
            m_framework.getBundleContext().getServiceReferences(serviceType.getName(), filter);
        if (reference != null && reference.length > 0) {
          return ((T) m_framework.getBundleContext().getService(reference[0]));
        }

        Thread.sleep(200);
      } catch (Exception e) {
        LOG.error("Some problem during looking up service from framework: " + m_framework, e);
      }
      // wait a bit
    } while ((System.currentTimeMillis()) < start + timeout);
    printAvailableAlternatives(serviceType);

    throw new TestContainerException(
        "Not found a matching Service "
            + serviceType.getName()
            + " for Filter:"
            + (filter != null ? filter : ""));
  }
Beispiel #2
0
  public static void main(String[] args) {

    try {

      ServiceLoader<FrameworkFactory> loader = ServiceLoader.load(FrameworkFactory.class);

      FrameworkFactory factory = loader.iterator().next();

      Map<String, Object> config = new HashMap<String, Object>();

      config.put(Constants.FRAMEWORK_STORAGE, "./target/storage");

      Framework framework = factory.newFramework(config);

      framework.start();

      BundleContext context = framework.getBundleContext();

      Bundle bundle =
          context.installBundle("http://www.eclipsezone.com/files/jsig/bundles/HelloWorld.jar");

      bundle.start();

      framework.waitForStop(0);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Test
  public void testNativeCodeExecPermission() throws Exception {
    String tempFileName =
        System.getProperty("java.io.tmpdir")
            + "/osgi_native"
            + System.currentTimeMillis()
            + ".test";
    File tempFile = new File(tempFileName);

    try {
      Map<String, String> props = new HashMap<String, String>();
      props.put("org.osgi.framework.storage", "target/osgi-store");
      props.put("org.osgi.framework.storage.clean", "onFirstInit");

      // Execute this command for every native library found in the bundle
      props.put("org.osgi.framework.command.execpermission", "cp ${abspath} " + tempFileName);

      FrameworkFactory factory = ServiceLoader.loadService(FrameworkFactory.class);
      Framework framework = factory.newFramework(props);
      framework.start();

      assertFalse("Precondition", tempFile.exists());
      Bundle bundle =
          framework.getBundleContext().installBundle(getTestArchivePath("simple-nativecode.jar"));
      bundle.start();
      assertTrue(tempFile.exists());

      framework.stop();
      framework.waitForStop(2000);
    } finally {
      tempFile.delete();
    }
  }
  @Override
  protected void setUp() throws Exception {
    tmp = IO.getFile("generated/tmp");
    tmp.mkdirs();

    configuration = new HashMap<String, Object>();
    configuration.put(
        Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    configuration.put(Constants.FRAMEWORK_STORAGE, new File(tmp, "fwstorage").getAbsolutePath());
    configuration.put(
        Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.4");
    framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration);
    framework.init();
    framework.start();
    BundleContext context = framework.getBundleContext();

    String[] bundles = {
      "../cnf/repo/osgi.cmpn/osgi.cmpn-4.3.1.jar", "testdata/slf4j-simple-1.7.12.jar",
      "testdata/slf4j-api-1.7.12.jar", "testdata/org.apache.aries.util-1.1.0.jar",
      "testdata/org.apache.aries.jmx-1.1.1.jar", "generated/biz.aQute.remote.test.jmx.jar"
    };

    for (String bundle : bundles) {
      String location = "reference:" + IO.getFile(bundle).toURI().toString();
      Bundle b = context.installBundle(location);
      if (!bundle.contains("slf4j-simple")) {
        b.start();
      }
    }

    super.setUp();
  }
Beispiel #5
0
 public synchronized void serviceChanged(ServiceEvent event) {
   if (event.getType() == ServiceEvent.REGISTERED) {
     mainThread =
         (Runnable) systemBundle.getBundleContext().getService(event.getServiceReference());
     notifyAll();
   }
 }
  /** Start the OSGI framework. */
  public void start() throws FrameworkStartFailedException {
    FrameworkFactory frameworkFactory = null; // org.eclipse.osgi.launch.EquinoxFactory

    try {
      frameworkFactory = java.util.ServiceLoader.load(FrameworkFactory.class).iterator().next();
    } catch (Exception ex) {
      LOG.error("Failed to load osgi framework class.", ex);
      // failed to load FrameworkFactory class
      throw new FrameworkStartFailedException("Can't load class FrameworkFactory.", ex);
    }

    framework = frameworkFactory.newFramework(prepareSettings());
    context = null;
    try {
      // start OSGi container ..
      framework.start();
    } catch (org.osgi.framework.BundleException ex) {
      LOG.error("Failed to start OSGI framework.", ex);
      // failed to start/initiate framework
      throw new FrameworkStartFailedException("Failed to start OSGi framework.", ex);
    }

    try {
      context = framework.getBundleContext();
    } catch (SecurityException ex) {
      LOG.error("Failed to get osgi context.", ex);
      // we have to stop framework ..
      stop();
      throw new FrameworkStartFailedException("Failed to get OSGi context.", ex);
    }

    // load resources
    startUpLoad();
  }
  public static void indexTargetPlatform(
      OutputStream outputStream,
      List<File> additionalJarFiles,
      long stopWaitTimeout,
      String... dirNames)
      throws Exception {

    Framework framework = null;

    Path tempPath = Files.createTempDirectory(null);

    ClassLoader classLoader = TargetPlatformIndexerUtil.class.getClassLoader();

    try (InputStream inputStream =
        classLoader.getResourceAsStream("META-INF/system.packages.extra.mf")) {

      Map<String, String> properties = new HashMap<>();

      properties.put(Constants.FRAMEWORK_STORAGE, tempPath.toString());

      Manifest extraPackagesManifest = new Manifest(inputStream);

      Attributes attributes = extraPackagesManifest.getMainAttributes();

      properties.put(
          Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, attributes.getValue("Export-Package"));

      ServiceLoader<FrameworkFactory> serviceLoader = ServiceLoader.load(FrameworkFactory.class);

      FrameworkFactory frameworkFactory = serviceLoader.iterator().next();

      framework = frameworkFactory.newFramework(properties);

      framework.init();

      BundleContext bundleContext = framework.getBundleContext();

      Bundle systemBundle = bundleContext.getBundle(0);

      TargetPlatformIndexer targetPlatformIndexer =
          new TargetPlatformIndexer(systemBundle, additionalJarFiles, dirNames);

      targetPlatformIndexer.index(outputStream);
    } finally {
      framework.stop();

      FrameworkEvent frameworkEvent = framework.waitForStop(stopWaitTimeout);

      if (frameworkEvent.getType() == FrameworkEvent.WAIT_TIMEDOUT) {
        throw new Exception(
            "OSGi framework event "
                + frameworkEvent
                + " triggered after a "
                + stopWaitTimeout
                + "ms timeout");
      }

      PathUtil.deltree(tempPath);
    }
  }
Beispiel #8
0
  @Override
  protected void setUp() throws Exception {
    tmp = IO.getFile("generated/tmp");
    tmp.mkdirs();
    IO.copy(IO.getFile("testdata/ws"), tmp);
    workspace = Workspace.getWorkspace(tmp);
    workspace.refresh();

    InfoRepository repo = workspace.getPlugin(InfoRepository.class);
    t1 = create("bsn-1", new Version(1, 0, 0));
    t2 = create("bsn-2", new Version(1, 0, 0));

    repo.put(new FileInputStream(t1), null);
    repo.put(new FileInputStream(t2), null);
    t1 = repo.get("bsn-1", new Version(1, 0, 0), null);
    t2 = repo.get("bsn-2", new Version(1, 0, 0), null);
    repo.put(new FileInputStream(IO.getFile("generated/biz.aQute.remote.launcher.jar")), null);

    workspace.getPlugins().add(repo);

    File storage = IO.getFile("generated/storage-1");
    storage.mkdirs();

    configuration = new HashMap<String, Object>();
    configuration.put(
        Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    configuration.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath());

    configuration.put(
        Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.2");

    framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration);
    framework.init();
    framework.start();
    context = framework.getBundleContext();
    location = "reference:" + IO.getFile("generated/biz.aQute.remote.agent.jar").toURI().toString();
    agent = context.installBundle(location);
    agent.start();

    thread =
        new Thread() {
          @Override
          public void run() {
            try {
              Main.main(
                  new String[] {
                    "-s", "generated/storage", "-c", "generated/cache", "-p", "1090", "-et"
                  });
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    thread.setDaemon(true);
    thread.start();

    super.setUp();
  }
Beispiel #9
0
  public int activate() throws Exception {
    Policy.setPolicy(new AllPolicy());

    systemBundle = createFramework();
    if (systemBundle == null) return LauncherConstants.ERROR;

    doTimeoutHandler();

    // Initialize this framework so it becomes STARTING
    systemBundle.start();
    trace("system bundle started ok");

    BundleContext systemContext = systemBundle.getBundleContext();
    ServiceReference ref = systemContext.getServiceReference(PackageAdmin.class.getName());
    if (ref != null) {
      padmin = (PackageAdmin) systemContext.getService(ref);
    } else trace("could not get package admin");

    systemContext.addServiceListener(this, "(&(objectclass=java.lang.Runnable)(main.thread=true))");

    update();

    if (parms.trace) {
      report(out);
    }

    // Start embedded activators
    trace("start embedded activators");
    if (parms.activators != null) {
      ClassLoader loader = getClass().getClassLoader();
      for (Object token : parms.activators) {
        try {
          Class<?> clazz = loader.loadClass((String) token);
          BundleActivator activator = (BundleActivator) clazz.newInstance();
          embedded.add(activator);
          trace("adding activator %s", activator);
        } catch (Exception e) {
          throw new IllegalArgumentException(
              "Embedded Bundle Activator incorrect: " + token + ", " + e);
        }
      }
    }
    int result = LauncherConstants.OK;
    for (BundleActivator activator : embedded)
      try {
        trace("starting activator %s", activator);
        activator.start(systemContext);
      } catch (Exception e) {
        error("Starting activator %s : %s", activator, e);
        result = LauncherConstants.ERROR;
      }

    return result;
  }
 public synchronized void cleanup() {
   while ((!m_installed.isEmpty())) {
     try {
       Long id = m_installed.pop();
       Bundle bundle = m_framework.getBundleContext().getBundle(id);
       bundle.uninstall();
       LOG.debug("Uninstalled bundle " + id);
     } catch (BundleException e) {
       e.printStackTrace();
     }
   }
 }
Beispiel #11
0
  public void report(PrintStream out) {
    try {
      out.println("------------------------------- REPORT --------------------------");
      out.println();
      row(out, "Framework", systemBundle == null ? "<>" : systemBundle.getClass());
      row(out, "Framework type", parms.services ? "META-INF/services" : "mini framework");
      row(out, "Storage", parms.storageDir);
      row(out, "Keep", parms.keep);
      row(out, "Security", security);
      list(out, fill("Run bundles", 40), parms.runbundles);
      list(
          out,
          fill("Classpath", 40),
          split(System.getProperty("java.class.path"), File.pathSeparator));
      list(out, fill("System Packages", 40), split(parms.systemPackages, ","));
      row(out, "Properties");
      for (java.util.Map.Entry<Object, Object> entry : properties.entrySet()) {
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();
        row(out, key, value);
      }
      if (systemBundle != null) {
        BundleContext context = systemBundle.getBundleContext();
        if (context != null) {
          Bundle bundles[] = context.getBundles();
          out.println();
          out.println("Id    State Modified      Location");

          for (int i = 0; i < bundles.length; i++) {
            String loc = bundles[i].getLocation();
            loc = loc.replaceAll("\\w+:", "");
            File f = new File(loc);
            out.print(fill(Long.toString(bundles[i].getBundleId()), 6));
            out.print(fill(toState(bundles[i].getState()), 6));
            if (f.exists()) out.print(fill(toDate(f.lastModified()), 14));
            else out.print(fill("<>", 14));

            if (errors.containsKey(bundles[i])) {
              out.print(fill(loc, 50));
              out.print(errors.get(bundles[i]).getMessage());
            } else out.print(bundles[i].getLocation());

            out.println();
          }
        }
      }
    } catch (Throwable t) {
      error("Sorry, can't print framework: %s", t);
    }
  }
 public synchronized long install(InputStream stream) {
   try {
     Bundle b = m_framework.getBundleContext().installBundle("local", stream);
     m_installed.push(b.getBundleId());
     LOG.debug("Installed bundle " + b.getSymbolicName() + " as Bundle ID " + b.getBundleId());
     setBundleStartLevel(b.getBundleId(), Constants.START_LEVEL_TEST_BUNDLE);
     // stream.close();
     b.start();
     return b.getBundleId();
   } catch (BundleException e) {
     e.printStackTrace();
   }
   return -1;
 }
Beispiel #13
0
 public static void main(final String[] args) {
   System.out.println("\nWelcome to AspGen");
   System.out.println("======================\n");
   final Map<String, String> config = setupConfiguration(args);
   try {
     mFwk = getFrameworkFactory().newFramework(config);
     mFwk.init();
     AutoProcessor.process(config, mFwk.getBundleContext());
     mFwk.start();
     mFwk.waitForStop(0);
   } catch (final IOException | BundleException | InterruptedException e) {
     e.printStackTrace();
     throw new RuntimeException("Error");
   }
   System.exit(0);
 }
  private <T> void printAvailableAlternatives(Class<T> serviceType) {
    try {
      ServiceReference[] reference =
          m_framework.getBundleContext().getAllServiceReferences(serviceType.getName(), null);
      if (reference != null) {
        LOG.warn("Test Endpoints: " + reference.length);

        for (ServiceReference ref : reference) {
          LOG.warn("Endpoint: " + ref);
        }
      }

    } catch (Exception e) {
      LOG.error("Some problem during looking up alternative service. ", e);
    }
  }
Beispiel #15
0
    private Bundle startBundle(URI bundleURI) {
      NavigableMap<URI, Bundle> expect, update;
      Bundle bundle = null;
      do {
        expect = get();
        if (expect.containsKey(bundleURI)) break;

        BundleContext ctx = m_framework.getBundleContext();
        bundle = ctx.getBundle(bundleURI.toASCIIString());
        if (bundle != null) {
          try {
            bundle.update();
          } catch (BundleException e) {
            String msg = e.getMessage();
            throw loggedModularException(e, "Unable to update bundle %s. %s", bundleURI, msg);
          } catch (Throwable t) {
            throw loggedModularException(t, "Unable to update bundle %s", bundleURI);
          }
        } else {
          try {
            bundle = ctx.installBundle(bundleURI.toASCIIString());
          } catch (BundleException e) {
            String msg = e.getMessage();
            throw loggedModularException(e, "Unable to install bundle %s. %s", bundleURI, msg);
          } catch (Throwable t) {
            throw loggedModularException(t, "Unable to instal bundle %s", bundleURI);
          }
        }
        try {
          bundle.start();
        } catch (BundleException e) {
          String msg = e.getMessage();
          throw loggedModularException(e, "Unable to start bundle %s. %s", bundleURI, msg);
        } catch (Throwable t) {
          throw loggedModularException(t, "Unable to start bundle %s", bundleURI);
        }

        update =
            ImmutableSortedMap.<URI, Bundle>naturalOrder()
                .putAll(expect)
                .put(bundleURI, bundle)
                .build();
      } while (!compareAndSet(expect, update));

      return get().get(bundleURI);
    }
  public TestContainer start() throws TestContainerException {
    ClassLoader parent = null;
    try {
      final Map<String, String> p = new HashMap<String, String>(m_properties);
      String folder = p.get("org.osgi.framework.storage");
      if (folder == null) {
        folder = System.getProperty("org.osgi.framework.storage");
      }
      if (folder == null) {
        // folder = System.getProperty( "user.home" ) + File.separator + "osgi";
        folder = getCache();
      }
      LOG.debug("Cache folder set to " + folder);
      FileUtils.delete(new File(folder));
      // load default stuff

      p.put("org.osgi.framework.storage", folder);
      //  System.setProperty( "org.osgi.vendor.framework", "org.ops4j.pax.exam" );

      p.put(
          "org.osgi.framework.system.packages.extra",
          "org.ops4j.pax.exam;version=" + skipSnapshotFlag(Info.getPaxExamVersion()));

      parent = Thread.currentThread().getContextClassLoader();
      // Thread.currentThread().setContextClassLoader( null );

      m_framework = m_frameworkFactory.newFramework(p);
      m_framework.init();

      installAndStartBundles(m_framework.getBundleContext());

      Thread.currentThread().setContextClassLoader(parent);

    } catch (Exception e) {
      throw new TestContainerException("Problem starting test container.", e);
    } finally {
      if (parent != null) {
        Thread.currentThread().setContextClassLoader(parent);
      }
    }
    return this;
  }
Beispiel #17
0
 Bundle install(File f) throws Exception {
   BundleContext context = systemBundle.getBundleContext();
   try {
     trace("will install %s with reference", f.getAbsolutePath());
     String reference = "reference:" + f.toURI().toURL().toExternalForm();
     Bundle b = context.installBundle(reference);
     if (b.getLastModified() < f.lastModified()) {
       b.update();
     }
     return b;
   } catch (BundleException e) {
     trace("failed reference, will try to install %s with input stream", f.getAbsolutePath());
     String reference = f.toURI().toURL().toExternalForm();
     InputStream in = new FileInputStream(f);
     try {
       return context.installBundle(reference, in);
     } finally {
       in.close();
     }
   }
 }
Beispiel #18
0
  private void run(String args[]) throws Throwable {
    try {
      int status = activate();
      if (status != 0) {
        report(out);
        System.exit(status);
      }

      trace("framework=" + systemBundle);

      // Register the command line with ourselves as the
      // service.
      if (parms.services) { // Does not work for our dummy framework
        Hashtable<String, Object> argprops = new Hashtable<String, Object>();
        argprops.put(LauncherConstants.LAUNCHER_ARGUMENTS, args);
        argprops.put(LauncherConstants.LAUNCHER_READY, "true");
        systemBundle.getBundleContext().registerService(Launcher.class.getName(), this, argprops);
        trace("registered launcher with arguments for syncing");
      }

      // Wait until a Runnable is registered with main.thread=true.
      // not that this will never happen when we're running on the mini fw
      // but the test case normally exits.
      synchronized (this) {
        while (mainThread == null) {
          trace("will wait for a registered Runnable");
          wait();
        }
      }
      trace("Will run %s as main thread", mainThread);
      mainThread.run();
    } catch (Throwable e) {
      error("Unexpected error in the run body: %s", e);
      throw e;
    } finally {
      systemBundle.stop();
      trace("stopped system bundle due to leaving run body");
    }
  }
  @Override
  public void afterPropertiesSet() throws Exception {
    if (!configuration.containsKey(Constants.FRAMEWORK_STORAGE)) {
      File storageDir =
          Bootstrap.getHmpHomeDirectory(this.applicationContext)
              .createRelative("osgi-storage")
              .getFile();
      if (!storageDir.exists()) {
        storageDir.mkdir();
      }
      configuration.put(Constants.FRAMEWORK_STORAGE, storageDir.getCanonicalPath());
    }
    if (!configuration.containsKey(Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT)) {
      configuration.put(
          Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    }
    if (!configuration.containsKey(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA)) {
      InputStreamReader isr =
          new InputStreamReader(getClass().getResourceAsStream(SYSTEM_PACKAGES_RESOURCE));
      String rawSystemPackages = FileCopyUtils.copyToString(isr);
      String[] lines = rawSystemPackages.split("\\r?\\n");
      String systemPackages = StringUtils.collectionToCommaDelimitedString(Arrays.asList(lines));
      configuration.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, systemPackages);
      LOGGER.debug(systemPackages);
      isr.close();
    }
    if (!configuration.containsKey("felix.fileinstall.dir")) {
      File pluginsDir = getPluginsDir(this.applicationContext).getFile();
      if (!pluginsDir.exists()) {
        pluginsDir.mkdir();
      }
      configuration.put("felix.fileinstall.dir", pluginsDir.getCanonicalPath());
    }

    ServiceLoader<FrameworkFactory> factoryLoader = ServiceLoader.load(FrameworkFactory.class);
    FrameworkFactory frameworkFactory = factoryLoader.iterator().next();

    framework = frameworkFactory.newFramework(configuration);
    framework.start();

    // install some bundles
    List<Bundle> installedBundles = new ArrayList<Bundle>();
    File bundlesDir =
        Bootstrap.getHmpHomeDirectory(this.applicationContext).createRelative("bundles").getFile();
    if (!bundlesDir.exists())
      throw new ServiceConfigurationError(
          "HMP OSGi system bundles missing or configured incorrectly (cannot find 'bundles' folder inside '"
              + Bootstrap.getHmpHomeDirectory(this.applicationContext).getFile().getAbsolutePath());
    for (File f : bundlesDir.listFiles()) {
      if (f.getName().endsWith("jar")) {
        try {
          Bundle bundle =
              framework.getBundleContext().installBundle("file:" + f.getCanonicalPath());
          installedBundles.add(bundle);
        } catch (BundleException e) {
          LOGGER.error("Unable to install bundle: " + f.getName(), e);
        }
      }
    }

    // start the installed bundles
    for (Bundle bundle : installedBundles) {
      if (bundle.getHeaders().get(Constants.FRAGMENT_HOST) == null) {
        try {
          bundle.start();
          LOGGER.info(
              "Started bundle: {}({})", bundle.getSymbolicName(), bundle.getVersion().toString());
        } catch (BundleException e) {
          LOGGER.error("Unable to start bundle: " + bundle.getSymbolicName(), e);
        }
      }
    }
  }
Beispiel #20
0
  /**
   * This method performs the main task of constructing an framework instance and starting its
   * execution. The following functions are performed when invoked:
   *
   * <ol>
   *   <li><i><b>Examine and verify command-line arguments.</b></i> The launcher accepts a
   *       "<tt>-b</tt>" command line switch to set the bundle auto-deploy directory and a single
   *       argument to set the bundle cache directory.
   *   <li><i><b>Read the system properties file.</b></i> This is a file containing properties to be
   *       pushed into <tt>System.setProperty()</tt> before starting the framework. This mechanism
   *       is mainly shorthand for people starting the framework from the command line to avoid
   *       having to specify a bunch of <tt>-D</tt> system property definitions. The only properties
   *       defined in this file that will impact the framework's behavior are the those concerning
   *       setting HTTP proxies, such as <tt>http.proxyHost</tt>, <tt>http.proxyPort</tt>, and
   *       <tt>http.proxyAuth</tt>. Generally speaking, the framework does not use system properties
   *       at all.
   *   <li><i><b>Read the framework's configuration property file.</b></i> This is a file containing
   *       properties used to configure the framework instance and to pass configuration information
   *       into bundles installed into the framework instance. The configuration property file is
   *       called <tt>config.properties</tt> by default and is located in the <tt>conf/</tt>
   *       directory of the Felix installation directory, which is the parent directory of the
   *       directory containing the <tt>felix.jar</tt> file. It is possible to use a different
   *       location for the property file by specifying the desired URL using the
   *       <tt>felix.config.properties</tt> system property; this should be set using the
   *       <tt>-D</tt> syntax when executing the JVM. If the <tt>config.properties</tt> file cannot
   *       be found, then default values are used for all configuration properties. Refer to the <a
   *       href="Felix.html#Felix(java.util.Map)"><tt>Felix</tt></a> constructor documentation for
   *       more information on framework configuration properties.
   *   <li><i><b>Copy configuration properties specified as system properties into the set of
   *       configuration properties.</b></i> Even though the Felix framework does not consult system
   *       properties for configuration information, sometimes it is convenient to specify them on
   *       the command line when launching Felix. To make this possible, the Felix launcher copies
   *       any configuration properties specified as system properties into the set of configuration
   *       properties passed into Felix.
   *   <li><i><b>Add shutdown hook.</b></i> To make sure the framework shutdowns cleanly, the
   *       launcher installs a shutdown hook; this can be disabled with the
   *       <tt>felix.shutdown.hook</tt> configuration property.
   *   <li><i><b>Create and initialize a framework instance.</b></i> The OSGi standard
   *       <tt>FrameworkFactory</tt> is retrieved from <tt>META-INF/services</tt> and used to create
   *       a framework instance with the configuration properties.
   *   <li><i><b>Auto-deploy bundles.</b></i> All bundles in the auto-deploy directory are deployed
   *       into the framework instance.
   *   <li><i><b>Start the framework.</b></i> The framework is started and the launcher thread waits
   *       for the framework to shutdown.
   * </ol>
   *
   * <p>It should be noted that simply starting an instance of the framework is not enough to create
   * an interactive session with it. It is necessary to install and start bundles that provide a
   * some means to interact with the framework; this is generally done by bundles in the auto-deploy
   * directory or specifying an "auto-start" property in the configuration property file. If no
   * bundles providing a means to interact with the framework are installed or if the configuration
   * property file cannot be found, the framework will appear to be hung or deadlocked. This is not
   * the case, it is executing correctly, there is just no way to interact with it.
   *
   * <p>The launcher provides two ways to deploy bundles into a framework at startup, which have
   * associated configuration properties:
   *
   * <ul>
   *   <li>Bundle auto-deploy - Automatically deploys all bundles from a specified directory,
   *       controlled by the following configuration properties:
   *       <ul>
   *         <li><tt>felix.auto.deploy.dir</tt> - Specifies the auto-deploy directory from which
   *             bundles are automatically deploy at framework startup. The default is the
   *             <tt>bundle/</tt> directory of the current directory.
   *         <li><tt>felix.auto.deploy.action</tt> - Specifies the auto-deploy actions to be found
   *             on bundle JAR files found in the auto-deploy directory. The possible actions are
   *             <tt>install</tt>, <tt>update</tt>, <tt>start</tt>, and <tt>uninstall</tt>. If no
   *             actions are specified, then the auto-deploy directory is not processed. There is no
   *             default value for this property.
   *       </ul>
   *   <li>Bundle auto-properties - Configuration properties which specify URLs to bundles to
   *       install/start:
   *       <ul>
   *         <li><tt>felix.auto.install.N</tt> - Space-delimited list of bundle URLs to
   *             automatically install when the framework is started, where <tt>N</tt> is the start
   *             level into which the bundle will be installed (e.g., felix.auto.install.2).
   *         <li><tt>felix.auto.start.N</tt> - Space-delimited list of bundle URLs to automatically
   *             install and start when the framework is started, where <tt>N</tt> is the start
   *             level into which the bundle will be installed (e.g., felix.auto.start.2).
   *       </ul>
   * </ul>
   *
   * <p>These properties should be specified in the <tt>config.properties</tt> so that they can be
   * processed by the launcher during the framework startup process.
   *
   * @param args Accepts arguments to set the auto-deploy directory and/or the bundle cache
   *     directory.
   * @throws Exception If an error occurs.
   */
  public static void main(String[] args) throws Exception {
    // Look for bundle directory and/or cache directory.
    // We support at most one argument, which is the bundle
    // cache directory.
    String bundleDir = null;
    String cacheDir = null;
    boolean expectBundleDir = false;
    for (int i = 0; i < args.length; i++) {
      if (args[i].equals(BUNDLE_DIR_SWITCH)) {
        expectBundleDir = true;
      } else if (expectBundleDir) {
        bundleDir = args[i];
        expectBundleDir = false;
      } else {
        cacheDir = args[i];
      }
    }

    if ((args.length > 3) || (expectBundleDir && bundleDir == null)) {
      System.out.println("Usage: [-b <bundle-deploy-dir>] [<bundle-cache-dir>]");
      System.exit(0);
    }

    // Load system properties.
    Main.loadSystemProperties();

    // Read configuration properties.
    Properties configProps = Main.loadConfigProperties();
    // If no configuration properties were found, then create
    // an empty properties object.
    if (configProps == null) {
      System.err.println("No " + CONFIG_PROPERTIES_FILE_VALUE + " found.");
      configProps = new Properties();
    }

    // Copy framework properties from the system properties.
    Main.copySystemProperties(configProps);

    // If there is a passed in bundle auto-deploy directory, then
    // that overwrites anything in the config file.
    if (bundleDir != null) {
      configProps.setProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, bundleDir);
    }

    // If there is a passed in bundle cache directory, then
    // that overwrites anything in the config file.
    if (cacheDir != null) {
      configProps.setProperty(Constants.FRAMEWORK_STORAGE, cacheDir);
    }

    // If enabled, register a shutdown hook to make sure the framework is
    // cleanly shutdown when the VM exits.
    String enableHook = configProps.getProperty(SHUTDOWN_HOOK_PROP);
    if ((enableHook == null) || !enableHook.equalsIgnoreCase("false")) {
      Runtime.getRuntime()
          .addShutdownHook(
              new Thread("Felix Shutdown Hook") {
                public void run() {
                  try {
                    if (m_fwk != null) {
                      m_fwk.stop();
                      m_fwk.waitForStop(0);
                    }
                  } catch (Exception ex) {
                    System.err.println("Error stopping framework: " + ex);
                  }
                }
              });
    }

    try {
      // Create an instance of the framework.
      FrameworkFactory factory = getFrameworkFactory();
      m_fwk = factory.newFramework(configProps);
      // Initialize the framework, but don't start it yet.
      m_fwk.init();
      // Use the system bundle context to process the auto-deploy
      // and auto-install/auto-start properties.
      AutoProcessor.process(configProps, m_fwk.getBundleContext());
      FrameworkEvent event;
      do {
        // Start the framework.
        m_fwk.start();
        // Wait for framework to stop to exit the VM.
        event = m_fwk.waitForStop(0);
      }
      // If the framework was updated, then restart it.
      while (event.getType() == FrameworkEvent.STOPPED_UPDATE);
      // Otherwise, exit.
      System.exit(0);
    } catch (Exception ex) {
      System.err.println("Could not create framework: " + ex);
      ex.printStackTrace();
      System.exit(0);
    }
  }
Beispiel #21
0
  @Override
  public boolean startup(IPentahoSession session) {

    logger.info("Starting OSGI Environment");
    String solutionRootPath = PentahoSystem.getApplicationContext().getSolutionRootPath();

    final String sep = File.separator;
    Properties osgiProps = new Properties();
    File propsFile =
        new File(solutionRootPath + sep + "system" + sep + "osgi" + sep + "config.properties");
    if (propsFile.exists()) {
      try {
        osgiProps.load(new FileInputStream(propsFile));
      } catch (IOException e) {
        logger.error("Error reading OSGI Host config", e);
      }
    }

    Map<String, String> configProps = new HashMap<String, String>();

    for (Map.Entry<Object, Object> entry : osgiProps.entrySet()) {
      configProps.put(entry.getKey().toString(), entry.getValue().toString());
    }

    // configProps.put( FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, Collections.singletonList(new
    // org.pentaho.platform.osgi.PentahoOSGIActivator()) );
    configProps.put(Constants.FRAMEWORK_STORAGE, solutionRootPath + "/system/osgi/cache");
    System.setProperty("felix.fileinstall.dir", solutionRootPath + "/system/osgi/bundles");

    configProps.put("felix.fileinstall.debug", "4");
    configProps.put("felix.fileinstall.bundles.new.start", "true");
    configProps.put("felix.fileinstall.bundles.startActivationPolicy", "false");

    configProps.put("org.eclipse.virgo.kernel.home", solutionRootPath + "/osgi/virgo");
    configProps.put(
        "org.eclipse.virgo.kernel.config", solutionRootPath + "/osgi/virgo/configuration");
    configProps.put(
        "osgi.sharedConfiguration.area", solutionRootPath + "/osgi/virgo/configuration");
    configProps.put("osgi.configuration.area", solutionRootPath + "/osgi/virgo/configuration");
    configProps.put("osgi.install.area", solutionRootPath + "/osgi/virgo");
    configProps.put("eclipse.ignoreApp", "true");

    try {
      logger.debug("Attempting to load OSGI FrameworkFactory.");
      FrameworkFactory factory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
      logger.debug("FrameworkFactory found");
      framework = factory.newFramework(configProps);
      logger.debug("Initializing FrameworkFactory");
      framework.init();

      logger.debug("Starting FrameworkFactory");
      framework.start();

      Runtime.getRuntime()
          .addShutdownHook(
              new Thread("Felix Shutdown Hook") {
                public void run() {
                  shutdownFramework();
                }
              });

      List<Bundle> bundleList = new ArrayList<Bundle>();

      File[] bundleDirectories =
          new File[] {
            new File(
                solutionRootPath
                    + File.separator
                    + "system"
                    + File.separator
                    + "osgi"
                    + File.separator
                    + "core_bundles"),
            new File(
                solutionRootPath
                    + File.separator
                    + "system"
                    + File.separator
                    + "osgi"
                    + File.separator
                    + "fragment_bundles"),
            new File(
                solutionRootPath
                    + File.separator
                    + "system"
                    + File.separator
                    + "osgi"
                    + File.separator
                    + "bundles")
          };

      logger.debug("Installing bundles");
      for (File bundleDirectory : bundleDirectories) {
        if (bundleDirectory.exists() == false) {
          logger.warn("Bundle directory: " + bundleDirectory.getName() + " does not exist");
          continue;
        }
        for (File f : bundleDirectory.listFiles()) {
          if (f.isFile() && f.getName().endsWith(".jar")) {
            try {
              Bundle b = framework.getBundleContext().installBundle(f.toURI().toString());
              bundleList.add(b);
            } catch (Exception e) {
              logger.error("Error installing Bundle", e);
            }
          }
        }
      }

      logger.debug("Starting bundles");
      for (Bundle bundle : bundleList) {
        try {
          // detect if a fragment bundle and skip. They cannot be started..
          if (bundle.getHeaders().get("Fragment-Host") != null) {
            continue;
          }
          bundle.start();
        } catch (Exception e) {
          logger.error("Error installing Bundle", e);
        }
      }

      new PentahoOSGIActivator().setBundleContext(framework.getBundleContext());

      return true;
    } catch (Exception ex) {
      logger.error("Error starting OSGI environment", ex);
      return false;
    }
  }
 public static BundleContext getSystemContext() throws BundleException {
   Framework framework = getFramework();
   return framework.getBundleContext();
 }
 public void setBundleStartLevel(long bundleId, int startLevel) throws TestContainerException {
   StartLevel sl = getStartLevelService(m_framework.getBundleContext());
   sl.setBundleStartLevel(m_framework.getBundleContext().getBundle(bundleId), startLevel);
 }
 private void syncWithOsgi() {
   Framework f = FelixWrapper.getInstance(null).getFramework();
   mBundles = f.getBundleContext().getBundles();
 }