org.osgi.framework.launch.Framework Java Examples

The following examples show how to use org.osgi.framework.launch.Framework. 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: ClassLoaderUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected <T> Maybe<T> tryLoadFromBundleWhiteList(LoaderDispatcher<T> dispatcher, String className) {
    Framework framework = getFramework();
    if (framework == null) {
        return Maybe.absentNull();
    }
    List<Bundle> bundles = Osgis.bundleFinder(framework)
        .satisfying(createBundleMatchingPredicate())
        .findAll();
    for (Bundle b : bundles) {
        Maybe<T> item = dispatcher.tryLoadFrom(b, className);
        if (item.isPresent()) {
            return item;
        }
    }
    return Maybe.absentNull();
}
 
Example #2
Source File: CarbonServer.java    From carbon-kernel with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes and start framework. Framework will try to resolve all the bundles if their requirements
 * can be satisfied.
 *
 * @param framework osgiFramework
 * @throws BundleException
 */
private void initAndStartOSGiFramework(Framework framework) throws BundleException {
    if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "Initializing the OSGi framework.");
    }

    framework.init();

    // Starts the framework.
    if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "Starting the OSGi framework.");
    }

    framework.start();

    if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "Started the OSGi framework.");
    }
}
 
Example #3
Source File: TestOsgi.java    From sensorhub with Mozilla Public License 2.0 6 votes vote down vote up
protected Bundle installBundle(Framework fw, String bundleURL, String bundleName) throws Exception
{
    int numBundles = fw.getBundleContext().getBundles().length;
    
    // install bundle
    Bundle newBundle = fw.getBundleContext().installBundle(bundleURL);
    assertTrue("bundle should not be null", newBundle != null);        
    System.out.println("Bundle name is " + newBundle.getSymbolicName());
    
    // check that it was properly loaded
    assertEquals("Wrong number of loaded bundles", numBundles+1, fw.getBundleContext().getBundles().length);
    assertEquals("Unexpected bundle name", bundleName, newBundle.getSymbolicName());
    assertEquals("Bundle should be in INSTALLED state", Bundle.INSTALLED, newBundle.getState());
    
    return newBundle;
}
 
Example #4
Source File: EmbeddedFelixFramework.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static Framework newFrameworkStarted(String felixCacheDir, boolean clean, Map<?,?> extraStartupConfig) {
    Map<Object,Object> cfg = MutableMap.copyOf(extraStartupConfig);
    if (clean) cfg.put(Constants.FRAMEWORK_STORAGE_CLEAN, "onFirstInit");
    if (felixCacheDir!=null) cfg.put(Constants.FRAMEWORK_STORAGE, felixCacheDir);
    cfg.put(Constants.FRAMEWORK_BSNVERSION, Constants.FRAMEWORK_BSNVERSION_MULTIPLE);
    FrameworkFactory factory = newFrameworkFactory();

    Stopwatch timer = Stopwatch.createStarted();
    Framework framework = factory.newFramework(cfg);
    try {
        framework.init();
        installBootBundles(framework);
        framework.start();
    } catch (Exception e) {
        // framework bundle start exceptions are not interesting to caller...
        throw Exceptions.propagate(e);
    }
    LOG.debug("System bundles are: "+SYSTEM_BUNDLES);
    LOG.debug("OSGi framework started in " + Duration.of(timer));
    return framework;
}
 
Example #5
Source File: TestOsgi.java    From sensorhub with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void test2InstallBundle() throws Exception
{
    Framework fw = getFramework();
    fw.start();
    
    // install bundle w/o dependency
    Bundle newBundle = installBundle(fw, getClass().getResource("/test-nodep.jar").toString(), "org.sensorhub.test");
            
    // attempt to start it
    newBundle.start();
    assertEquals("Bundle should be in ACTIVE state", Bundle.ACTIVE, newBundle.getState());
    
    fw.stop();
    fw.waitForStop(0);
}
 
