下面列出了org.osgi.framework.Bundle#start ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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);
}
}
@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");
}
}
/**
* 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();
}
}
}
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();
}
/**
* 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
}
}
@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);
}
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);
}
}
}
}
@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");
}
}
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);
}
}
}
/**
* 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;
}
/**
* 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;
}
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);
}
}
@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));
}
@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);
}
}
/**
* 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);
}
}
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();
}
}
}
}
@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);
}
protected Bundle startBundle(String bundleSymbolicName) throws BundleException {
Bundle bundle = getBundle(bundleSymbolicName);
bundle.start();
return bundle;
}
/**
* 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);
}
/**
* 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;
}