Java Code Examples for org.osgi.framework.Bundle#start()

The following examples show how to use org.osgi.framework.Bundle#start() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NexusBundleTracker.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void prepareDependencies(final Bundle bundle) {
  final BundleWiring wiring = bundle.adapt(BundleWiring.class);
  final List<BundleWire> wires = wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
  if (wires != null) {
    for (final BundleWire wire : wires) {
      try {
        final Bundle dependency = wire.getProviderWiring().getBundle();
        if (!visited.contains(dependency.getSymbolicName()) && hasComponents(dependency)) {
          if (!live(dependency)) {
            dependency.start();
          }
          if (live(dependency)) {
            // pseudo-event to trigger bundle activation
            addingBundle(dependency, null /* unused */);
          }
        }
      }
      catch (final Exception e) {
        log.warn("MISSING {}", wire, e);
      }
    }
  }
}
 
Example 2
Source File: TestOsgi.java    From sensorhub with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void test3BundleDependencies() throws Exception
{
    Framework fw = getFramework();
    fw.start();
    
    assertEquals("Wrong number of loaded bundles", 1, fw.getBundleContext().getBundles().length);
    
    // install 1st bundle
    installBundle(fw, getClass().getResource("/test-nodep.jar").toString(), "org.sensorhub.test");
    
    // install 2nd bundle
    Bundle bundle2 = installBundle(fw, getClass().getResource("/test-withdep.jar").toString(), "org.sensorhub.test2");
    
    bundle2.start();
    assertEquals("Bundle " + bundle2.getSymbolicName() + " should be in ACTIVE state", Bundle.ACTIVE, bundle2.getState());
    
    fw.stop();
    fw.waitForStop(0);
}
 
Example 3
Source File: KarafFullFeatureIntegrationTest.java    From camunda-bpm-platform-osgi with Apache License 2.0 6 votes vote down vote up
@Test
public void startCamundaOsgiBundle() throws BundleException {
  assertThat(ctx, is(notNullValue()));
  Bundle[] bundles = ctx.getBundles();
  boolean found = false;
  for (Bundle b : bundles) {
    assertThat("Bundle " + b.getSymbolicName() + " is in wrong state.",b.getState(), is(either(equalTo(Bundle.RESOLVED)).or(equalTo(Bundle.ACTIVE)).or(equalTo(Bundle.STARTING))));
    if (b.getSymbolicName().equals("org.camunda.bpm.extension.osgi")) {
      b.start();
      found = true;
    }
  }
  if (!found) {
    fail("Couldn't find bundle");
  }
}
 
Example 4
Source File: CarbonServer.java    From carbon-kernel with Apache License 2.0 6 votes vote down vote up
/**
 * Installs a bundle from the specified locations.
 *
 * @param bundleContext bundle's execution context within the Framework
 * @throws BundleException
 */
private void loadInitialBundles(BundleContext bundleContext) throws BundleException {
    //Setting this property due to an issue with equinox simple configurator where it tries to uninstall bundles
    //which are loaded from initial bundle list.
    System.setProperty(Constants.EQUINOX_SIMPLE_CONFIGURATOR_EXCLUSIVE_INSTALLATION, "false");

    for (CarbonInitialBundle initialBundleInfo : config.getInitialBundles()) {
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Loading initial bundle: " + initialBundleInfo.getLocation().toExternalForm() +
                    " with startlevel " + initialBundleInfo.getLevel());
        }

        Bundle bundle = bundleContext.installBundle(initialBundleInfo.getLocation().toString());
        if (initialBundleInfo.shouldStart()) {
            bundle.start();
        }
    }
}
 
Example 5
Source File: FrameworkLaunchArgsTest.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This test will install a bundle which refers to a class from Java runtime
 * (<code>javax.imageio</code>). As this <code>javax</code> package is
 * missing in system packages, it can NOT be used and an exception will be
 * thrown, which is expected behavior.
 */
@Test
public void testGetClassFromBootdelegationMissing() throws Exception {
	startFramework();
	SyntheticBundleBuilder builder = SyntheticBundleBuilder.newBuilder();
	builder.bundleSymbolicName("testGetClassFromBootdelegationMissing")
			.bundleVersion("1.0.0");
	Bundle bundleUnderTest = installBundle(builder);
	bundleUnderTest.start();
	assertBundleResolved(bundleUnderTest);

	String className = "javax.imageio.ImageTranscoder";
	RunInClassLoader runner = new RunInClassLoader(bundleUnderTest);
	try {
		runner.getClass(className);
		Assert.fail("Oops, ClassNotFoundException expected");
	} catch (ClassNotFoundException ex) {
		// OK expected
	}
}
 