Example #6
Source File: ClassLoaderUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private Framework getFramework() {
    if (mgmt != null) {
        Maybe<OsgiManager> osgiManager = ((ManagementContextInternal)mgmt).getOsgiManager();
        if (osgiManager.isPresent()) {
            OsgiManager osgi = osgiManager.get();
            return osgi.getFramework();
        }
    }

    // Requires that caller code is executed AFTER loading bundle brooklyn-core
    Bundle bundle = FrameworkUtil.getBundle(ClassLoaderUtils.class);
    if (bundle != null) {
        BundleContext bundleContext = bundle.getBundleContext();
        return (Framework) bundleContext.getBundle(0);
    } else {
        return null;
    }
}
 
Example #7
Source File: CarbonServer.java    From carbon-kernel with Apache License 2.0 6 votes vote down vote up
/**
 * Wait until this Framework has completely stopped.
 *
 * @param framework OSGi framework
 * @throws java.lang.Exception
 */
private void waitForServerStop(Framework framework) throws Exception {
    if (!isFrameworkActive()) {
        return;
    }

    while (true) {
        FrameworkEvent event = framework.waitForStop(0);

        // We should not stop the framework if the user has updated the system bundle via the OSGi console or
        //  programmatically. In this case, framework will shutdown and start itself.
        if (event.getType() != FrameworkEvent.STOPPED_UPDATE) {
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "OSGi framework is stopped for update.");
            }
            break;
        }
    }
}
 
Example #8
Source File: SystemBundle.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <A> A adapt(Class<A> type)
{
  secure.checkAdaptPerm(this, type);
  Object res = null;
  if (FrameworkWiring.class.equals(type)) {
    res = fwWiring;
  } else if (FrameworkStartLevel.class.equals(type)) {
    if (fwCtx.startLevelController != null) {
      res = fwCtx.startLevelController.frameworkStartLevel();
    }
  } else if (Framework.class.equals(type)) {
    res = this;
  } else if (FrameworkStartLevelDTO.class.equals(type)) {
    if (fwCtx.startLevelController != null) {
      res = fwCtx.startLevelController.frameworkStartLevel().getDTO();
    }
  } else if (FrameworkDTO.class.equals(type)) {
    res = getFrameworkDTO();
  } else {
    // TODO filter which adaptation we can do?!
    res = adaptSecure(type);
  }
  return (A) res;
}
 
Example #9
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 #10
Source File: Main.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns a bundle id from a string. The string is either a number
 * or the location used for the bundle in the
 * "-install bundleLocation" or "-istart" command.
 * @param base Base URL to complete locations with.
 * @param idLocation bundle id or location of the bundle to lookup
 */
private long getBundleID(Framework fw, String idLocation) {
  try {
    return Long.parseLong(idLocation);
  } catch (final NumberFormatException nfe) {
    final Bundle[] bl = fw.getBundleContext().getBundles();
    final String loc = completeLocation(idLocation);
    for(int i = 0; bl != null && i < bl.length; i++) {
      if(loc.equals(bl[i].getLocation())) {
        return bl[i].getBundleId();
      }
    }
    throw new IllegalArgumentException
      ("Invalid bundle id/location: " +idLocation);
  }
}
 
Example #11
Source File: AbstractConciergeTestCase.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/** Start framework for a given framework. */
public void useFramework(final Framework frameworkToStart)
		throws Exception {
	// start OSGi framework
	this.framework = frameworkToStart;
	this.bundleContext = this.framework.getBundleContext();

	if (stayInShell()) {
		String shellJarName = "./test/resources/org.eclipse.concierge.shell-5.0.0.20151029184259.jar";
		if (!new File(shellJarName).exists()) {
			System.err.println(
					"Oops, could not find shell bundle at " + shellJarName);
		} else {
			// assume to get shell jar file in target folder
			installAndStartBundle(shellJarName);
		}
	}
}
 
