Java 类org.osgi.framework.launch.Framework 实例源码

项目:gemini.blueprint    文件:DefaultFrameworkTemplate.java   
public DefaultFrameworkTemplate(Object target, Log log) {
    if (OsgiPlatformDetector.isR42()) {
        Assert.isInstanceOf(Framework.class, target);
        fwk = (Framework) target;
    } else {
        throw new IllegalStateException("Cannot use OSGi 4.2 Framework API in an OSGi 4.1 environment");
    }
    this.log = log;
}
项目:sensorhub    文件:TestOsgi.java   
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;
}
项目:sensorhub    文件:TestOsgi.java   
@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);
}
项目:sensorhub    文件:TestOsgi.java   
@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);
}
项目:guice    文件:OSGiContainerTest.java   
public void testGuiceWorksInOSGiContainer() throws Throwable {

    // ask framework to clear cache on startup
    Properties properties = new Properties();
    properties.setProperty("org.osgi.framework.storage", BUILD_TEST_DIR + "/bundle.cache");
    properties.setProperty("org.osgi.framework.storage.clean", "onFirstInit");

    // test each available OSGi framework in turn
    for (FrameworkFactory frameworkFactory : ServiceLoader.load(FrameworkFactory.class)) {
      Framework framework = frameworkFactory.newFramework(properties);

      framework.start();
      BundleContext systemContext = framework.getBundleContext();

      // load all the necessary bundles and start the OSGi test bundle
      /*if[AOP]*/
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/aopalliance.jar");
      /*end[AOP]*/
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/javax.inject.jar");
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/guava.jar");
      systemContext.installBundle("reference:file:" + GUICE_JAR);
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/osgitests.jar").start();

      framework.stop();
    }
  }
