@Test public void testNativeCodeExecPermission() throws Exception { String tempFileName = System.getProperty("java.io.tmpdir") + "/osgi_native" + System.currentTimeMillis() + ".test"; File tempFile = new File(tempFileName); try { Map<String, String> props = new HashMap<String, String>(); props.put("org.osgi.framework.storage", "target/osgi-store"); props.put("org.osgi.framework.storage.clean", "onFirstInit"); // Execute this command for every native library found in the bundle props.put("org.osgi.framework.command.execpermission", "cp ${abspath} " + tempFileName); FrameworkFactory factory = ServiceLoader.loadService(FrameworkFactory.class); Framework framework = factory.newFramework(props); framework.start(); assertFalse("Precondition", tempFile.exists()); Bundle bundle = framework.getBundleContext().installBundle(getTestArchivePath("simple-nativecode.jar")); bundle.start(); assertTrue(tempFile.exists()); framework.stop(); framework.waitForStop(2000); } finally { tempFile.delete(); } }
@SuppressWarnings("unchecked") private <T> T getService(Class<T> serviceType, String filter, long timeout) throws TestContainerException { assert m_framework != null : "Framework should be up"; assert serviceType != null : "serviceType not be null"; final Long start = System.currentTimeMillis(); LOG.info("Aquiring Service " + serviceType.getName() + " " + (filter != null ? filter : "")); do { try { ServiceReference[] reference = m_framework.getBundleContext().getServiceReferences(serviceType.getName(), filter); if (reference != null && reference.length > 0) { return ((T) m_framework.getBundleContext().getService(reference[0])); } Thread.sleep(200); } catch (Exception e) { LOG.error("Some problem during looking up service from framework: " + m_framework, e); } // wait a bit } while ((System.currentTimeMillis()) < start + timeout); printAvailableAlternatives(serviceType); throw new TestContainerException( "Not found a matching Service " + serviceType.getName() + " for Filter:" + (filter != null ? filter : "")); }
@Override protected void tearDown() throws Exception { framework.stop(); framework.waitForStop(10000); IO.delete(tmp); super.tearDown(); }
@Override public void destroy() throws Exception { if (framework != null) { framework.stop(); framework.waitForStop(0); } }
@Override protected void setUp() throws Exception { tmp = IO.getFile("generated/tmp"); tmp.mkdirs(); configuration = new HashMap<String, Object>(); configuration.put( Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); configuration.put(Constants.FRAMEWORK_STORAGE, new File(tmp, "fwstorage").getAbsolutePath()); configuration.put( Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.4"); framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration); framework.init(); framework.start(); BundleContext context = framework.getBundleContext(); String[] bundles = { "../cnf/repo/osgi.cmpn/osgi.cmpn-4.3.1.jar", "testdata/slf4j-simple-1.7.12.jar", "testdata/slf4j-api-1.7.12.jar", "testdata/org.apache.aries.util-1.1.0.jar", "testdata/org.apache.aries.jmx-1.1.1.jar", "generated/biz.aQute.remote.test.jmx.jar" }; for (String bundle : bundles) { String location = "reference:" + IO.getFile(bundle).toURI().toString(); Bundle b = context.installBundle(location); if (!bundle.contains("slf4j-simple")) { b.start(); } } super.setUp(); }
public static void main(String[] args) { try { ServiceLoader<FrameworkFactory> loader = ServiceLoader.load(FrameworkFactory.class); FrameworkFactory factory = loader.iterator().next(); Map<String, Object> config = new HashMap<String, Object>(); config.put(Constants.FRAMEWORK_STORAGE, "./target/storage"); Framework framework = factory.newFramework(config); framework.start(); BundleContext context = framework.getBundleContext(); Bundle bundle = context.installBundle("http://www.eclipsezone.com/files/jsig/bundles/HelloWorld.jar"); bundle.start(); framework.waitForStop(0); } catch (Exception e) { e.printStackTrace(); } }
/** Start the OSGI framework. */ public void start() throws FrameworkStartFailedException { FrameworkFactory frameworkFactory = null; // org.eclipse.osgi.launch.EquinoxFactory try { frameworkFactory = java.util.ServiceLoader.load(FrameworkFactory.class).iterator().next(); } catch (Exception ex) { LOG.error("Failed to load osgi framework class.", ex); // failed to load FrameworkFactory class throw new FrameworkStartFailedException("Can't load class FrameworkFactory.", ex); } framework = frameworkFactory.newFramework(prepareSettings()); context = null; try { // start OSGi container .. framework.start(); } catch (org.osgi.framework.BundleException ex) { LOG.error("Failed to start OSGI framework.", ex); // failed to start/initiate framework throw new FrameworkStartFailedException("Failed to start OSGi framework.", ex); } try { context = framework.getBundleContext(); } catch (SecurityException ex) { LOG.error("Failed to get osgi context.", ex); // we have to stop framework .. stop(); throw new FrameworkStartFailedException("Failed to get OSGi context.", ex); } // load resources startUpLoad(); }
public static void shutdownFramework() throws BundleException, InterruptedException { if (framework != null) { framework.stop(); framework.waitForStop(2000); framework = null; } }
public static void indexTargetPlatform( OutputStream outputStream, List<File> additionalJarFiles, long stopWaitTimeout, String... dirNames) throws Exception { Framework framework = null; Path tempPath = Files.createTempDirectory(null); ClassLoader classLoader = TargetPlatformIndexerUtil.class.getClassLoader(); try (InputStream inputStream = classLoader.getResourceAsStream("META-INF/system.packages.extra.mf")) { Map<String, String> properties = new HashMap<>(); properties.put(Constants.FRAMEWORK_STORAGE, tempPath.toString()); Manifest extraPackagesManifest = new Manifest(inputStream); Attributes attributes = extraPackagesManifest.getMainAttributes(); properties.put( Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, attributes.getValue("Export-Package")); ServiceLoader<FrameworkFactory> serviceLoader = ServiceLoader.load(FrameworkFactory.class); FrameworkFactory frameworkFactory = serviceLoader.iterator().next(); framework = frameworkFactory.newFramework(properties); framework.init(); BundleContext bundleContext = framework.getBundleContext(); Bundle systemBundle = bundleContext.getBundle(0); TargetPlatformIndexer targetPlatformIndexer = new TargetPlatformIndexer(systemBundle, additionalJarFiles, dirNames); targetPlatformIndexer.index(outputStream); } finally { framework.stop(); FrameworkEvent frameworkEvent = framework.waitForStop(stopWaitTimeout); if (frameworkEvent.getType() == FrameworkEvent.WAIT_TIMEDOUT) { throw new Exception( "OSGi framework event " + frameworkEvent + " triggered after a " + stopWaitTimeout + "ms timeout"); } PathUtil.deltree(tempPath); } }
@Override protected void setUp() throws Exception { tmp = IO.getFile("generated/tmp"); tmp.mkdirs(); IO.copy(IO.getFile("testdata/ws"), tmp); workspace = Workspace.getWorkspace(tmp); workspace.refresh(); InfoRepository repo = workspace.getPlugin(InfoRepository.class); t1 = create("bsn-1", new Version(1, 0, 0)); t2 = create("bsn-2", new Version(1, 0, 0)); repo.put(new FileInputStream(t1), null); repo.put(new FileInputStream(t2), null); t1 = repo.get("bsn-1", new Version(1, 0, 0), null); t2 = repo.get("bsn-2", new Version(1, 0, 0), null); repo.put(new FileInputStream(IO.getFile("generated/biz.aQute.remote.launcher.jar")), null); workspace.getPlugins().add(repo); File storage = IO.getFile("generated/storage-1"); storage.mkdirs(); configuration = new HashMap<String, Object>(); configuration.put( Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); configuration.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath()); configuration.put( Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.2"); framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration); framework.init(); framework.start(); context = framework.getBundleContext(); location = "reference:" + IO.getFile("generated/biz.aQute.remote.agent.jar").toURI().toString(); agent = context.installBundle(location); agent.start(); thread = new Thread() { @Override public void run() { try { Main.main( new String[] { "-s", "generated/storage", "-c", "generated/cache", "-p", "1090", "-et" }); } catch (Exception e) { e.printStackTrace(); } } }; thread.setDaemon(true); thread.start(); super.setUp(); }
private void shutdownFramework() { try { if (framework != null) { framework.stop(); framework.waitForStop(0); } } catch (Exception ex) { logger.error("Error stopping OSGI", ex); } }
@Override protected void before() throws Throwable { final Map<String, String> configMap = new HashMap<>(2); // Cleans framework before first init. Subsequent init invocations do not clean framework. configMap.put("org.osgi.framework.storage.clean", "onFirstInit"); // Delegates loading of endorsed libraries to JVM classloader // config.put("org.osgi.framework.bootdelegation", "javax.*,org.w3c.*,org.xml.*"); framework = factory.newFramework(configMap); framework.init(); framework.start(); }
@Override protected void tearDown() throws Exception { super.tearDown(); framework.stop(); IO.delete(tmp); Main.stop(); IO.delete(IO.getFile("generated/cache")); IO.delete(IO.getFile("generated/storage")); framework.waitForStop(100000); super.tearDown(); }
public int activate() throws Exception { Policy.setPolicy(new AllPolicy()); systemBundle = createFramework(); if (systemBundle == null) return LauncherConstants.ERROR; doTimeoutHandler(); // Initialize this framework so it becomes STARTING systemBundle.start(); trace("system bundle started ok"); BundleContext systemContext = systemBundle.getBundleContext(); ServiceReference ref = systemContext.getServiceReference(PackageAdmin.class.getName()); if (ref != null) { padmin = (PackageAdmin) systemContext.getService(ref); } else trace("could not get package admin"); systemContext.addServiceListener(this, "(&(objectclass=java.lang.Runnable)(main.thread=true))"); update(); if (parms.trace) { report(out); } // Start embedded activators trace("start embedded activators"); if (parms.activators != null) { ClassLoader loader = getClass().getClassLoader(); for (Object token : parms.activators) { try { Class<?> clazz = loader.loadClass((String) token); BundleActivator activator = (BundleActivator) clazz.newInstance(); embedded.add(activator); trace("adding activator %s", activator); } catch (Exception e) { throw new IllegalArgumentException( "Embedded Bundle Activator incorrect: " + token + ", " + e); } } } int result = LauncherConstants.OK; for (BundleActivator activator : embedded) try { trace("starting activator %s", activator); activator.start(systemContext); } catch (Exception e) { error("Starting activator %s : %s", activator, e); result = LauncherConstants.ERROR; } return result; }
public void report(PrintStream out) { try { out.println("------------------------------- REPORT --------------------------"); out.println(); row(out, "Framework", systemBundle == null ? "<>" : systemBundle.getClass()); row(out, "Framework type", parms.services ? "META-INF/services" : "mini framework"); row(out, "Storage", parms.storageDir); row(out, "Keep", parms.keep); row(out, "Security", security); list(out, fill("Run bundles", 40), parms.runbundles); list( out, fill("Classpath", 40), split(System.getProperty("java.class.path"), File.pathSeparator)); list(out, fill("System Packages", 40), split(parms.systemPackages, ",")); row(out, "Properties"); for (java.util.Map.Entry<Object, Object> entry : properties.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); row(out, key, value); } if (systemBundle != null) { BundleContext context = systemBundle.getBundleContext(); if (context != null) { Bundle bundles[] = context.getBundles(); out.println(); out.println("Id State Modified Location"); for (int i = 0; i < bundles.length; i++) { String loc = bundles[i].getLocation(); loc = loc.replaceAll("\\w+:", ""); File f = new File(loc); out.print(fill(Long.toString(bundles[i].getBundleId()), 6)); out.print(fill(toState(bundles[i].getState()), 6)); if (f.exists()) out.print(fill(toDate(f.lastModified()), 14)); else out.print(fill("<>", 14)); if (errors.containsKey(bundles[i])) { out.print(fill(loc, 50)); out.print(errors.get(bundles[i]).getMessage()); } else out.print(bundles[i].getLocation()); out.println(); } } } } catch (Throwable t) { error("Sorry, can't print framework: %s", t); } }
public synchronized void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.REGISTERED) { mainThread = (Runnable) systemBundle.getBundleContext().getService(event.getServiceReference()); notifyAll(); } }
private void installAndStartBundles(BundleContext context) throws BundleException { m_framework.start(); StartLevel sl = getStartLevelService(context); for (ProvisionOption bundle : m_bundles) { Bundle b = null; b = context.installBundle(bundle.getURL()); int startLevel = getStartLevel(bundle); sl.setBundleStartLevel(b, startLevel); b.start(); LOG.info("+ Install (start@" + startLevel + ") " + bundle); } LOG.info("++++ Jump to startlevel: " + Constants.START_LEVEL_TEST_BUNDLE); sl.setStartLevel(Constants.START_LEVEL_TEST_BUNDLE); // Work around for FELIX-2942 final CountDownLatch latch = new CountDownLatch(1); context.addFrameworkListener( new FrameworkListener() { public void frameworkEvent(FrameworkEvent frameworkEvent) { switch (frameworkEvent.getType()) { case FrameworkEvent.STARTLEVEL_CHANGED: latch.countDown(); } } }); try { latch.await(m_timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } }
public static void main(final String[] args) { System.out.println("\nWelcome to AspGen"); System.out.println("======================\n"); final Map<String, String> config = setupConfiguration(args); try { mFwk = getFrameworkFactory().newFramework(config); mFwk.init(); AutoProcessor.process(config, mFwk.getBundleContext()); mFwk.start(); mFwk.waitForStop(0); } catch (final IOException | BundleException | InterruptedException e) { e.printStackTrace(); throw new RuntimeException("Error"); } System.exit(0); }
private ModuleManager(File cacheRoot) { String systemPackagesSpec = FluentIterable.from(SYSTEM_PACKAGES).transform(appendVersion).join(COMMA_JOINER); Map<String, String> frameworkProps = ImmutableMap.<String, String>builder() .put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, systemPackagesSpec) .put("org.osgi.framework.storage.clean", "onFirstInit") .put("felix.cache.rootdir", cacheRoot.getAbsolutePath()) .put("felix.cache.locking", Boolean.FALSE.toString()) .build(); LOG.info("Framework properties are: " + frameworkProps); FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next(); m_framework = frameworkFactory.newFramework(frameworkProps); try { m_framework.start(); } catch (BundleException e) { LOG.error("Failed to start the felix OSGi framework", e); throw new SetUpException("Failed to start the felix OSGi framework", e); } m_bundles = new BundleRef(m_framework); }
@Override @Before public void setUp() throws Exception { super.setUp(); if (framework == null && isBeforeClassPresent() == false) { createFramework(); framework.start(); } }
public TestContainer start() throws TestContainerException { ClassLoader parent = null; try { final Map<String, String> p = new HashMap<String, String>(m_properties); String folder = p.get("org.osgi.framework.storage"); if (folder == null) { folder = System.getProperty("org.osgi.framework.storage"); } if (folder == null) { // folder = System.getProperty( "user.home" ) + File.separator + "osgi"; folder = getCache(); } LOG.debug("Cache folder set to " + folder); FileUtils.delete(new File(folder)); // load default stuff p.put("org.osgi.framework.storage", folder); // System.setProperty( "org.osgi.vendor.framework", "org.ops4j.pax.exam" ); p.put( "org.osgi.framework.system.packages.extra", "org.ops4j.pax.exam;version=" + skipSnapshotFlag(Info.getPaxExamVersion())); parent = Thread.currentThread().getContextClassLoader(); // Thread.currentThread().setContextClassLoader( null ); m_framework = m_frameworkFactory.newFramework(p); m_framework.init(); installAndStartBundles(m_framework.getBundleContext()); Thread.currentThread().setContextClassLoader(parent); } catch (Exception e) { throw new TestContainerException("Problem starting test container.", e); } finally { if (parent != null) { Thread.currentThread().setContextClassLoader(parent); } } return this; }
public TestContainer stop() { // if (1==1) throw new RuntimeException( "stop has been called." ); if (m_framework != null) { try { LOG.debug("Framework goes down.."); cleanup(); m_framework.stop(); m_framework.waitForStop(m_timeout); m_framework = null; } catch (BundleException e) { LOG.warn("Problem during stopping fw.", e); } catch (InterruptedException e) { LOG.warn("InterruptedException during stopping fw.", e); } } else { LOG.warn("Framework does not exist. Called start() before ? "); } return this; }
public synchronized void cleanup() { while ((!m_installed.isEmpty())) { try { Long id = m_installed.pop(); Bundle bundle = m_framework.getBundleContext().getBundle(id); bundle.uninstall(); LOG.debug("Uninstalled bundle " + id); } catch (BundleException e) { e.printStackTrace(); } } }
@Override protected void after() { if (framework != null) { try { framework.stop(); } catch (final BundleException e) { throw new RuntimeException(e); } finally { framework = null; } } }
private void run(String args[]) throws Throwable { try { int status = activate(); if (status != 0) { report(out); System.exit(status); } trace("framework=" + systemBundle); // Register the command line with ourselves as the // service. if (parms.services) { // Does not work for our dummy framework Hashtable<String, Object> argprops = new Hashtable<String, Object>(); argprops.put(LauncherConstants.LAUNCHER_ARGUMENTS, args); argprops.put(LauncherConstants.LAUNCHER_READY, "true"); systemBundle.getBundleContext().registerService(Launcher.class.getName(), this, argprops); trace("registered launcher with arguments for syncing"); } // Wait until a Runnable is registered with main.thread=true. // not that this will never happen when we're running on the mini fw // but the test case normally exits. synchronized (this) { while (mainThread == null) { trace("will wait for a registered Runnable"); wait(); } } trace("Will run %s as main thread", mainThread); mainThread.run(); } catch (Throwable e) { error("Unexpected error in the run body: %s", e); throw e; } finally { systemBundle.stop(); trace("stopped system bundle due to leaving run body"); } }
public synchronized long install(InputStream stream) { try { Bundle b = m_framework.getBundleContext().installBundle("local", stream); m_installed.push(b.getBundleId()); LOG.debug("Installed bundle " + b.getSymbolicName() + " as Bundle ID " + b.getBundleId()); setBundleStartLevel(b.getBundleId(), Constants.START_LEVEL_TEST_BUNDLE); // stream.close(); b.start(); return b.getBundleId(); } catch (BundleException e) { e.printStackTrace(); } return -1; }
@Override @After public void tearDown() throws Exception { // Nothing to do if the framework was not created or shutdown already if (framework != null && framework.getState() == Bundle.ACTIVE) { // Report and cleanup left over files in the bundle stream dir File streamDir = new File("./target/osgi-store/bundle-0/bundle-streams"); if (streamDir.exists() && streamDir.list().length > 0) { List<String> filelist = Arrays.asList(streamDir.list()); System.err.println("Bundle streams not cleaned up: " + filelist); } } super.tearDown(); }
private <T> void printAvailableAlternatives(Class<T> serviceType) { try { ServiceReference[] reference = m_framework.getBundleContext().getAllServiceReferences(serviceType.getName(), null); if (reference != null) { LOG.warn("Test Endpoints: " + reference.length); for (ServiceReference ref : reference) { LOG.warn("Endpoint: " + ref); } } } catch (Exception e) { LOG.error("Some problem during looking up alternative service. ", e); } }
private Bundle startBundle(URI bundleURI) { NavigableMap<URI, Bundle> expect, update; Bundle bundle = null; do { expect = get(); if (expect.containsKey(bundleURI)) break; BundleContext ctx = m_framework.getBundleContext(); bundle = ctx.getBundle(bundleURI.toASCIIString()); if (bundle != null) { try { bundle.update(); } catch (BundleException e) { String msg = e.getMessage(); throw loggedModularException(e, "Unable to update bundle %s. %s", bundleURI, msg); } catch (Throwable t) { throw loggedModularException(t, "Unable to update bundle %s", bundleURI); } } else { try { bundle = ctx.installBundle(bundleURI.toASCIIString()); } catch (BundleException e) { String msg = e.getMessage(); throw loggedModularException(e, "Unable to install bundle %s. %s", bundleURI, msg); } catch (Throwable t) { throw loggedModularException(t, "Unable to instal bundle %s", bundleURI); } } try { bundle.start(); } catch (BundleException e) { String msg = e.getMessage(); throw loggedModularException(e, "Unable to start bundle %s. %s", bundleURI, msg); } catch (Throwable t) { throw loggedModularException(t, "Unable to start bundle %s", bundleURI); } update = ImmutableSortedMap.<URI, Bundle>naturalOrder() .putAll(expect) .put(bundleURI, bundle) .build(); } while (!compareAndSet(expect, update)); return get().get(bundleURI); }
/** Stop OSGI and uninstall all bundles. */ public void stop() { for (BundleContainer bundle : bundles.values()) { try { bundle.uninstall(); } catch (BundleException e) { LOG.error("Failed to uninstall bundle {}", bundle.getUri(), e); } } bundles.clear(); try { if (framework != null) { // stop equinox framework.stop(); } } catch (Throwable e) { // we can't throw here .. } finally { framework = null; context = null; } }