/** * Simple method to parse META-INF/services file for framework factory. * Currently, it assumes the first non-commented line is the class name * of the framework factory implementation. * @return The created <tt>FrameworkFactory</tt> instance. * @throws Exception if any errors occur. **/ private static FrameworkFactory getFrameworkFactory() throws Exception { URL url = Main.class.getClassLoader().getResource( "META-INF/services/org.osgi.framework.launch.FrameworkFactory"); if (url != null) { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); try { for (String s = br.readLine(); s != null; s = br.readLine()) { s = s.trim(); // Try to load first non-empty, non-commented line. if ((s.length() > 0) && (s.charAt(0) != '#')) { return (FrameworkFactory) Class.forName(s).newInstance(); } } } finally { if (br != null) br.close(); } } throw new Exception("Could not find framework factory."); }
@Override public TestContainer[] create(ExamSystem system) { // we use ServiceLoader to load the OSGi Framework Factory List<TestContainer> containers = new ArrayList<>(); Iterator<FrameworkFactory> factories = ServiceLoader.load(FrameworkFactory.class) .iterator(); boolean factoryFound = false; while (factories.hasNext()) { try { containers.add(new MotechNativeTestContainer(system, factories.next())); factoryFound = true; } catch (IOException e) { throw new TestContainerException("Problem initializing container.", e); } } if (!factoryFound) { throw new TestContainerException( "No service org.osgi.framework.launch.FrameworkFactory found in META-INF/services on classpath"); } return containers.toArray(new TestContainer[containers.size()]); }
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(); } }
@Override public void start() { List<FrameworkFactory> frameworkFactories = IteratorUtils.toList(ServiceLoader.load(FrameworkFactory.class).iterator()); if (frameworkFactories.size() != 1) { throw new RuntimeException("One OSGi framework expected. Got " + frameworkFactories.size() + ": " + frameworkFactories); } try { framework = getFelixFramework(frameworkFactories); framework.start(); registerInternalServices(framework.getBundleContext()); } catch (BundleException e) { throw new RuntimeException("Failed to initialize OSGi framework", e); } }
private static FrameworkFactory getFrameworkFactory() throws Exception { java.net.URL url = FrameworkRunner.class.getClassLoader().getResource( "META-INF/services/org.osgi.framework.launch.FrameworkFactory"); if (url != null) { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); try { for (String s = br.readLine(); s != null; s = br.readLine()) { s = s.trim(); // Try to load first non-empty, non-commented line. if ((s.length() > 0) && (s.charAt(0) != '#')) { Debug.message("> FrameworkFactory class name: " + s); return (FrameworkFactory) Class.forName(s).newInstance(); } } } finally { if (br != null) br.close(); } } throw new Exception("Could not find framework factory."); }
@SuppressWarnings("deprecation") public OSGiFrameworkWrapper(File frameworkStorageDirectory, File bootBundlesDirectory, File hotBundlesDirectory) throws IOException { Map<String, String> config = new HashMap<>(); // https://svn.apache.org/repos/asf/felix/releases/org.apache.felix.main-1.2.0/doc/launching-and-embedding-apache-felix.html#LaunchingandEmbeddingApacheFelix-configproperty config.put("felix.embedded.execution", "true"); config.put(Constants.FRAMEWORK_EXECUTIONENVIRONMENT, "J2SE-1.8"); config.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); config.put(Constants.FRAMEWORK_STORAGE, frameworkStorageDirectory.getAbsolutePath()); // not FRAMEWORK_SYSTEMPACKAGES but _EXTRA config.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, new PackagesBuilder() .addPackage("org.slf4j", "1.7") .addPackage("ch.vorburger.minecraft.osgi.api") .addPackage("ch.vorburger.minecraft.utils") .addPackageWithSubPackages("com.google.common", "17.0.0") .addPackageWithSubPackages("com.flowpowered.math") .addPackageWithSubPackages("org.spongepowered.api") .addPackage("javax.inject") .addPackageWithSubPackages("com.google.inject") .build() ); FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next(); framework = frameworkFactory.newFramework(config); this.bootBundlesDirectory = bootBundlesDirectory; this.hotBundlesDirectory = hotBundlesDirectory; }
@BeforeClass public static void startOSGiContainer() throws BundleException, IOException { assertNull("OSGi framework is expected to be stopped.", osgiFramework); removeStorageDirectory(); Map<String, String> map = new HashMap<>(); map.put(Constants.FRAMEWORK_STORAGE, STORAGE_DIRECTORY); ServiceLoader<FrameworkFactory> frameworkFactory = ServiceLoader .load(FrameworkFactory.class); osgiFramework = frameworkFactory.iterator().next().newFramework(map); osgiFramework.start(); }
/** * Starts the OSGi framework, installs and starts the bundles. * * @throws BundleException * if the framework could not be started */ public void start() throws BundleException { logger.info("Loading the OSGi Framework Factory"); FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator() .next(); logger.info("Creating the OSGi Framework"); framework = frameworkFactory.newFramework(frameworkConfiguration); logger.info("Starting the OSGi Framework"); framework.start(); context = framework.getBundleContext(); context.addServiceListener(new ServiceListener() { public void serviceChanged(ServiceEvent event) { ServiceReference serviceReference = event.getServiceReference(); if (event.getType() == ServiceEvent.REGISTERED) { Object property = serviceReference .getProperty("org.springframework.context.service.name"); if (property != null) { addStartedSpringContext(property.toString()); } } logger.fine((event.getType() == ServiceEvent.REGISTERED ? "Registering : " : "Unregistering : ") + serviceReference); } }); installedBundles = installBundles(bundlesToInstall); List<Bundle> bundlesToStart = new ArrayList<Bundle>(); for (Bundle bundle : installedBundles) { if ("org.springframework.osgi.extender".equals(bundle.getSymbolicName())) { springOsgiExtender = bundle; } else { bundlesToStart.add(bundle); } } startBundles(bundlesToStart); }
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; }
private void initFramework(Properties properties) throws Exception{ String factoryClass = properties.getProperty(FrameworkFactory.class.getName()); if(factoryClass == null) throw new Exception("No FrameworkFactory available!"); FrameworkFactory frameworkFactory = (FrameworkFactory) Class.forName(factoryClass).newInstance(); Map<String, String> config = new HashMap<String, String>(); String runproperties = properties.getProperty("-runproperties"); if(runproperties!=null){ StringTokenizer st = new StringTokenizer(runproperties, ","); while(st.hasMoreTokens()){ String runproperty = st.nextToken(); int equalsIndex = runproperty.indexOf('='); if(equalsIndex!=-1){ String key = runproperty.substring(0, equalsIndex); String value = runproperty.substring(equalsIndex+1); config.put(key, value); } } } // point storage dir to internal storage config.put("org.osgi.framework.storage", (String)properties.getProperty("cacheDir")); // add framework exports config.put("org.osgi.framework.system.packages.extra", (String)properties.get("-runsystempackages")); framework = frameworkFactory.newFramework(config); framework.start(); }
/** * Starts a Carbon server instance. This method returns only after the server instance stops completely. * * @throws Exception if error occurred */ public void start() throws Exception { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Starting Carbon server instance."); } // Sets the server start time. System.setProperty(CARBON_START_TIME, Long.toString(System.currentTimeMillis())); try { // Creates an OSGi framework instance. ClassLoader fwkClassLoader = createOSGiFwkClassLoader(); FrameworkFactory fwkFactory = loadOSGiFwkFactory(fwkClassLoader); framework = fwkFactory.newFramework(config.getProperties()); setServerCurrentStatus(ServerStatus.STARTING); // Notify Carbon server start. dispatchEvent(CarbonServerEvent.STARTING); // Initialize and start OSGi framework. initAndStartOSGiFramework(framework); // Loads initial bundles listed in the launch.properties file. loadInitialBundles(framework.getBundleContext()); setServerCurrentStatus(ServerStatus.STARTED); // This thread waits until the OSGi framework comes to a complete shutdown. waitForServerStop(framework); setServerCurrentStatus(ServerStatus.STOPPING); // Notify Carbon server shutdown. dispatchEvent(CarbonServerEvent.STOPPING); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
/** * Creates a new service loader for the given service type and class loader. * Load OSGi framework factory for the given class loader. * * @param classLoader The class loader to be used to load provider-configurations * @return framework factory for creating framework instances */ private FrameworkFactory loadOSGiFwkFactory(ClassLoader classLoader) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Loading OSGi FrameworkFactory implementation class from the classpath."); } ServiceLoader<FrameworkFactory> loader = ServiceLoader.load(FrameworkFactory.class, classLoader); if (!loader.iterator().hasNext()) { throw new RuntimeException("An implementation of the " + FrameworkFactory.class.getName() + " must be available in the classpath"); } return loader.iterator().next(); }
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); }
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(); } }
@Before public void setUp() throws Exception { initMocks(this); FelixGoPluginOSGiFramework goPluginOSGiFramwork = new FelixGoPluginOSGiFramework(registry, systemEnvironment); spy = spy(goPluginOSGiFramwork); when(framework.getBundleContext()).thenReturn(bundleContext); when(registry.getPlugin(TEST_SYMBOLIC_NAME)).thenReturn(descriptor); doReturn(framework).when(spy).getFelixFramework(Matchers.<List<FrameworkFactory>>anyObject()); }
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(); } }
public void start ( final String[] args ) throws Exception { if ( this.started ) { return; } this.started = true; this.debug = Boolean.getBoolean ( "org.eclipse.scada.utils.osgi.daemon.debug" ); //$NON-NLS-1$ if ( this.debug ) { this.logger = new Formatter ( System.out ); } final ServiceLoader<FrameworkFactory> loader = ServiceLoader.load ( FrameworkFactory.class ); final Iterator<FrameworkFactory> i = loader.iterator (); if ( !i.hasNext () ) { throw new IllegalStateException ( "No FrameworkFactory found!" ); } final FrameworkFactory factory = i.next (); this.properties = new HashMap<String, String> (); for ( final String arg : args ) { final String[] toks = arg.split ( "=", 2 ); if ( toks.length >= 2 ) { this.properties.put ( toks[0], toks[1] ); } else { this.properties.put ( toks[0], null ); } } this.properties.put ( Constants.FRAMEWORK_BEGINNING_STARTLEVEL, "4" ); this.framework = factory.newFramework ( this.properties ); this.framework.init (); try { loadStartBundles ( this.framework, this.properties ); } catch ( final Exception e ) { this.framework.stop (); throw e; } this.framework.start (); }
public void start() { frame = new SplashFrame(); final SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() { protected Void doInBackground() throws Exception { try { String factoryClass = getFactoryClass(); FrameworkFactory factory = (FrameworkFactory) Class.forName(factoryClass).newInstance(); Framework framework = factory.newFramework(getLaunchProperties()); framework.start(); context = framework.getBundleContext(); BundleLoader loader = new BundleLoader(context); /* load embedded bundles, i.e. all bundles that are inside pathvisio.jar */ System.out.println("Installing bundles that are embedded in the jar."); Set<String> jarNames = loader.getResourceListing(PathVisioMain.class); int cnt = 0; int total = jarNames.size() + pluginLocations.size(); for (String s : jarNames) { String text = (s.length() > 50) ? s.substring(0, 50) : s; frame.getTextLabel().setText("<html>Install " + text + ".</html>"); frame.repaint(); publish(100 * (++cnt) / total); loader.installEmbeddedBundle(s); } frame.getTextLabel().setText("<html>Install active plugins.</html>"); frame.repaint(); System.out.println("Installing bundles from directories specified on the command-line."); for(String location : pluginLocations) { publish(100 * (++cnt) / total); loader.loadFromParameter(location); } startBundles(context, loader.getBundles()); frame.getTextLabel().setText("Start application."); frame.repaint(); } catch(Exception ex) { reportException("Startup Error", ex); ex.printStackTrace(); } return null; } protected void process(List<Integer> chunks) { for (Integer chunk : chunks) { frame.getProgressBar().setString("Installing modules..." + chunk + "%"); frame.getProgressBar().setValue(chunk); frame.repaint(); } } protected void done() { frame.setVisible(false); } }; worker.execute(); }
public MotechNativeTestContainer(ExamSystem system, FrameworkFactory frameworkFactory) throws IOException { super(system, frameworkFactory); examSystem = system; }
private Framework createFramework() throws IOException { final ServiceLoader<FrameworkFactory> factoryLoader = ServiceLoader.load(FrameworkFactory.class); final Iterator<FrameworkFactory> iterator = factoryLoader.iterator(); final FrameworkFactory next = iterator.next(); return next.newFramework(ConfigUtil.createFrameworkConfiguration()); }
@Override public void onCreate() { super.onCreate(); if(D) Log.d(TAG, "Setting up a thread for felix."); Thread felixThread = new Thread() { @Override public void run() { File dexOutputDir = getApplicationContext().getDir("transformationmanager", 0); // if default bundles were not installed already, install them File f = new File(dexOutputDir.getAbsolutePath()+"/bundle"); if(!f.isDirectory()) { if(D) Log.i(TAG, "Installing default bundles..."); unzipBundles(FelixService.this.getResources().openRawResource(R.raw.bundles), dexOutputDir.getAbsolutePath()+"/"); } FelixConfig felixConfig = new FelixConfig(dexOutputDir.getAbsolutePath()); Map<String, String> configProperties = felixConfig.getProperties2(); try { FrameworkFactory frameworkFactory = new org.apache.felix.framework.FrameworkFactory(); felixFramework = frameworkFactory.newFramework(configProperties); felixFramework.init(); AutoProcessor.process(configProperties,felixFramework.getBundleContext()); felixFramework.start(); // Registering the android context as an osgi service Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put("platform", "android"); felixFramework.getBundleContext().registerService( Context.class.getName(), getApplicationContext(), properties); } catch (Exception ex) { Log.e(TAG, "Felix could not be started", ex); ex.printStackTrace(); } } }; felixThread.setDaemon(true); felixThread.start(); LocalBroadcastManager.getInstance(this).registerReceiver(downloadReceiver, new IntentFilter(FELIX_SUCCESSFUL_WEB_REQUEST)); }
Framework getFelixFramework(List<FrameworkFactory> frameworkFactories) { return frameworkFactories.get(0).newFramework(generateOSGiFrameworkConfig()); }
private Framework startOSGiContainer(final String[] bundleLocations, final String tempDirPath) throws BundleException { FrameworkFactory frameworkFactory = ServiceLoader .load(FrameworkFactory.class).iterator().next(); Map<String, String> config = new HashMap<String, String>(); config.put("org.osgi.framework.system.packages", ""); config.put("osgi.configuration.area", tempDirPath); config.put("osgi.baseConfiguration.area", tempDirPath); config.put("osgi.sharedConfiguration.area", tempDirPath); config.put("osgi.instance.area", tempDirPath); config.put("osgi.user.area", tempDirPath); config.put("osgi.hook.configurators.exclude", "org.eclipse.core.runtime.internal.adaptor.EclipseLogHook"); Framework framework = frameworkFactory.newFramework(config); framework.init(); BundleContext systemBundleContext = framework.getBundleContext(); org.apache.maven.artifact.Artifact equinoxCompatibilityStateArtifact = pluginArtifactMap.get("org.eclipse.tycho:org.eclipse.osgi.compatibility.state"); URI compatibilityBundleURI = equinoxCompatibilityStateArtifact.getFile().toURI(); systemBundleContext.installBundle("reference:" + compatibilityBundleURI.toString()); framework.start(); for (String bundleLocation : bundleLocations) { try { systemBundleContext.installBundle(bundleLocation); } catch (BundleException e) { getLog().warn("Could not install bundle " + bundleLocation, e); } } FrameworkWiring frameworkWiring = framework .adapt(FrameworkWiring.class); frameworkWiring.resolveBundles(null); return framework; }
private static void initFelixFramework() throws IOException, BundleException { Properties configProps = _loadOsgiConfigProperties(); // configure Felix auto-deploy directory String sAutoDeployDir = configProps.getProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY); if (sAutoDeployDir == null) { throw new RuntimeException("Can not find configuration [" + AutoProcessor.AUTO_DEPLOY_DIR_PROPERY + "] in file " + OSGiSERVER_OSGI_PROPERTIES.getAbsolutePath()); } File fAutoDeployDir = new File(OSGiSERVER_HOME, sAutoDeployDir); if (LOGGER.isDebugEnabled()) { LOGGER.debug(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY + ": " + fAutoDeployDir.getAbsolutePath()); } configProps.setProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, fAutoDeployDir.getAbsolutePath()); // configure Felix temp (storage) directory String sCacheDir = configProps.getProperty(Constants.FRAMEWORK_STORAGE); if (sCacheDir == null) { throw new RuntimeException("Can not find configuration [" + Constants.FRAMEWORK_STORAGE + "] in file " + OSGiSERVER_OSGI_PROPERTIES.getAbsolutePath()); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug(Constants.FRAMEWORK_STORAGE + ": " + sCacheDir); } File fCacheDir = new File(OSGiSERVER_HOME, sCacheDir); configProps.setProperty(Constants.FRAMEWORK_STORAGE, fCacheDir.getAbsolutePath()); // configure Felix's File Install watch directory final String PROP_FELIX_FILE_INSTALL_DIR = "felix.fileinstall.dir"; String sMonitorDir = configProps.getProperty(PROP_FELIX_FILE_INSTALL_DIR); if (sMonitorDir != null) { File fMonitorDir = new File(OSGiSERVER_HOME, sMonitorDir); configProps.setProperty(PROP_FELIX_FILE_INSTALL_DIR, fMonitorDir.getAbsolutePath()); if (LOGGER.isDebugEnabled()) { LOGGER.debug(PROP_FELIX_FILE_INSTALL_DIR + ": " + fMonitorDir.getAbsolutePath()); } } // check for Felix's Remote Shell listen IP & Port if (LOGGER.isDebugEnabled()) { String remoteShellListenIp = configProps.getProperty("osgi.shell.telnet.ip"); String remoteShellListenPort = configProps.getProperty("osgi.shell.telnet.port"); LOGGER.debug("Remote Shell: " + remoteShellListenIp + ":" + remoteShellListenPort); } Map<String, String> config = new HashMap<String, String>(); for (Entry<Object, Object> entry : configProps.entrySet()) { config.put(entry.getKey().toString(), entry.getValue().toString()); } FrameworkFactory factory = new org.apache.felix.framework.FrameworkFactory(); framework = factory.newFramework(config); framework.init(); AutoProcessor.process(configProps, framework.getBundleContext()); _autoDeployBundles(fAutoDeployDir, framework); framework.start(); }
public OsgiTestRule(final FrameworkFactory factory) { this.factory = factory; }
@Override protected FrameworkFactory getFactory() { return new org.apache.felix.framework.FrameworkFactory(); }
@Override protected FrameworkFactory getFactory() { return new EquinoxFactory(); }
protected abstract FrameworkFactory getFactory();