项目:carbon-kernel    文件:CarbonServer.java   
/**
 * 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.");
    }
}
项目:carbon-kernel    文件:CarbonServer.java   
/**
 * 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;
        }
    }
}
项目:osgiserver    文件:StandaloneBootstrap.java   
private static void _autoDeployBundles(File fileOrDir, Framework framework)
        throws FileNotFoundException, BundleException {
    if (fileOrDir.isFile() && fileOrDir.getName().endsWith(".jar")) {
        _deployBundle(fileOrDir.getName(), fileOrDir);
    } else {
        // make sure bundles are deployed and started in order!
        File[] files = fileOrDir.listFiles();
        if (files != null && files.length > 0) {
            Arrays.sort(files, new Comparator<File>() {
                @Override
                public int compare(File file1, File file2) {
                    return file1.compareTo(file2);
                }
            });
            for (File f : files) {
                if (!f.getName().startsWith(".")) {
                    _autoDeployBundles(f, framework);
                }
            }
        }
    }
}
项目:incubator-netbeans    文件:Netigso.java   
@Override
protected ClassLoader findFrameworkClassLoader() {
    ClassLoader l = frameworkLoader;
    if (l != null) {
        return l;
    }
    Framework f = framework;
    if (f != null) {
        return frameworkLoader = f.getClass().getClassLoader();
    }
    return getClass().getClassLoader();
}
项目:incubator-netbeans    文件:Netigso.java   
private static Set<String> toActivate(Framework f, Collection<? extends Module> allModules) {
    ServiceReference sr = f.getBundleContext().getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); // NOI18N
    if (sr == null) {
        return null;
    }
    PackageAdmin pkgAdm = (PackageAdmin)f.getBundleContext().getService(sr);
    if (pkgAdm == null) {
        return null;
    }
    Set<String> allCnbs = new HashSet<String>(allModules.size() * 2);
    for (ModuleInfo m : allModules) {
        allCnbs.add(m.getCodeNameBase());
    }

    Set<String> needEnablement = new HashSet<String>();
    for (Bundle b : f.getBundleContext().getBundles()) {
        String loc = b.getLocation();
        if (loc.startsWith("netigso://")) {
            loc = loc.substring("netigso://".length());
        } else {
            continue;
        }
        RequiredBundle[] arr = pkgAdm.getRequiredBundles(loc);
        if (arr != null) for (RequiredBundle rb : arr) {
            for (Bundle n : rb.getRequiringBundles()) {
                if (allCnbs.contains(n.getSymbolicName().replace('-', '_'))) {
                    needEnablement.add(loc);
                }
            }
        }
    }
    return needEnablement;
}
项目:incubator-netbeans    文件:NetigsoServices.java   
NetigsoServices(Netigso netigso, Framework f) {
    this.netigso = netigso;
    for (ServiceReference ref : f.getRegisteredServices()) {
        MainLookup.register(ref, this);
    }
    f.getBundleContext().addServiceListener(this);
    f.getBundleContext().addBundleListener(this);
}
项目:incubator-netbeans    文件:IntegrationTest.java   
@RandomlyFails // NB-Core-Build #8007: Framework found
public void testCheckWhichContainerIsRunning() throws Exception {
    ModuleManager mgr = Main.getModuleSystem().getManager();
    Module m1;
    mgr.mutexPrivileged().enterWriteAccess();
    try {
        String mf = "Bundle-SymbolicName: org.foo\n" +
            "Bundle-Version: 1.1.0\n" +
            "Bundle-ManifestVersion: 2\n" +
            "Export-Package: org.foo";

        LOG.info("about to enable module org.foo");
        File jj1 = NetigsoHid.changeManifest(getWorkDir(), j1, mf);
        m1 = mgr.create(jj1, null, false, false, false);
        mgr.enable(m1);
        LOG.info("Enabling is over");

        assertTrue("OSGi module is now enabled", m1.isEnabled());
    } finally {
        mgr.mutexPrivileged().exitWriteAccess();
    }

    Framework w = NetigsoUtil.framework(mgr);
    assertNotNull("Framework found", w);
    if (!w.getClass().getName().contains("felix")) {
        fail("By default the OSGi framework is felix: " + w.getClass());
    }


    ClassLoader fwloader = w.getClass().getClassLoader();
    Method addURLMethod = howEclipseFindsMethodToSupportFrameworks(fwloader.getClass());

    assertNotNull("addURL method found", addURLMethod);
}
项目:incubator-netbeans    文件:NetigsoUtil.java   
public static Framework framework(ModuleManager mgr) throws Exception {
    final Method nm = mgr.getClass().getDeclaredMethod("netigso");
    nm.setAccessible(true);
    final Netigso netigso = (Netigso) nm.invoke(mgr);
    Method m = Netigso.class.getDeclaredMethod("getFramework");
    m.setAccessible(true);
    Framework f = (Framework) m.invoke(netigso);
    return f;
}
项目:incubator-netbeans    文件:NetigsoUtil.java   
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;
}
项目:incubator-netbeans    文件:NetigsoSelfQueryTest.java   
@Override
public Framework newFramework(Map map) {
    NetigsoArchive archive = (NetigsoArchive) map.get("netigso.archive");
    assertNotNull("archive provided", archive);
    AtomicReference<BundleContext> ar = new AtomicReference<BundleContext>();
    return (Framework) delegate(new MockFramework(archive, ar), ar, Framework.class, BundleContext.class);
}
项目:incubator-netbeans    文件:NetigsoServicesTest.java   
public static Framework findFramework() {
    try {
        return NetigsoUtil.framework(Main.getModuleSystem().getManager());
    } catch (Exception ex) {
        throw new AssertionError(ex);
    }
}
项目:incubator-netbeans    文件:NetigsoStartLevelTest.java   
public void testActivation() throws Exception {
    ModuleSystem ms = Main.getModuleSystem();
    mgr = ms.getManager();
    mgr.mutexPrivileged().enterWriteAccess();
    try {
        m1 = mgr.createBundle(simpleModule, null, false, false, false, 10);
        mgr.enable(m1);
    } finally {
        mgr.mutexPrivileged().exitWriteAccess();
    }

    Class<?> main = m1.getClassLoader().loadClass("org.activate.Main");
    Object s = main.getField("start").get(null);
    assertNull("Not started yet", s);

    Framework f = NetigsoServicesTest.findFramework();
    final BundleContext fc = f.getBundleContext();
    fc.addFrameworkListener(this);
    ServiceReference sr = fc.getServiceReference(StartLevel.class.getName());
    assertNotNull("Start level service found", sr);
    StartLevel level = (StartLevel) fc.getService(sr);
    assertNotNull("Start level found", level);
    level.setStartLevel(10);
    waitLevelChanged();

    s = main.getField("start").get(null);
    assertNotNull("Bundle started, its context provided", s);

    mgr.mutexPrivileged().enterWriteAccess();
    try {
        mgr.disable(m1);

        Object e = main.getField("stop").get(null);
        assertNotNull("Bundle stopped, its context provided", e);
    } finally {
        mgr.mutexPrivileged().exitWriteAccess();
    }
}
项目:incubator-netbeans    文件:Activator.java   
public @Override void start(final BundleContext context) throws Exception {
        if (System.getProperty("netbeans.home") != null) {
            throw new IllegalStateException("Should not be run from inside regular NetBeans module system");
        }
        String storage = context.getProperty(Constants.FRAMEWORK_STORAGE);
        if (storage != null) {
            System.setProperty("netbeans.user", storage);
        }
        System.setProperty("TopSecurityManager.disable", "true");
        NbBundle.setBranding(System.getProperty("branding.token"));
        OSGiMainLookup.initialize(context);
        queue = new DependencyQueue<String,Bundle>();
        this.context = context;
        framework = ((Framework) context.getBundle(0));
        if (framework.getState() == Bundle.STARTING) {
            LOG.fine("framework still starting");
            final AtomicReference<FrameworkListener> frameworkListener = new AtomicReference<FrameworkListener>();
            frameworkListener.set(new FrameworkListener() {
                public @Override void frameworkEvent(FrameworkEvent event) {
                    if (event.getType() == FrameworkEvent.STARTED) {
//                        System.err.println("framework started");
                        context.removeFrameworkListener(frameworkListener.get());
                        context.addBundleListener(Activator.this);
                        processLoadedBundles();
                    }
                }
            });
            context.addFrameworkListener(frameworkListener.get());
        } else {
            LOG.fine("framework already started");
            context.addBundleListener(this);
            processLoadedBundles();
        }
    }
项目:incubator-netbeans    文件:IntegrationTest.java   
public void testCheckWhichContainerIsRunning() throws Exception {
    ModuleManager mgr = Main.getModuleSystem().getManager();
    mgr.mutexPrivileged().enterWriteAccess();
    Module m1;
    String mf = "Bundle-SymbolicName: org.foo\n" +
        "Bundle-Version: 1.1.0\n" +
        "Bundle-ManifestVersion: 2\n" +
        "Export-Package: org.foo";

    File jj1 = NetigsoHid.changeManifest(getWorkDir(), j1, mf);
    m1 = mgr.create(jj1, null, false, false, false);
    mgr.enable(m1);

    assertTrue("OSGi module is now enabled", m1.isEnabled());
    mgr.mutexPrivileged().exitWriteAccess();
    Framework w = findFramework();
    assertNotNull("Framework found", w);
    assertEquals("Felix is not in its name", -1, w.getClass().getName().indexOf("felix"));
    StringBuilder sb = new StringBuilder();
    for (Bundle b : w.getBundleContext().getBundles()) {
        sb.append("\n").append(b.getSymbolicName());
        if (b.getSymbolicName().equals("org.eclipse.osgi")) {
            return;
        }
    }
    fail("Expecting equinox among list of enabled bundles:" + sb);
}
项目:incubator-netbeans    文件:LogReaderServiceTest.java   
public void testExtendedLogReaderServiceAvailable() throws Exception {
    Framework f = IntegrationTest.findFramework();
    BundleContext bc = f.getBundleContext();

    ServiceTracker logReaderTracker = new ServiceTracker(bc, ExtendedLogReaderService.class.getName(), null);
    logReaderTracker.open();

    LogReaderService logReader = (ExtendedLogReaderService) logReaderTracker.getService();
    assertNotNull(logReader);

}
项目:incubator-netbeans    文件:CachingAndExternalPathsTest.java   
public void testTeaseTheSystemWithFileLocatorBundleFile() throws Exception {
    Framework f = findFramework();
    Method getBundleFile;
    try {
        getBundleFile = Class.forName("org.eclipse.core.runtime.FileLocator").getMethod("getBundleFile", Bundle.class);
    } catch (Exception ex) {
        LOG.log(Level.INFO, "Skipping the " + getName() + " test", ex);
        return;
    }
    for (Bundle b : f.getBundleContext().getBundles()) {
        File file = (File) getBundleFile.invoke(null, b);
        assertNotNull("Some file is found", file);
    }
}
项目:incubator-netbeans    文件:NetigsoHasSAXParserTest.java   
public void testSAXParserAvailable() throws Exception {
    Framework f = IntegrationTest.findFramework();
    BundleContext bc = f.getBundleContext();

    ServiceReference sr = bc.getServiceReference(SAXParserFactory.class.getName());
    assertNotNull("SAX Service found", sr);
    Object srvc = bc.getService(sr);
    assertTrue("Instance of the right type: " + srvc, srvc instanceof SAXParserFactory);

}
项目:neoscada    文件:Starter.java   
private void loadStartBundles ( final Framework framework, final Map<String, String> properties )
{
    final String bundles = getProperty ( PROP_OSGI_BUNDLES );
    if ( bundles == null || bundles.isEmpty () )
    {
        return;
    }

    final Map<String, Bundle> best = getBestBundles ( findRoot () );
    for ( final String bundle : bundles.split ( PATTERN_BUNDLES_SPLITTER ) )
    {
        processBundle ( framework, bundle, best );
    }
}
项目:nexus-public    文件:LauncherActivator.java   
public void start(final BundleContext bundleContext) throws Exception {
  framework = (Framework) bundleContext.getBundle(0);
  ShutdownHelper.setDelegate(this);

  final String baseDir = checkProperty(bundleContext, "karaf.base");
  final String dataDir = checkProperty(bundleContext, "karaf.data");

  final File defaultsFile = new File(baseDir, "etc/nexus-default.properties");
  final File propertiesFile = new File(dataDir, "etc/nexus.properties");
  final File nodeNamePropertiesFile = new File(dataDir, "etc/node-name.properties");

  maybeCopyDefaults(defaultsFile, propertiesFile);

  MDC.put("userId", SYSTEM_USERID);
  launcher = new Launcher(defaultsFile, propertiesFile, nodeNamePropertiesFile);
  launcher.startAsync(
      () -> {
        connectorConfigurationTracker = new ConnectorConfigurationTracker(
            bundleContext,
            launcher.getServer()
        );
        connectorConfigurationTracker.open();
      }
  );

  final Dictionary<String, ?> properties = new Hashtable<>(singletonMap("name", "nexus"));
  jettyServerConfigurationRegistration = bundleContext.registerService(
      JettyServerConfiguration.class,
      new JettyServerConfiguration(launcher.getServer().defaultConnectors()),
      properties
  );
}
项目:osgi-in-action    文件:Main.java   
/**
 * Creates a framework instance using the standard META-INF/services approach.
 * The created instance is configured to start with a clean cache and for the
 * system bundle to export the shape API. All bundles located in the "bundles"
 * directory are installed and started.
 * @return the created framework instance.
 * @throws Exception if any error occurs.
 */