Example 6
Source File: DefaultAppDeployer.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
    * Installs an OSGi bundle into the OSGi environment through the bundle context..
    *
    * @param bundlePath - absolute path to the bundle to be installed..
    */
   private void installBundle(String bundlePath) {
       String bundlePathFormatted = getFormattedBundlePath(bundlePath);
log.info("OSGi bundle in "+bundlePathFormatted+" location is about to be installed to Carbon Server.");

       try {
           Bundle bundle = CarbonCoreDataHolder.getInstance()
                   .getBundleContext().installBundle(bundlePathFormatted);
           if (bundle != null) {
	log.info("OSGi bundle "+bundle.getSymbolicName()+" installed to Carbon Server.");
               bundle.start();
	log.info("OSGi bundle "+bundle.getSymbolicName()+" successfully started on Carbon Server.");
           }
       } catch (BundleException e) {
           log.error("Error while installing bundle : " + bundlePathFormatted, e);
       }
   }
 
Example 7
Source File: HttpWhiteboardCoexistenceTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
private void restartHttpServiceWhiteboard() throws Exception {
    BundleWiring runtimeWiring = _runtimeServiceReference.getBundle().adapt(BundleWiring.class);
    
    Bundle httpService = runtimeWiring.getRequiredWires("osgi.implementation").stream()
        .filter(bw -> "osgi.http".equals(bw.getCapability().getAttributes().get("osgi.implementation")))
        .map(bw -> bw.getProvider().getBundle())
        .findFirst().get();
    
    try {
        httpService.stop();
    } finally {
        httpService.start();
    }
    
    _runtime = _runtimeTracker.waitForService(5000);
    _runtimeServiceReference = _runtimeTracker.getServiceReference();
}
 
Example 8
Source File: FelixFramework.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public void startBundles(List<Bundle> bundles, boolean privileged) throws BundleException {
    for (Bundle bundle : bundles) {
        if (!privileged && OsgiHeader.isSet(bundle, OsgiHeader.PRIVILEGED_ACTIVATOR)) {
            log.log(Level.INFO, "OSGi bundle '" + bundle.getSymbolicName() + "' " +
                    "states that it requires privileged " +
                    "initialization, but privileges are not available. YMMV.");
        }
        if (bundle.getHeaders().get(Constants.FRAGMENT_HOST) != null) {
            continue; // fragments can not be started
        }
        bundle.start();
    }
    log.info(startedBundlesMessage(bundles));
}
 
Example 9
Source File: BundlesWithFrameworkDependenciesTest.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testInstallAndStartManifestWithRequireBundleSystemBundle()
		throws Exception {
	final SyntheticBundleBuilder builder = SyntheticBundleBuilder
			.newBuilder();
	builder.bundleSymbolicName(
			"testInstallAndStartManifestWithRequireBundleSystemBundle")
			.bundleVersion("1.0.0")
			.addManifestHeader("Require-Bundle", "system.bundle");
	final Bundle bundleUnderTest = installBundle(builder);
	bundleUnderTest.start();
	assertBundleActive(bundleUnderTest);
}
 
Example 10
Source File: LaunchServiceTest.java    From JaxRSProviders with Apache License 2.0 5 votes vote down vote up
static void startBundle(String symbolicName) throws BundleException {
	BundleContext context = FrameworkUtil.getBundle(LaunchServiceTest.class).getBundleContext();
	for (Bundle bundle : context.getBundles()) {
		if (bundle.getSymbolicName().equals(symbolicName)) {
			if (bundle.getState() != Bundle.ACTIVE) {
				bundle.start();
			}
		}
	}
}
 
Example 11
Source File: ChameleonExecutor.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Deploys the `probe` bundle, i.e. the bundle containing the test classes and the Wisdom Test Utilities (such as
 * the InVivo Runner). If such a bundle is already deployed, nothing is done, else, the probe bundle is built,
 * installed and started.
 * <p>
 * Initially, this method was returning {@code null}. In the 0.7 version, it changes to {@code Bundle}. The
 * returned object is the installed bundle.
 *
 * @return the probe bundle.
 * @throws BundleException if the probe bundle cannot be started.
 */