Example #12
Source File: KfApk.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Create a new framework, initialize and start it. If the init
 * parameter is true, or if there is no stored framework state, bundle
 * Jar file data will be read from the "jars" folder of the provided
 * AssetManager. If the init parameter is false and there is a stored
 * framework state, the framework will be started and its state will
 * be the stored state.
 * 
 * @param localStorage Path to application's storage location in the
 *        file system, framework state will be stored here
 * @param init If true, any stored framework state is ignored.
 * @param am AssetManager for the application, will be used to read
 *        bundle Jar file data when the framework is started without
 *        using a stored state.
 * @return a framework instance or null if the framework could not be
 *         started or initialized.
 * @throws IOException if there was a problem reading bundle Jar file
 *         data or framework/system properties using the AssestManager.
 */
public static Framework newFramework(String localStorage,
                                     boolean init,
                                     AssetManager am)
    throws IOException
{
  config = getConfiguration(am);
  String fwDir = localStorage + File.separator + FWDIR;
  config.put(Constants.FRAMEWORK_STORAGE, fwDir);

  boolean doInit = init || !new File(fwDir).exists();
  
  if (doInit) {
    config.put(Constants.FRAMEWORK_STORAGE_CLEAN,
               Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
  }

  Framework fw = new Main().getFrameworkFactory().newFramework(config);
  try {
    fw.init();
    int runlevel;
    if (doInit) {
      runlevel = scanBundles(fw, am);
      saveRunlevel(runlevel, fwDir);
    } else {
      runlevel = loadRunlevel(fwDir);
    }
    fw.start();
    // set target start level for framework start-up
    final FrameworkStartLevel fsl = fw.adapt(FrameworkStartLevel.class);
    if (fsl!=null) {
      fsl.setStartLevel(runlevel);
    }      
  } catch (BundleException be) {
    Log.e(KfApk.class.getName(), "Failed to init/start framework", be);
    return null;
  }
  
  return fw;
}
 
Example #13
Source File: KfApk.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Method that can be used to wait for a started framework to be
 * shut down.
 * 
 * @param fw the framework to wait on.
 */
public static void waitForStop(Framework fw) {
  while (true) { // Ignore interrupted exception.
    try {
      FrameworkEvent stopEvent = fw.waitForStop(0L);
      switch (stopEvent.getType()) {
      case FrameworkEvent.STOPPED:
        // FW terminated, Main is done!
        Log.i(KfApk.class.getName(), "Framework terminated");
        return;
      case FrameworkEvent.STOPPED_UPDATE:
        // Automatic FW restart, wait again.
        break;
      case FrameworkEvent.STOPPED_BOOTCLASSPATH_MODIFIED:
        // A manual FW restart with new boot class path is needed.
        return; // TODO
      case FrameworkEvent.ERROR:
        // Stop failed or other error, give up.
        Log.i(KfApk.class.getName(), "Fatal framework error, terminating.",
              stopEvent.getThrowable());
        return;
      case FrameworkEvent.WAIT_TIMEDOUT:
        // Should not happen with timeout==0, give up.
        Log.i(KfApk.class.getName(), "Framework waitForStop(0) timed out!",
              stopEvent.getThrowable());
        break;
      }
    } catch (final InterruptedException ie) { }
  }
}
 
Example #14
Source File: BrooklynLauncherRebindCatalogOsgiTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void runInstallPreexistingBundleViaInitialBomBrooklynLibrariesReference(boolean useVersionRange) throws Exception {
    Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0"));
    VersionedName systemBundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest.system"+Identifiers.makeRandomId(4), "1.0.0");
    File systemBundleFile = newTmpBundle(bundleItems, systemBundleName);

    VersionedName systemBundleNameRef;
    if (useVersionRange) {
        systemBundleNameRef = new VersionedName(systemBundleName.getSymbolicName(), "[1,2)");
    } else {
        systemBundleNameRef = systemBundleName;
    }
    File initialBomFile = newTmpFile(createCatalogYaml(ImmutableList.of(), ImmutableList.of(systemBundleNameRef), ImmutableList.of()));
    
    // Add our bundle, so it feels for all intents and purposes like a "system bundle"
    Framework reusedFramework = initReusableOsgiFramework();
    Bundle pseudoSystemBundle = installBundle(reusedFramework, systemBundleFile);
    manuallyInsertedBundles.add(pseudoSystemBundle);
    
    startupAssertions = () -> {
        assertOnlyBundle(launcherLast, systemBundleName, pseudoSystemBundle);
        assertCatalogConsistsOfIds(launcherLast, bundleItems);
        assertManagedBundle(launcherLast, systemBundleName, bundleItems);
    };
    
    // Launch brooklyn, with initial catalog pointing at system bundle.
    // Should bring it under brooklyn-management (without re-installing it).
    startT1(newLauncherForTests(initialBomFile.getAbsolutePath()));

    // Launch brooklyn again (because will have persisted both those bundles)
    startT2(newLauncherForTests(CATALOG_EMPTY_INITIAL));
    launcherT2.terminate();
}
 
Example #15
Source File: RebindOsgiTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Bundle getBundle(ManagementContext mgmt, final String symbolicName) throws Exception {
    OsgiManager osgiManager = ((ManagementContextInternal)mgmt).getOsgiManager().get();
    Framework framework = osgiManager.getFramework();
    Maybe<Bundle> result = Osgis.bundleFinder(framework)
            .symbolicName(symbolicName)
            .find();
    return result.get();
}
 
Example #16
Source File: EmbeddedFelixFramework.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static void installBootBundles(Framework framework) {
    Stopwatch timer = Stopwatch.createStarted();
    LOG.debug("Installing OSGi boot bundles from "+EmbeddedFelixFramework.class.getClassLoader()+"...");
    
    Iterator<URL> resources = BOOT_BUNDLES.iterator();
    // previously we evaluated this each time, but lately (discovered in 2019,
    // possibly the case for a long time before) it seems to grow, accessing ad hoc dirs
    // in cache/* made by tests, which get deleted, logging lots of errors.
    // so now we statically populate it at load time.
    
    BundleContext bundleContext = framework.getBundleContext();
    Map<String, Bundle> installedBundles = getInstalledBundlesById(bundleContext);
    while (resources.hasNext()) {
        URL url = resources.next();
        ReferenceWithError<?> installResult = installExtensionBundle(bundleContext, url, installedBundles, OsgiUtils.getVersionedId(framework));
        if (installResult.hasError() && !installResult.masksErrorIfPresent()) {
            // it's reported as a critical error, so warn here
            LOG.warn("Unable to install manifest from "+url+": "+installResult.getError(), installResult.getError());
        } else {
            Object result = installResult.getWithoutError();
            if (result instanceof Bundle) {
                String v = OsgiUtils.getVersionedId( (Bundle)result );
                SYSTEM_BUNDLES.add(v);
                if (installResult.hasError()) {
                    LOG.debug(installResult.getError().getMessage()+(result!=null ? " ("+result+"/"+v+")" : ""));
                } else {
                    LOG.debug("Installed "+v+" from "+url);
                }
            } else if (installResult.hasError()) {
                LOG.debug(installResult.getError().getMessage());
            }
        }
    }
    LOG.debug("Installed OSGi boot bundles in "+Time.makeTimeStringRounded(timer)+": "+Arrays.asList(framework.getBundleContext().getBundles()));
}
 
Example #17
Source File: BrooklynLauncherRebindCatalogOsgiTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * See https://issues.apache.org/jira/browse/BROOKLYN-546.
 * 
 * We built up to launcher2, which will have three things:
 *  1. a pre-installed "system bundle"
 *  2. an initial catalog that references this same system bundle (hence the bundle will be "managed")
 *  3. persisted state that references this same system bundle.
 *
 * At the end of this, we want only one version of that "system bundle" to be installed, but also for
 * it to be a "brooklyn managed bundle".
 *
 * This scenario isn't quite the same as BROOKLYN-546. To make it fail, we'd need to have bundle URLs like:
 *     "mvn:org.apache.brooklyn/brooklyn-software-cm-ansible/1.0.0-SNAPSHOT"
 * (as is used in brooklyn-library/karaf/catalog/target/classes/catalog.bom).
 *
 * When that is used, the "osgi unique url" is the same as for the system library, so when it tries
 * to replace the library by calling "installBundle" then it fails.
 *
 * We ensure this isn't happening by asserting that our manually installed "system bundle" is still the same.
 */
@Test
public void testRebindWithSystemBundleInCatalog() throws Exception {
    Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0-SNAPSHOT"));
    VersionedName bundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest."+Identifiers.makeRandomId(4), "1.0.0.SNAPSHOT");
    File bundleFile = newTmpBundle(bundleItems, bundleName);
    File bundleFileCopy = newTmpCopy(bundleFile);

    File initialBomFile = newTmpFile(createCatalogYaml(ImmutableList.of(bundleFile.toURI()), ImmutableList.of()));

    // Add our bundle, so it feels for all intents and purposes like a "system bundle"
    Framework reusedFramework = initReusableOsgiFramework();
    Bundle pseudoSystemBundle = installBundle(reusedFramework, bundleFileCopy);
    manuallyInsertedBundles.add(pseudoSystemBundle);
    
    startupAssertions = () -> {
        assertCatalogConsistsOfIds(launcherLast, bundleItems);
        assertManagedBundle(launcherLast, bundleName, bundleItems);
    };
    
    // Launch brooklyn, where initial catalog includes a duplicate of the system bundle
    startT1(newLauncherForTests(initialBomFile.getAbsolutePath()));

    // Launch brooklyn, where persisted state now includes the initial catalog's bundle
    startT2(newLauncherForTests(initialBomFile.getAbsolutePath()));
    
    // Should not have replaced the original "system bundle"
    assertOnlyBundle(reusedFramework, bundleName, pseudoSystemBundle);

    launcherT2.terminate();
}
 
Example #18
Source File: NetigsoUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static Bundle bundle(Module module) throws Exception {
    Framework f = framework(module.getManager());
    for (Bundle b : f.getBundleContext().getBundles()) {
        if (b.getSymbolicName().equals(module.getCodeNameBase())) {
            return b;
        }
    }
    Assert.fail("no bundle found for " + module);
    return null;
}
 
Example #19
Source File: BrooklynLauncherRebindCatalogOsgiTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testInstallPreexistingBundleViaIndirectBrooklynLibrariesReference() throws Exception {
    Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0-SNAPSHOT"));
    VersionedName systemBundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest.system"+Identifiers.makeRandomId(4), "1.0.0.SNAPSHOT");
    File systemBundleFile = newTmpBundle(bundleItems, systemBundleName);

    String bundleBom = createCatalogYaml(ImmutableList.of(), ImmutableList.of(systemBundleName), ImmutableList.of());
    VersionedName bundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest.initial"+Identifiers.makeRandomId(4), "1.0.0.SNAPSHOT");
    File bundleFile = newTmpBundle(ImmutableMap.of(BasicBrooklynCatalog.CATALOG_BOM, bundleBom.getBytes(StandardCharsets.UTF_8)), bundleName);
    
    File initialBomFile = newTmpFile(createCatalogYaml(ImmutableList.of(bundleFile.toURI()), ImmutableList.of()));
    
    Preconditions.checkArgument(reuseOsgi, "Should be reusing OSGi; test did not correctly reset it.");
    // Add our bundle, so it feels for all intents and purposes like a "system bundle"
    Framework reusedFramework = initReusableOsgiFramework();
    Bundle pseudoSystemBundle = installBundle(reusedFramework, systemBundleFile);
    manuallyInsertedBundles.add(pseudoSystemBundle);
    
    startupAssertions = () -> {
        assertOnlyBundle(launcherLast, systemBundleName, pseudoSystemBundle);
        assertCatalogConsistsOfIds(launcherLast, bundleItems);
        assertManagedBundle(launcherLast, systemBundleName, bundleItems);
        assertManagedBundle(launcherLast, bundleName, ImmutableSet.of());
    };
    
    // Launch brooklyn, with initial catalog pointing at bundle that points at system bundle.
    // Should bring it under brooklyn-management (without re-installing it).
    startT1(newLauncherForTests(initialBomFile.getAbsolutePath()));

    // Launch brooklyn again (because will have persisted both those bundles)
    startT2(newLauncherForTests(CATALOG_EMPTY_INITIAL));
    
    launcherT2.terminate();
}
 
Example #20
Source File: EmbeddedFelixFramework.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static void stopFramework(Framework framework) throws RuntimeException {
    try {
        if (framework != null) {
            framework.stop();
            framework.waitForStop(0);
        }
    } catch (BundleException | InterruptedException e) {
        throw Exceptions.propagate(e);
    }
}
 
Example #21
Source File: BrooklynLauncherRebindCatalogOsgiTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void runInstallReplacesPreexistingBundle(boolean force) throws Exception {
    Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0-SNAPSHOT"));
    VersionedName bundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest."+Identifiers.makeRandomId(4), "1.0.0.SNAPSHOT");
    File systemBundleFile = newTmpBundle(bundleItems, bundleName);
    File replacementBundleFile = newTmpBundle(bundleItems, bundleName, "randomDifference"+Identifiers.makeRandomId(4));

    // Add our bundle, so it feels for all intents and purposes like a "system bundle"
    Framework reusedFramework = initReusableOsgiFramework();
    Bundle pseudoSystemBundle = installBundle(reusedFramework, systemBundleFile);
    manuallyInsertedBundles.add(pseudoSystemBundle);
    
    // Launch brooklyn, and explicitly install pre-existing bundle.
    // Should bring it under brooklyn-management (should not re-install it).
    startT1(newLauncherForTests(CATALOG_EMPTY_INITIAL));
    installBrooklynBundle(launcherT1, replacementBundleFile, force).getWithError();
    assertOnlyBundleReplaced(launcherLast, bundleName, pseudoSystemBundle);
    startupAssertions = () -> {
        assertCatalogConsistsOfIds(launcherLast, bundleItems);
        assertManagedBundle(launcherLast, bundleName, bundleItems);
    };
    startupAssertions.run();
    
    // Launch brooklyn again (because will have persisted the pre-installed bundle)
    startT2(newLauncherForTests(CATALOG_EMPTY_INITIAL));
    assertOnlyBundleReplaced(reusedFramework, bundleName, pseudoSystemBundle);
    launcherT2.terminate();
}
 
Example #22
Source File: BrooklynLauncherRebindCatalogOsgiTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Framework initReusableOsgiFramework() {
    if (!reuseOsgi) throw new IllegalStateException("Must first set reuseOsgi");
    
    if (OsgiManager.tryPeekFrameworkForReuse().isAbsent()) {
        BrooklynLauncher launcher = newLauncherForTests(CATALOG_EMPTY_INITIAL);
        launcher.start();
        launcher.terminate();
        Os.deleteRecursively(persistenceDir);
    }
    return OsgiManager.tryPeekFrameworkForReuse().get();
}
 
Example #23
Source File: ClassLoaderUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected <T> Maybe<T> tryLoadFromBundle(LoaderDispatcher<T> dispatcher, String symbolicName, String version,
                                         String name) {
    Framework framework = getFramework();
    if (framework != null) {
        Maybe<Bundle> bundle = Osgis.bundleFinder(framework)
            .symbolicName(symbolicName)
            .version(version)
            .find();
        if (bundle.isAbsent()) {
            String requestedV = symbolicName+":"+(Strings.isBlank(version) ? BrooklynCatalog.DEFAULT_VERSION : version);
            String upgradedV = CatalogUpgrades.getBundleUpgradedIfNecessary(mgmt, requestedV);
            if (!Objects.equal(upgradedV, requestedV)) {
                log.debug("Upgraded access to bundle "+requestedV+" for loading "+name+" to use bundle "+upgradedV);
                bundle = Osgis.bundleFinder(framework)
                    .id(upgradedV)
                    .find();
            }
            if (bundle.isAbsent()) {
                throw new IllegalStateException("Bundle " + toBundleString(symbolicName, version)
                    + " not found to load " + name);
            }
        }
        return dispatcher.tryLoadFrom(bundle.get(), name);
    } else {
        Maybe<T> result = dispatcher.tryLoadFrom(classLoader, name);
        if (result.isAbsent()) {
            if (name==null || name.startsWith("//") || symbolicName==null || "classpath".equals(symbolicName) || "http".equals(symbolicName) || "https".equals(symbolicName) || "file".equals(symbolicName)) {
                // this is called speculatively by BasicBrooklynCatalog.PlanInterpreterGuessingType so can log a lot of warnings where URLs are passed
                if (log.isTraceEnabled()) {
                    log.trace("Request for bundle '"+symbolicName+"' "+(Strings.isNonBlank(version) ? "("+version+") " : "")+"was ignored as no framework available; and failed to find '"+name+"' in plain old classpath");
                }
            } else {
                // TODO not sure warning is appropriate, but won't hide that in all cases yet
                log.warn("Request for bundle '"+symbolicName+"' "+(Strings.isNonBlank(version) ? "("+version+") " : "")+"was ignored as no framework available; and failed to find '"+name+"' in plain old classpath");
            }
        }
        return result;
    }
}
 
Example #24
Source File: Osgis.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Installs a bundle from the given URL, doing a check if already installed, and
 * using the {@link ResourceUtils} loader for this project (brooklyn core)
 */
public static Bundle install(Framework framework, String url) throws BundleException {
    boolean isLocal = isLocalUrl(url);
    String localUrl = url;
    if (!isLocal) {
        localUrl = cacheFile(url);
    }

    try {
        Bundle bundle = getInstalledBundle(framework, localUrl);
        if (bundle != null) {
            return bundle;
        }

        // use our URL resolution so we get classpath items
        LOG.debug("Installing bundle into {} from url: {}", framework, url);
        InputStream stream = getUrlStream(localUrl);
        Bundle installedBundle = framework.getBundleContext().installBundle(url, stream);
        
        return installedBundle;
    } finally {
        if (!isLocal) {
            try {
                new File(new URI(localUrl)).delete();
            } catch (URISyntaxException e) {
                throw Exceptions.propagate(e);
            }
        }
    }
}
 
Example #25
Source File: OsgiManager.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static Maybe<Framework> tryPeekFrameworkForReuse() {
    synchronized (OSGI_FRAMEWORK_CONTAINERS_FOR_REUSE) {
        if (!OSGI_FRAMEWORK_CONTAINERS_FOR_REUSE.isEmpty()) {
            return Maybe.of(OSGI_FRAMEWORK_CONTAINERS_FOR_REUSE.get(0));
        }
    }
    return Maybe.absent();
}
 
Example #26
Source File: OsgisTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    myBundle1_0_0 = Mockito.mock(Bundle.class);
    Mockito.when(myBundle1_0_0.getSymbolicName()).thenReturn("mybundle");
    Mockito.when(myBundle1_0_0.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    
    myBundle1_1_0 = Mockito.mock(Bundle.class);
    Mockito.when(myBundle1_1_0.getSymbolicName()).thenReturn("mybundle");
    Mockito.when(myBundle1_1_0.getVersion()).thenReturn(Version.parseVersion("1.1.0"));
    
    myBundle2_0_0 = Mockito.mock(Bundle.class);
    Mockito.when(myBundle2_0_0.getSymbolicName()).thenReturn("mybundle");
    Mockito.when(myBundle2_0_0.getVersion()).thenReturn(Version.parseVersion("2.0.0"));
    
    myBundle2_0_0_snapshot = Mockito.mock(Bundle.class);
    Mockito.when(myBundle2_0_0_snapshot.getSymbolicName()).thenReturn("mybundle");
    Mockito.when(myBundle2_0_0_snapshot.getVersion()).thenReturn(Version.parseVersion("2.0.0.SNAPSHOT"));
    
    otherBundle1_0_0 = Mockito.mock(Bundle.class);
    Mockito.when(otherBundle1_0_0.getSymbolicName()).thenReturn("otherbundle");
    Mockito.when(otherBundle1_0_0.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    
    snapshotBundle1_0_0_snapshot = Mockito.mock(Bundle.class);
    Mockito.when(snapshotBundle1_0_0_snapshot.getSymbolicName()).thenReturn("snapshotbundle");
    Mockito.when(snapshotBundle1_0_0_snapshot.getVersion()).thenReturn(Version.parseVersion("1.0.0.SNAPSHOT"));
    
    bundleContext = Mockito.mock(BundleContext.class);
    Mockito.when(bundleContext.getBundles()).thenReturn(new Bundle[] {myBundle1_0_0, myBundle1_1_0, myBundle2_0_0, 
            myBundle2_0_0_snapshot, otherBundle1_0_0, snapshotBundle1_0_0_snapshot});
    
    framework = Mockito.mock(Framework.class);
    Mockito.when(framework.getBundleContext()).thenReturn(bundleContext);
    
}
 
Example #27
Source File: ClassLoaderUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadClassInOsgiWhiteListWithInvalidBundlePresent() throws Exception {
    String bundlePath = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH;
    String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
    String classname = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_SIMPLE_ENTITY;
    
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), bundlePath);

    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = installBundle(mgmt, bundleUrl);
    
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    JarOutputStream target = new JarOutputStream(buffer, manifest);
    target.close();
    
    OsgiManager osgiManager = ((ManagementContextInternal)mgmt).getOsgiManager().get();
    Framework framework = osgiManager.getFramework();
    Bundle installedBundle = framework.getBundleContext().installBundle("stream://invalid", new ByteArrayInputStream(buffer.toByteArray()));
    assertNotNull(installedBundle);
    
    Class<?> clazz = bundle.loadClass(classname);
    Entity entity = createSimpleEntity(bundleUrl, clazz);
    
    String whileList = bundle.getSymbolicName()+":"+bundle.getVersion();
    System.setProperty(ClassLoaderUtils.WHITE_LIST_KEY, whileList);
    
    ClassLoaderUtils cluMgmt = new ClassLoaderUtils(getClass(), mgmt);
    ClassLoaderUtils cluClass = new ClassLoaderUtils(clazz);
    ClassLoaderUtils cluEntity = new ClassLoaderUtils(getClass(), entity);
    
    assertLoadSucceeds(classname, clazz, cluMgmt, cluClass, cluEntity);
    assertLoadSucceeds(bundle.getSymbolicName() + ":" + classname, clazz, cluMgmt, cluClass, cluEntity);
}
 
Example #28
Source File: ClassLoaderUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Bundle getBundle(ManagementContext mgmt, final String symbolicName) throws Exception {
    OsgiManager osgiManager = ((ManagementContextInternal)mgmt).getOsgiManager().get();
    Framework framework = osgiManager.getFramework();
    Maybe<Bundle> result = Osgis.bundleFinder(framework)
            .symbolicName(symbolicName)
            .find();
    return result.get();
}
 
Example #29
Source File: TestOsgi.java    From sensorhub with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void test1StartStopFramework() throws Exception
{
    Framework fw = getFramework();
    fw.start();
    Thread.sleep(500);
    fw.stop();
    fw.waitForStop(0);
}
 
Example #30
Source File: ClassLoaderFromStackOfBrooklynClassLoadingContextTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Bundle getBundle(ManagementContext mgmt, final String symbolicName) throws Exception {
    OsgiManager osgiManager = ((ManagementContextInternal)mgmt).getOsgiManager().get();
    Framework framework = osgiManager.getFramework();
    Maybe<Bundle> result = Osgis.bundleFinder(framework)
            .symbolicName(symbolicName)
            .find();
    return result.get();
}