private static Framework createFramework() throws Exception {
  // Look in the "bundles" directory to create a list
  // of all JAR files to install.
  File[] files = new File("bundles").listFiles();
  Arrays.sort(files);
  List jars = new ArrayList();
  for (int i = 0; i < files.length; i++)
    if (files[i].getName().toLowerCase().endsWith(".jar"))
      jars.add(files[i]);

  try {
    // Create, configure, and start an OSGi framework instance
    // using the ServiceLoader to get a factory.
    List bundleList = new ArrayList();
    Map m = new HashMap();
    m.putAll(System.getProperties());
    m.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    m.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.foo.shape; version=\"4.0.0\"");
    fwk = getFrameworkFactory().newFramework(m);
    fwk.start();
    // Install bundle JAR files and remember the bundle objects.
    BundleContext ctxt = fwk.getBundleContext();
    for (int i = 0; i < jars.size(); i++) {
      Bundle b = ctxt.installBundle(((File) jars.get(i)).toURI().toString());
      bundleList.add(b);
    }
    // Start all installed bundles.
    for (int i = 0; i < bundleList.size(); i++) {
      ((Bundle) bundleList.get(i)).start();
    }
  } catch (Exception ex) {
    System.err.println("Error starting framework: " + ex);
    ex.printStackTrace();
    System.exit(0);
  }

  return fwk;
}
项目:ApkLauncher    文件:FrameworkHelper.java   
void registerListener(Framework f) {
    f.getBundleContext().addBundleListener(new BundleListener() {

        @Override
        public void bundleChanged(BundleEvent e) {
            Log.d(TAG, "bundleChanged. event:" + e);

        }
    });
}
项目:motech    文件:MotechNativeTestContainer.java   
protected Framework getFramework() {
    // We need the framework field declared in our superclass, but the exam creators did not think about us
    // and made it a private field. No matter, we get it through reflection.
    try {
        Field frameworkField = getClass().getSuperclass().getDeclaredField("framework");
        frameworkField.setAccessible(true);
        return (Framework) ReflectionUtils.getField(frameworkField, this);
    } catch (NoSuchFieldException e) {
        throw new IllegalStateException("Unable to access the framework field from super", e);
    }
}
项目:sensorhub    文件:TestOsgi.java   
protected Framework getFramework()
{
    Iterator<FrameworkFactory> it = ServiceLoader.load(org.osgi.framework.launch.FrameworkFactory.class).iterator();
    assertTrue("No OSGI implementation found in classpath", it.hasNext());

    Map<String,String> osgiConfig = new HashMap<String,String>();
    //osgiConfig.put(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, "");
    osgiConfig.put("org.osgi.framework.storage", CACHE_FOLDER);
    osgiConfig.put("org.osgi.framework.storage.clean", "onFirstInit");
    Framework fw = it.next().newFramework(osgiConfig);

    return fw;
}
项目:sensorhub    文件:TestOsgi.java   
@Test
public void test1StartStopFramework() throws Exception
{
    Framework fw = getFramework();
    fw.start();
    Thread.sleep(500);
    fw.stop();
    fw.waitForStop(0);
}
项目:ph-commons    文件:SimpleLSResourceResolverTest.java   
@Test
public void testOSGIBundle () throws BundleException
{
  LSInput aRes;

  // Initializing Apache Felix as OSGI container is required to get the
  // "bundle" URL protocol installed correctly
  // Otherwise the first call would end up as a "file" resource ;-)
  final Framework aOSGI = new FrameworkFactory ().newFramework (new HashMap <String, String> ());
  aOSGI.start ();
  try
  {
    // Bundle 0 is the org.apache.felix.framework bundle
    final Bundle b = aOSGI.getBundleContext ().getBundle (0);
    assertNotNull (b);
    assertEquals (b.getState (), Bundle.ACTIVE);

    // No leading slash is important as the ClassLoader is used!
    assertNotNull (b.getResource ("org/apache/felix/framework/util/Mutex.class"));

    final LSResourceResolver aRR = new SimpleLSResourceResolver ();

    // No class loader
    aRes = aRR.resolveResource (XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                null,
                                null,
                                "../Felix.class",
                                "bundle://0.0:1/org/apache/felix/framework/util/Mutex.class");
    assertTrue (aRes instanceof ResourceLSInput);
    final IHasInputStream aISP = ((ResourceLSInput) aRes).getInputStreamProvider ();
    assertTrue (aISP instanceof URLResource);
    // Path maybe a "jar:file:" resource
    assertTrue (((URLResource) aISP).getPath ().endsWith ("org/apache/felix/framework/Felix.class"));
  }
  finally
  {
    aOSGI.stop ();
  }
}
项目:pipeline-gui    文件:GUIService.java   
public void stopGUI(){
        try {
                ((Framework) this.ctxt.getBundle(0)).stop();
        } catch (BundleException e) {
                logger.error("Error closing the framework ",e);
                //exit the hard way
                System.exit(-1);
        }
}
项目:planetBot    文件:Launcher.java   
private void initialize() throws BundleException, URISyntaxException {

        Map<String, String> configMap = loadProperties();
        System.setProperty(LOG_CONFIG_FILE_PROPERTY, configMap.get(LOG_CONFIG_FILE_PROPERTY));

        System.out.println("Building OSGi Framework");
        FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
        Framework framework = frameworkFactory.newFramework(configMap);

        framework.init();
        // (9) Use the system bundle context to process the auto-deploy
        // and auto-install/auto-start properties.
        AutoProcessor.process(configMap, framework.getBundleContext());
        // (10) Start the framework.
        System.out.println("Starting OSGi Framework");
        framework.start();

        BundleContext context = framework.getBundleContext();
        // declarative services dependency is necessary, otherwise they won't be picked up!
        loadScrBundle(context);

        try {
            framework.waitForStop(0);
        } catch (InterruptedException e) {
            appendToFile(e);
            showErrorMessage();
        }
        System.exit(0);
    }