public static Bundle deployProbe() throws BundleException {
    for (Bundle bundle : ChameleonInstanceHolder.get().context().getBundles()) {
        if (bundle.getSymbolicName().equals(ProbeBundleMaker.BUNDLE_NAME)) {
            return bundle;
        }
    }
    try {
        Bundle probe = ChameleonInstanceHolder.get().context().installBundle("local", ProbeBundleMaker.probe());
        probe.start();
        return probe;
    } catch (Exception e) {
        throw new RuntimeException("Cannot install or start the probe bundle", e);
    }
}
 
Example 12
Source File: BundleStateResource.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Representation put(final Representation value,
		final Variant variant) {
	try {
		final Bundle bundle = getBundleFromKeys(RestService.BUNDLE_ID_KEY);
		if (bundle == null) {
			setStatus(Status.CLIENT_ERROR_NOT_FOUND);
			return null;
		}

		final BundleStatePojo targetState = fromRepresentation(value,
				value.getMediaType());

		if (bundle.getState() == Bundle.UNINSTALLED) {
			return ERROR(Status.CLIENT_ERROR_PRECONDITION_FAILED, "target state "
					+ targetState.getState() + " not reachable from the current state");
		} else if (targetState.getState() == Bundle.ACTIVE) {
			bundle.start(targetState.getOptions());
			return getRepresentation(
					new BundleStatePojo(bundle.getState()), variant);
		} else if (targetState.getState() == Bundle.RESOLVED) {
			bundle.stop(targetState.getOptions());
			return getRepresentation(
					new BundleStatePojo(bundle.getState()), variant);
		} else {
			return ERROR(Status.CLIENT_ERROR_BAD_REQUEST, "target state "
					+ targetState.getState() + " not supported");
		}
	} catch (final Exception e) {
		return ERROR(e, variant);
	}
}
 
Example 13
Source File: OsgiImpl.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static void ensureBundleActive(Bundle bundle) throws IllegalStateException {
    int state = bundle.getState();
    Throwable cause = null;
    if (state != Bundle.ACTIVE) {
        try {
            // Get the reason why the bundle isn't active.
            // Do not change this method to not fail if start is successful without carefully analyzing
            // why there are non-active bundles.
            bundle.start();
        } catch (BundleException e) {
            cause = e;
        }
        throw new IllegalStateException("Bundle " + bundle + " is not active. State=" + state + ".", cause);
    }
}
 
