private void startDependencyAsynch(final Bundle bundle) { System.out.println("starting dependency test bundle"); Runnable runnable = new Runnable() { public void run() { try { bundle.start(); System.out.println("started dependency test bundle"); } catch (BundleException ex) { System.err.println("can't start bundle " + ex); } } }; Thread thread = new Thread(runnable); thread.setDaemon(false); thread.setName("dependency test bundle"); thread.start(); }
public static String getPlatformName(BundleContext bundleContext) { String vendorProperty = bundleContext.getProperty(Constants.FRAMEWORK_VENDOR); String frameworkVersion = bundleContext.getProperty(Constants.FRAMEWORK_VERSION); // get system bundle Bundle bundle = bundleContext.getBundle(0); String name = (String) bundle.getHeaders().get(Constants.BUNDLE_NAME); String version = (String) bundle.getHeaders().get(Constants.BUNDLE_VERSION); String symName = bundle.getSymbolicName(); StringBuilder buf = new StringBuilder(); buf.append(name); buf.append(" "); buf.append(symName); buf.append("|"); buf.append(version); buf.append("{"); buf.append(frameworkVersion); buf.append(" "); buf.append(vendorProperty); buf.append("}"); return buf.toString(); }
private Bundle installBundleFromApk(String bundleName) throws Exception{ Bundle bundle = null; findBundleSource(bundleName); if(mTmpBundleSourceFile!=null){ bundle = Framework.installNewBundle(bundleName,mTmpBundleSourceFile); }else if(mTmpBundleSourceInputStream!=null){ bundle = Framework.installNewBundle(bundleName,mTmpBundleSourceInputStream); }else{ IOException e = new IOException("can not find bundle source file"); Map<String, Object> detail = new HashMap<>(); detail.put("installBundleFromApk",bundleName); AtlasMonitor.getInstance().report(AtlasMonitor.CONTAINER_BUNDLE_SOURCE_MISMATCH, detail, e); throw e; } return bundle; }
public Object getDataAsObject ( final Bundle bundle, final Object defaultValue ) { try { final Object result = getDataAsObject ( bundle ); if ( result == null ) { return defaultValue; } else { return result; } } catch ( final Exception e ) { return defaultValue; } }
protected Image getIcon(String fullPath) throws IOException { if (fullPath==null) return defaultIcon; if ("".equals(fullPath)) return defaultIcon; try { if (iconMap.containsKey(fullPath)) return iconMap.get(fullPath); final String[] sa = fullPath.split("/"); final Bundle bundle = Platform.getBundle(sa[0]); if (bundle==null) return defaultIcon; if (bundle!=null) { Image image = new Image(null, bundle.getResource(sa[1]+"/"+sa[2]).openStream()); iconMap.put(fullPath, image); } return iconMap.get(fullPath); } catch (Exception ne) { logger.debug("Cannot get icon for "+fullPath, ne); return defaultIcon; } }
@Test public void testInstallBundle() throws Exception { final String installCommand ="bundle:install mvn:" + OSGIFX_GROUP_ID + "/" + IT_DUMMY_BUNDLE_ARTIFACT_ID + "/" + PROJECT_VERSION; session.execute(installCommand); Bundle dummyBundle = null; for (Bundle bundle : bundleContext.getBundles()) { if (bundle.getSymbolicName() != null && bundle.getSymbolicName().equals(OSGIFX_GROUP_ID + "." + IT_DUMMY_BUNDLE_ARTIFACT_ID)) { dummyBundle = bundle; break; } } assertNotNull(dummyBundle); }
public void testInvocationWhenServiceNA() throws Throwable { // service n/a ServiceReference reference = new MockServiceReference() { public Bundle getBundle() { return null; } }; interceptor = new ServiceStaticInterceptor(new MockBundleContext(), reference); Object target = new Object(); Method m = target.getClass().getDeclaredMethod("hashCode", null); MethodInvocation invocation = new MockMethodInvocation(m); try { interceptor.invoke(invocation); fail("should have thrown exception"); } catch (ServiceUnavailableException ex) { // expected } }
private Bundle findBundle ( final String symbolicName ) { final Bundle[] bundles = this.context.getBundles (); if ( bundles == null ) { return null; } for ( final Bundle bundle : bundles ) { if ( bundle.getSymbolicName ().equals ( symbolicName ) ) { return bundle; } } return null; }
private boolean isFullyStarted(Bundle bundle) { Component[] components = scrService.getComponents(bundle); if (components != null) { for (Component component : components) { if (!isFullyStarted(component)) { return false; } } } return true; }
/** * Called if a bundle releases the service (stop the scope). * * @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle, * org.osgi.framework.ServiceRegistration, java.lang.Object) */ public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) { try { // tell the scope, it's an outside bundle that does the call EXTERNAL_BUNDLE.set(Boolean.TRUE); // unget object first decoratedServiceFactory.ungetService(bundle, registration, service); // then apply the destruction callback (if any) Runnable callback = callbacks.remove(bundle); if (callback != null) callback.run(); } finally { // clean ThreadLocal EXTERNAL_BUNDLE.set(null); } }
/** * notify all framework listeners. * * @param state the new state. * @param bundle the bundle. * @param throwable a throwable. */ static void notifyFrameworkListeners(final int state, final Bundle bundle, final Throwable throwable) { if (frameworkListeners.isEmpty()) { return; } final FrameworkEvent event = new FrameworkEvent(state); final FrameworkListener[] listeners = frameworkListeners.toArray(new FrameworkListener[frameworkListeners.size()]); for (int i = 0; i < listeners.length; i++) { final FrameworkListener listener = listeners[i]; listener.frameworkEvent(event); } }
private void createIcons() { icons = new HashMap<String, Image>(7); final IConfigurationElement[] eles = Platform.getExtensionRegistry().getConfigurationElementsFor("org.eclipse.scanning.api.generator"); for (IConfigurationElement e : eles) { final String identity = e.getAttribute("id"); final String icon = e.getAttribute("icon"); if (icon !=null) { final String cont = e.getContributor().getName(); final Bundle bundle= Platform.getBundle(cont); final URL entry = bundle.getEntry(icon); final ImageDescriptor des = ImageDescriptor.createFromURL(entry); icons.put(identity, des.createImage()); } } }
/** * If the service of a managed bundle are consumed by an unmanaged bundle, * that dependency should not affect the shutdown ordering as gemini blueprint is only responsible for * orderly shutting down the bundles it is managing. */ public void testUnmanagedBundlesAreIgnoredForShutdownOrdering() throws Exception { DependencyMockBundle a = new DependencyMockBundle("A"); DependencyMockBundle b = new DependencyMockBundle("B"); DependencyMockBundle c = new DependencyMockBundle("C"); DependencyMockBundle d = new DependencyMockBundle("D"); DependencyMockBundle e = new DependencyMockBundle("E"); DependencyMockBundle unmanaged = new DependencyMockBundle("F"); b.setDependentOn(c); d.setDependentOn(e, -13, 12); e.setDependentOn(d, 0, 14); a.setDependentOn(unmanaged); List<Bundle> order = getOrder(a, b, c, d, e); assertOrder(order, c, a, b, d, e); }
public DelegatedExecutionOsgiBundleApplicationContext createApplicationContext(BundleContext bundleContext) throws Exception { Bundle bundle = bundleContext.getBundle(); ApplicationContextConfiguration config = new BlueprintContainerConfig(bundle); String bundleName = OsgiStringUtils.nullSafeNameAndSymName(bundle); if (log.isTraceEnabled()) log.trace("Created configuration " + config + " for bundle " + bundleName); // it's not a spring bundle, ignore it if (!config.isSpringPoweredBundle()) { if (log.isDebugEnabled()) log.debug("No blueprint configuration found in bundle " + bundleName + "; ignoring it..."); return null; } log.info("Discovered configurations " + ObjectUtils.nullSafeToString(config.getConfigurationLocations()) + " in bundle [" + bundleName + "]"); DelegatedExecutionOsgiBundleApplicationContext sdoac = new OsgiBundleXmlApplicationContext(config.getConfigurationLocations()); sdoac.setBundleContext(bundleContext); sdoac.setPublishContextAsService(config.isPublishContextAsService()); return sdoac; }
/** * Return a bundle with a .melange declaring 'language' */ public static Bundle getMelangeBundle(String languageName){ IConfigurationElement[] melangeLanguages = Platform .getExtensionRegistry().getConfigurationElementsFor( "fr.inria.diverse.melange.language"); String melangeBundleName = ""; for (IConfigurationElement lang : melangeLanguages) { if(lang.getAttribute("id").equals(languageName)){ melangeBundleName = lang.getContributor().getName(); return Platform.getBundle(melangeBundleName); } } return null; }
/** * Indicates if the given bundle is lazily activated or not. That is, the * bundle has a lazy activation policy and a STARTING state. Bundles that * have been lazily started but have been activated will return false. * * <p/> * On OSGi R4.0 platforms, this method will always return false. * * @param bundle OSGi bundle * @return true if the bundle is lazily activated, false otherwise. */ @SuppressWarnings("unchecked") public static boolean isBundleLazyActivated(Bundle bundle) { Assert.notNull(bundle, "bundle is required"); if (OsgiPlatformDetector.isR41()) { if (bundle.getState() == Bundle.STARTING) { Dictionary<String, String> headers = bundle.getHeaders(); if (headers != null) { Object val = headers.get(Constants.BUNDLE_ACTIVATIONPOLICY); if (val != null) { String value = ((String) val).trim(); return (value.startsWith(Constants.ACTIVATION_LAZY)); } } } } return false; }
/** * Gets the ID of all required bundles for the specified bundle. * * @param bundle the bundle to evaluate * @return the required bundle ID's */ public static ArrayList<String> getRequiredBundleIDs(Bundle bundle) { ArrayList<String> requiredBundles = new ArrayList<>(); String reqBundles = bundle.getHeaders().get(Constants.REQUIRE_BUNDLE); if (reqBundles!=null && reqBundles.isEmpty()==false) { String[] reqBundlesArray = reqBundles.split(","); for (int i = 0; i < reqBundlesArray.length; i++) { String reqLine = reqBundlesArray[i]; if (reqLine.contains(";")==true) { reqLine = reqLine.substring(0, reqLine.indexOf(";")); } requiredBundles.add(reqLine); } } return requiredBundles; }
public void testNewProxiesCreatedOnBundleRefresh() throws Exception { // get a hold of the bundle proxy creator bundle and update it Bundle bundle = OsgiBundleUtils.findBundleBySymbolicName(bundleContext, PROXY_CREATOR_SYM_NAME); assertNotNull("proxy creator bundle not found", bundle); // update bundle (and thus create a new version of the classes) bundle.update(); // make sure it starts-up try { waitOnContextCreation(PROXY_CREATOR_SYM_NAME, 60); } catch (Exception ex) { fail("updating the bundle failed"); } }
private void shutdownAllContainers() { shuttingDown = true; restartService.close(); // Close all CSS modules first. ConfigSystemService configSystem = getOSGiService(ConfigSystemService.class); if (configSystem != null) { configSystem.closeAllConfigModules(); } LOG.info("Shutting down all blueprint containers..."); Collection<Bundle> containerBundles = new HashSet<>(Arrays.asList(bundleContext.getBundles())); while (!containerBundles.isEmpty()) { // For each iteration of getBundlesToDestroy, as containers are destroyed, other containers become // eligible to be destroyed. We loop until we've destroyed them all. for (Bundle bundle : getBundlesToDestroy(containerBundles)) { containerBundles.remove(bundle); BlueprintContainer container = blueprintExtenderService.getContainer(bundle); if (container != null) { blueprintExtenderService.destroyContainer(bundle, container); } } } LOG.info("Shutdown of blueprint containers complete"); }
private static long findBundle(BundleContext context, String namePattern) { Bundle[] installedBundles = context.getBundles(); for (int i = 0; i < installedBundles.length; i++) { Bundle bundle = installedBundles[i]; if (bundle.getSymbolicName().matches(namePattern)) { return bundle.getBundleId(); } } throw new RuntimeException("Cannot locate bundle with name pattern " + namePattern); }
private static Set<String> preLaodedBundlesNamePtterns(BundleContext context) { Set<String> installedBundleDescriptions = new HashSet<>(); Bundle[] installed0 = context.getBundles(); for (int i = 0; i < installed0.length; i++) { String descriptor = installed0[i].getSymbolicName() + ".*"; installedBundleDescriptions.add(descriptor); } return installedBundleDescriptions; }
public boolean pass(Bundle bundle) { try { Class<?> type = bundle.loadClass(NS_HANDLER_RESOLVER_CLASS_NAME); return NamespaceHandlerResolver.class.equals(type); } catch (Throwable th) { // if the interface is not wired, ignore the bundle log.warn("Bundle " + OsgiStringUtils.nullSafeNameAndSymName(bundle) + " cannot see class [" + NS_HANDLER_RESOLVER_CLASS_NAME + "]; ignoring it as a namespace resolver"); return false; } }
/** * Test method for * {@link org.eclipse.gemini.blueprint.mock.MockBundleContext#MockBundleContext(org.osgi.framework.Bundle)}. */ public void testMockBundleContextBundle() { Bundle bundle = new MockBundle(); mock = new MockBundleContext(bundle); assertSame(bundle, mock.getBundle()); assertNotNull(mock.getProperty(Constants.FRAMEWORK_VENDOR)); }
private void startDependency(Bundle simpleService2Bundle) throws BundleException, InterruptedException { System.out.println("Starting dependency"); simpleService2Bundle.start(); waitOnContextCreation("org.eclipse.gemini.blueprint.iandt.simpleservice2"); System.out.println("Dependency started"); }
private static boolean isResolved(Bundle b) { if (b.getState() == Bundle.INSTALLED) { // try to ask for a known resource which is known to resolve // the bundle b.findEntries("META-INF", "MANIFEST.MF", false); // NOI18N } return b.getState() != Bundle.INSTALLED; }
public BootstrappingDependenciesFailedEvent(ApplicationContext source, Bundle bundle, Throwable th, Collection<OsgiServiceDependencyEvent> nestedEvents, Filter filter) { super(source, bundle, th); this.dependencyEvents = nestedEvents; this.dependenciesFilter = filter; List<String> depFilters = new ArrayList<String>(dependencyEvents.size()); for (OsgiServiceDependencyEvent dependency : nestedEvents) { depFilters.add(dependency.getServiceDependency().getServiceFilter().toString()); } dependencyFilters = Collections.unmodifiableCollection(depFilters); }
/** * Install bundle - the equivalent of install action. * * @return * @throws BundleException */ private Bundle installBundle() throws BundleException { Assert.hasText(location, "location parameter required when installing a bundle"); // install bundle (default) log.info("Loading bundle from [" + location + "]"); Bundle bundle = null; boolean installBasedOnLocation = (resource == null); if (!installBasedOnLocation) { InputStream stream = null; try { stream = resource.getInputStream(); } catch (IOException ex) { // catch it since we fallback on normal install installBasedOnLocation = true; } if (!installBasedOnLocation) bundle = bundleContext.installBundle(location, stream); } if (installBasedOnLocation) bundle = bundleContext.installBundle(location); return bundle; }
private void registerService(ApplicationContext applicationContext) { final Dictionary<String, Object> serviceProperties = new Hashtable<String, Object>(); Bundle bundle = bundleContext.getBundle(); String symName = bundle.getSymbolicName(); serviceProperties.put(Constants.BUNDLE_SYMBOLICNAME, symName); serviceProperties.put(BLUEPRINT_SYMNAME, symName); Version version = OsgiBundleUtils.getBundleVersion(bundle); serviceProperties.put(Constants.BUNDLE_VERSION, version); serviceProperties.put(BLUEPRINT_VERSION, version); log.info("Publishing BlueprintContainer as OSGi service with properties " + serviceProperties); // export just the interface final String[] serviceNames = new String[] { BlueprintContainer.class.getName() }; if (log.isDebugEnabled()) log.debug("Publishing service under classes " + ObjectUtils.nullSafeToString(serviceNames)); AccessControlContext acc = SecurityUtils.getAccFrom(applicationContext); // publish service if (System.getSecurityManager() != null) { registration = AccessController.doPrivileged(new PrivilegedAction<ServiceRegistration>() { public ServiceRegistration run() { return bundleContext.registerService(serviceNames, blueprintContainer, serviceProperties); } }, acc); } else { registration = bundleContext.registerService(serviceNames, blueprintContainer, serviceProperties); } }
/** * Check if it has configuration * * @param extendedNodeType The ExtendedNodeType to check for xk config node * @return true or false */ public static boolean hasXKConfigNode(ExtendedNodeType extendedNodeType){ boolean response = false; if (extendedNodeType != null ){ String path = getNodeTypePathInsideBundle(extendedNodeType); Bundle bundle = getBundle(extendedNodeType); response = pathExists(bundle, path); } return response; }
void add(Bundle bundle, boolean isLazy, boolean applyCondition) { if (isLazy) { lazyBundles.put(bundle, Boolean.valueOf(applyCondition)); } else { activeBundles.put(bundle, activator.activate(bundle)); } }
private void waitForContextStartEvent(Bundle bundle) throws Exception { int eventNumber = eventList.size(); bundle.start(); waitOnContextCreation(bundle.getSymbolicName()); while (eventList.size() < eventNumber + 1) waitForEvent(TIME_OUT); }
@Override public String toString() { Bundle b = bundle; if (b == null) { return "uninitialized"; } return b.getLocation(); }
@Override public void removedService(ServiceReference<T> serviceReference, U u) { Bundle bundle = FrameworkUtil.getBundle( TransformServiceTrackerCustomizer.class); BundleContext bundleContext = bundle.getBundleContext(); bundleContext.ungetService(serviceReference); onRemovedService(serviceReference, u); }
protected void setUp() throws Exception { context = new AbstractOsgiBundleApplicationContext() { protected void loadBeanDefinitions(DefaultListableBeanFactory arg0) throws IOException, BeansException { } }; mocksControl = createStrictControl(); bundleCtx = mocksControl.createMock(BundleContext.class); bundle = createNiceMock(Bundle.class); expect(bundleCtx.getBundle()).andReturn(bundle); }
private Image getImage() { String path = "icons/ksp.gif"; Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID); URL url = FileLocator.find(bundle, new Path(path), null); ImageDescriptor imageDesc = ImageDescriptor.createFromURL(url); return imageDesc.createImage(); }
public void testOSGiCanProvideLayer() throws Exception { FileObject fo; Module m2; try { mgr.mutexPrivileged().enterWriteAccess(); String mfBar = "Bundle-SymbolicName: org.bar\n" + "Bundle-Version: 1.1.0\n" + "Bundle-ManifestVersion: 2\n" + "Import-Package: org.foo\n" + "OpenIDE-Module-Layer: org/bar/layer.xml\n" + "\n\n"; File j2 = changeManifest(new File(jars, "depends-on-simple-module.jar"), mfBar); m2 = mgr.create(j2, null, false, false, false); mgr.enable(m2); } finally { mgr.mutexPrivileged().exitWriteAccess(); } try { mgr.mutexPrivileged().enterWriteAccess(); fo = FileUtil.getConfigFile("TestFolder"); assertNotNull("Layer found and its entries registered", fo); Bundle b = NetigsoServicesTest.findBundle(m2.getCodeNameBase()); assertNotNull("Bundle for m2 found", b); assertEquals("It still remains in installed state only", Bundle.INSTALLED, b.getState()); } finally { mgr.disable(m2); mgr.mutexPrivileged().exitWriteAccess(); } }
public String getEventValue() { Bundle bundle = Platform.getBundle(PLUGIN_ID.THIS); if (bundle == null) { return NOT_INSTALLED; } IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode(PLUGIN_ID.THIS); boolean showOnStartup = prefs.getBoolean(SHOW_BOX_ON_STARTUP, true); if (showOnStartup) { return TRUE; } return FALSE; }
/** * Helps to diagnose bundles that are not resolved as it will throw a detailed exception * * @throws BundleException */ public void resolveBundles() throws BundleException { Bundle[] bundles = bundleContext.getBundles(); for (Bundle bundle : bundles) { if (bundle.getState() == Bundle.INSTALLED) { System.out.println("Found non resolved bundle " + bundle.getBundleId() + ":" + bundle.getSymbolicName() + ":" + bundle.getVersion()); bundle.start(); } } }
Advice createServiceProviderTCCLAdvice(ServiceReference reference) { Bundle bundle = reference.getBundle(); // if reference is dead already, it's impossible to provide the service // class loader if (bundle == null) return null; return new ServiceTCCLInterceptor(ClassLoaderFactory.getBundleClassLoaderFor(bundle)); }
/** * Test method for * {@link org.eclipse.gemini.blueprint.mock.MockServiceReference#MockServiceReference(org.osgi.framework.Bundle)}. */ public void testMockServiceReferenceBundle() { Bundle bundle = new MockBundle(); mock = new MockServiceReference(bundle); assertSame(bundle, mock.getBundle()); assertNotNull(mock.getPropertyKeys()); }