项目:guice-old    文件:OSGiContainerTest.java   
public void testGuiceWorksInOSGiContainer()
      throws Throwable {

    // ask framework to clear cache on startup
    Properties properties = new Properties();
    properties.setProperty("org.osgi.framework.storage", BUILD_TEST_DIR + "/bundle.cache");
    properties.setProperty("org.osgi.framework.storage.clean", "onFirstInit");

    // test each available OSGi framework in turn
    Iterator<FrameworkFactory> f = ServiceRegistry.lookupProviders(FrameworkFactory.class);
    while (f.hasNext()) {
      Framework framework = f.next().newFramework(properties);

      framework.start();
      BundleContext systemContext = framework.getBundleContext();

      // load all the necessary bundles and start the OSGi test bundle
/*if[AOP]*/
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/aopalliance.jar");
/*end[AOP]*/
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/javax.inject.jar");
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/guava.jar");
      systemContext.installBundle("reference:file:" + GUICE_JAR);
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/osgitests.jar").start();

      framework.stop();
    }
  }
项目:osgi_in_action-    文件:Main.java   
/**
 * Creates a framework instance using the standard META-INF/services approach.
 * The created instance is configured to start with a clean cache and for the
 * system bundle to export the shape API. All bundles located in the "bundles"
 * directory are installed and started.
 * @return the created framework instance.
 * @throws Exception if any error occurs.
 */