Example 14
Source File: DatasetClassPathHelper.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the workspace classpath
 * 
 * @return
 * 
 * @deprecated use {@link #getWorkspaceClassPath(String)}
 */
public static String getWorkspaceClassPath( )
{
	try
	{
		Bundle bundle = Platform.getBundle( FINDER_BUNDLE_NAME );
		if ( bundle != null )
		{
			if ( bundle.getState( ) == Bundle.RESOLVED )
			{
				bundle.start( Bundle.START_TRANSIENT );
			}
		}

		if ( bundle == null )
			return null;

		Class clz = bundle.loadClass( FINDER_CLASSNAME );

		// register workspace classpath finder
		IDatasetWorkspaceClasspathFinder finder = (IDatasetWorkspaceClasspathFinder) clz.newInstance( );
		if ( finder == null )
			return null;

		return finder.getClassPath( );
	}
	catch ( Exception e )
	{
		e.printStackTrace( );
	}

	return null;
}
 
Example 15
Source File: AbstractConciergeTestCase.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Install a bundle for given name. Will check whether bundle can be
 * resolved.
 */
protected Bundle installAndStartBundle(final String bundleName)
		throws BundleException {
	final String url = this.localBundleStorage.getUrlForBundle(bundleName);
	// System.err.println("installAndStartBundle: " + bundleName);

	final Bundle bundle = bundleContext.installBundle(url);

	if (!isFragmentBundle(bundle)) {
		bundle.start();
	}
	return bundle;
}
 
Example 16
Source File: ServerTestsActivator.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
static private void ensureBundleStarted(String name) throws BundleException {
	Bundle bundle = getBundle(name);
	if (bundle != null) {
		if (bundle.getState() == Bundle.RESOLVED || bundle.getState() == Bundle.STARTING) {
			bundle.start(Bundle.START_TRANSIENT);
		}
	}
}
 
Example 17
Source File: KarafMinimalFeatureIntegrationTest.java    From camunda-bpm-platform-osgi with Apache License 2.0 5 votes vote down vote up
@Test
public void startCamundaOsgiBundle() throws BundleException {
  assertThat(ctx, is(notNullValue()));
  Bundle[] bundles = ctx.getBundles();
  boolean found = false;
  for (Bundle b : bundles) {
    if (b.getSymbolicName().equals("org.camunda.bpm.extension.osgi")) {
      b.start();
      found = true;
    }
  }
  if (!found) {
    fail("Couldn't find bundle");
  }
}
 
Example 18
Source File: BundlesWithFrameworkExtensionsTest.java    From concierge with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This test will install a fragment bundle to framework system.bundle, a
 * second bundle to use the exported package. All is fine. The stop the
 * framework, restart again from storage. But now the bundle can NOT be
 * resolved anymore, so something is wrong.
 */
@Test
@Ignore("TODO does not work when restarting from storage")
public void testFrameworkExtensionFragmentOfSystemBundleRestart()
		throws Exception {
	startFramework();
	SyntheticBundleBuilder builder;

	builder = SyntheticBundleBuilder.newBuilder();
	builder.bundleSymbolicName(
			"testFrameworkExtensionFragmentOfSystemBundle")
			.bundleVersion("1.0.0")
			.addManifestHeader("Fragment-Host",
					"system.bundle; extension:=framework")
			.addManifestHeader("Export-Package", "p1");
	Bundle bundle1UnderTest = installBundle(builder);
	assertBundleResolved(bundle1UnderTest);

	builder = SyntheticBundleBuilder.newBuilder();
	builder.bundleSymbolicName(
			"testBundleUsingAnExtensionFragmentOfSystemBundle")
			.bundleVersion("1.0.0")
			.addManifestHeader("Import-package", "p1");
	Bundle bundle2UnderTest = installBundle(builder);
	bundle2UnderTest.start();
	assertBundleResolved(bundle2UnderTest);

	// restart framework, NO clean start
	stopFramework();
	startFrameworkNonClean();

	Bundle[] bundles = framework.getBundleContext().getBundles();
	Assert.assertThat(bundles, notNullValue());
	Bundle bundle1 = getBundleForBSN(bundles,
			"testFrameworkExtensionFragmentOfSystemBundle");
	Assert.assertThat(bundle1, notNullValue());
	// fragment must be resolved
	assertBundleResolved(bundle1);

	Bundle bundle2 = getBundleForBSN(bundles,
			"testBundleUsingAnExtensionFragmentOfSystemBundle");
	Assert.assertThat(bundle2, notNullValue());
	// bundle must be active, which does not yet work
	assertBundleActive(bundle2);
}
 
Example 19
Source File: OSGiTestEnvironment.java    From camunda-bpm-platform-osgi with Apache License 2.0 4 votes vote down vote up
protected Bundle startBundle(String bundleSymbolicName) throws BundleException {
  Bundle bundle = getBundle(bundleSymbolicName);
  bundle.start();
  return bundle;
}
 
Example 20
Source File: SyntheticBundleInstaller.java    From smarthome with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Install synthetic bundle, denoted by its name, into the test runtime (by using the given bundle context).
 *
 * @param bundleContext the bundle context of the test runtime
 * @param testBundleNamethe symbolic name of the sub-directory of {@value #BUNDLE_POOL_PATH}, which contains the
 *            files
 *            for the synthetic bundle
 * @param extensionsToInclude a list of extension to be included into the synthetic bundle. In order to use the list
 *            of default extensions ({@link #DEFAULT_EXTENSIONS})
 *
 * @return the synthetic bundle representation
 * @throws Exception thrown when error occurs while installing or starting the synthetic bundle
 */
public static Bundle install(BundleContext bundleContext, String testBundleName, Set<String> extensionsToInclude)
        throws Exception {
    String bundlePath = BUNDLE_POOL_PATH + "/" + testBundleName + "/";
    byte[] syntheticBundleBytes = createSyntheticBundle(bundleContext.getBundle(), bundlePath, testBundleName,
            extensionsToInclude);

    Bundle syntheticBundle = bundleContext.installBundle(testBundleName,
            new ByteArrayInputStream(syntheticBundleBytes));
    syntheticBundle.start(Bundle.ACTIVE);
    waitUntilLoadingFinished(bundleContext, syntheticBundle);
    return syntheticBundle;
}