private static Framework createFramework() throws Exception {
  // Look in the "bundles" directory to create a list
  // of all JAR files to install.
  File[] files = new File("bundles").listFiles();
  Arrays.sort(files);
  List jars = new ArrayList();
  for (int i = 0; i < files.length; i++)
    if (files[i].getName().toLowerCase().endsWith(".jar"))
      jars.add(files[i]);

  try {
    // Create, configure, and start an OSGi framework instance
    // using the ServiceLoader to get a factory.
    List bundleList = new ArrayList();
    Map m = new HashMap();
    m.putAll(System.getProperties());
    m.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    m.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.foo.shape; version=\"4.0.0\"");
    fwk = getFrameworkFactory().newFramework(m);
    fwk.start();
    // Install bundle JAR files and remember the bundle objects.
    BundleContext ctxt = fwk.getBundleContext();
    for (int i = 0; i < jars.size(); i++) {
      Bundle b = ctxt.installBundle(((File) jars.get(i)).toURI().toString());
      bundleList.add(b);
    }
    // Start all installed bundles.
    for (int i = 0; i < bundleList.size(); i++) {
      ((Bundle) bundleList.get(i)).start();
    }
  } catch (Exception ex) {
    System.err.println("Error starting framework: " + ex);
    ex.printStackTrace();
    System.exit(0);
  }

  return fwk;
}
项目:google-guice    文件:OSGiContainerTest.java   
public void testGuiceWorksInOSGiContainer()
      throws Throwable {

    // ask framework to clear cache on startup
    Properties properties = new Properties();
    properties.setProperty("org.osgi.framework.storage", BUILD_TEST_DIR + "/bundle.cache");
    properties.setProperty("org.osgi.framework.storage.clean", "onFirstInit");

    // test each available OSGi framework in turn
    Iterator<FrameworkFactory> f = ServiceRegistry.lookupProviders(FrameworkFactory.class);
    while (f.hasNext()) {
      Framework framework = f.next().newFramework(properties);

      framework.start();
      BundleContext systemContext = framework.getBundleContext();

      // load all the necessary bundles and start the OSGi test bundle
/*if[AOP]*/
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/aopalliance.jar");
/*end[AOP]*/
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/javax.inject.jar");
      systemContext.installBundle("reference:file:" + GUICE_JAR);
      systemContext.installBundle("reference:file:" + BUILD_TEST_DIR + "/osgitests.jar").start();

      framework.stop();
    }
  }
项目:felix-on-android    文件:FelixWrapper.java   
public static void registerListener(Framework f) {
    f.getBundleContext().addBundleListener(new BundleListener(){

        @Override
        public void bundleChanged(BundleEvent e) {
            Log.d(TAG, "bundleChanged. e:" + e);

        }});
}
项目:mvn-osgi-library-2013    文件:MainFrame.java   
public void exit() {
    try {
        Bundle bnd = context.getBundle(0);
        Framework fw = (Framework) bnd;
        fw.stop();
        fw.waitForStop(0);
    } catch (BundleException | InterruptedException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.INFO, null, ex);
    }
}
项目:incubator-netbeans    文件:Netigso.java   
Framework getFramework() {
    return framework;
}
项目:incubator-netbeans    文件:NetbinoxFactory.java   
@Override
    @SuppressWarnings("unchecked")
    public Framework newFramework(Map map) {
        Map<String,Object> configMap = new HashMap<String,Object>();
        configMap.putAll(map);
//        configMap.put("osgi.hook.configurators.exclude", // NOI18N
//            "org.eclipse.core.runtime.internal.adaptor.EclipseLogHook" // NOI18N
////            + ",org.eclipse.core.runtime.internal.adaptor.EclipseClassLoadingHook" // NOI18N
//        );
        configMap.put("osgi.hook.configurators.include", NetbinoxHooks.class.getName()); // NOI18N
        final String userArea = toFileURL(System.getProperty("netbeans.user"));
        configMap.put("osgi.user.area.default", userArea); // NOI18N
        configMap.put("osgi.user.area", userArea); // NOI18N
        configMap.put("osgi.instance.area", userArea); // NOI18N
        configMap.put("osgi.instance.area.default", userArea); // NOI18N
        final String installArea = toFileURL(findInstallArea());
        LOG.log(Level.INFO, "Install area set to {0}", installArea); // NOI18N
        configMap.put("osgi.install.area", installArea); // NOI18N
        // some useless value
        configMap.put("osgi.framework.properties", System.getProperty("netbeans.user")); // NOI18N
        // don't change classloader when getting XMLParsers
        configMap.put("eclipse.parsers.setTCCL", "false"); // NOI18N
        configMap.put(Constants.FRAMEWORK_STORAGE, toFileURL(
            (String)map.get(Constants.FRAMEWORK_STORAGE)
        ));
        if (System.getProperty("osgi.locking") == null) { // NOI18N
            configMap.put("osgi.locking", "none"); // NOI18N
        }

        Object rawBundleMap = configMap.get("felix.bootdelegation.classloaders"); // NOI18N

        Map<Bundle,ClassLoader> bundleMap;
        if (rawBundleMap == null) {
            bundleMap = null;
        } else {
            bundleMap = (Map<Bundle,ClassLoader>)rawBundleMap;
        }

        NetbinoxHooks.registerMap(bundleMap);
        NetbinoxHooks.registerArchive((NetigsoArchive)configMap.get("netigso.archive")); // NOI18N

        String loc = EquinoxFactory.class.getProtectionDomain().getCodeSource().getLocation().toExternalForm();
        int file = loc.indexOf("file:");
        if (file > 0) {
            loc = loc.substring(file);
        }
        int exclaim = loc.indexOf("!");
        if (exclaim > 0) {
            loc = loc.substring(0, exclaim);
        }
        configMap.put("osgi.framework", loc);
        return new Netbinox(configMap);
    }
项目:incubator-netbeans    文件:IntegrationTest.java   
static Framework findFramework() throws Exception {
    return NetigsoUtil.framework(Main.getModuleSystem().getManager());
}