Java Code Examples for org.osgi.framework.Bundle

The following are top voted examples for showing how to use org.osgi.framework.Bundle. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: gemini.blueprint   File: DependencyTest.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 2
Project: gemini.blueprint   File: OsgiUtils.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 3
Project: atlas   File: BundleInstaller.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 4
Project: neoscada   File: DataNode.java   Source Code and License 6 votes vote down vote up
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;
    }
}
 
Example 5
Project: scanning   File: DetectorView.java   Source Code and License 6 votes vote down vote up
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;
		}
	}
 
Example 6
Project: flexfx   File: DeployOsgiFxTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 7
Project: gemini.blueprint   File: OsgiServiceStaticInterceptorTest.java   Source Code and License 6 votes vote down vote up
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
	}
}
 
Example 8
Project: neoscada   File: Activator.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 9
Project: athena   File: ComponentsMonitor.java   Source Code and License 6 votes vote down vote up
private boolean isFullyStarted(Bundle bundle) {
    Component[] components = scrService.getComponents(bundle);
    if (components != null) {
        for (Component component : components) {
            if (!isFullyStarted(component)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 10
Project: gemini.blueprint   File: OsgiBundleScope.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 11
Project: atlas   File: Framework.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 12
Project: scanning   File: GeneratorDescriptor.java   Source Code and License 6 votes vote down vote up
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());
		}

	}
}
 
Example 13
Project: gemini.blueprint   File: BlueprintShutdownSorterTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 14
Project: gemini.blueprint   File: BlueprintContainerCreator.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 15
Project: gemoc-studio-modeldebugging   File: MelangeHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 16
Project: gemini.blueprint   File: OsgiBundleUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 17
Project: AgentWorkbench   File: BundleFeatureMapper.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 18
Project: gemini.blueprint   File: ProxyCreatorTest.java   Source Code and License 6 votes vote down vote up
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");
	}
}
 
Example 19
Project: hashsdn-controller   File: BlueprintBundleTracker.java   Source Code and License 5 votes vote down vote up
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");
}
 
Example 20
Project: n4js   File: ProductLauncher.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 21
Project: n4js   File: ProductLauncher.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 22
Project: gemini.blueprint   File: NamespacePlugins.java   Source Code and License 5 votes vote down vote up
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;
	}
}
 
Example 23
Project: gemini.blueprint   File: MockBundleContextTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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));
}
 
Example 24
Project: gemini.blueprint   File: MavenArtifactLookupTest.java   Source Code and License 5 votes vote down vote up
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");
}
 
Example 25
Project: incubator-netbeans   File: Netigso.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 26
Project: gemini.blueprint   File: BootstrappingDependenciesFailedEvent.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 27
Project: gemini.blueprint   File: BundleFactoryBean.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 28
Project: gemini.blueprint   File: BlueprintContainerServicePublisher.java   Source Code and License 5 votes vote down vote up
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);
	}
}
 
Example 29
Project: JahiaDF   File: JahiaUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 30
Project: gemini.blueprint   File: LazyBundleRegistry.java   Source Code and License 5 votes vote down vote up
void add(Bundle bundle, boolean isLazy, boolean applyCondition) {
	if (isLazy) {
		lazyBundles.put(bundle, Boolean.valueOf(applyCondition));
	} else {
		activeBundles.put(bundle, activator.activate(bundle));
	}
}
 
Example 31
Project: gemini.blueprint   File: DepedencyEventTest.java   Source Code and License 5 votes vote down vote up
private void waitForContextStartEvent(Bundle bundle) throws Exception {
	int eventNumber = eventList.size();
	bundle.start();
	waitOnContextCreation(bundle.getSymbolicName());
	while (eventList.size() < eventNumber + 1)
		waitForEvent(TIME_OUT);
}
 
Example 32
Project: incubator-netbeans   File: NetigsoLoader.java   Source Code and License 5 votes vote down vote up
@Override
public String toString() {
    Bundle b = bundle;
    if (b == null) {
        return "uninitialized";
    }
    return b.getLocation();
}
 
Example 33
Project: com-liferay-apio-architect   File: TransformServiceTrackerCustomizer.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 34
Project: gemini.blueprint   File: AbstractRefreshableOsgiBundleApplicationContextTest.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 35
Project: vertigo-chroma-kspplugin   File: AboutDialog.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 36
Project: incubator-netbeans   File: NetigsoLayerDoesNotActivateTest.java   Source Code and License 5 votes vote down vote up
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();
    }
}
 
Example 37
Project: pgcodekeeper   File: EclipseEnvironment.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 38
Project: aries-jpa   File: AbstractJPAItest.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
        }
    }
}
 
Example 39
Project: gemini.blueprint   File: StaticServiceProxyCreator.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 40
Project: gemini.blueprint   File: MockServiceReferenceTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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());

}
 
Example 41
Project: incubator-netbeans   File: OSGiClassLoader.java   Source Code and License 5 votes vote down vote up
protected @Override Class<?> findClass(String name) throws ClassNotFoundException {
    for (Bundle b : bundles()) {
        try {
            return b.loadClass(name);
        } catch (ClassNotFoundException x) {
            // normal, try next one
        }
    }
    return super.findClass(name);
}
 
Example 42
Project: gemini.blueprint   File: ClassUtils.java   Source Code and License 5 votes vote down vote up
public static ClassLoader getFwkClassLoader() {
	if (System.getSecurityManager() != null) {
		return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
			public ClassLoader run() {
				return Bundle.class.getClassLoader();
			}
		});
	} else {
		return Bundle.class.getClassLoader();
	}
}
 
Example 43
Project: gemini.blueprint   File: NamespacePluginsTest.java   Source Code and License 5 votes vote down vote up
public void testCanResolveEntityAfterAddingPlugin() throws IOException, SAXException {
	Bundle b = new MockBundle();
	this.namespacePlugins.addPlugin(b, false, true);
	InputSource resolver = this.namespacePlugins.resolveEntity("public-id",
		"http://www.springframework.org/schema/beans/testme.xsd");
	assertNotNull("Should find resolver", resolver);
}
 
Example 44
Project: gemini.blueprint   File: OSGI723Test.java   Source Code and License 5 votes vote down vote up
public void testSpecialBundle() throws Exception {
	Bundle bundle = OsgiBundleUtils.findBundleBySymbolicName(bundleContext, "issue.osgi-723");
	System.out.println(bundle);

	File tmpFile = File.createTempFile("tomcat-bla", ".osgi");
	tmpFile.delete();
	tmpFile.mkdir();

	unpackBundle(bundle, tmpFile);
}
 
Example 45
Project: gemini.blueprint   File: BlueprintLoaderListener.java   Source Code and License 5 votes vote down vote up
@Override
public void start(BundleContext context) throws Exception {
	this.listenerManager = new BlueprintListenerManager(context);
       EventAdminDispatcher dispatcher = new EventAdminDispatcher(context);
       Bundle bundle = context.getBundle();
	this.contextProcessor = new BlueprintContainerProcessor(dispatcher, listenerManager, bundle);
	this.typeChecker = new BlueprintTypeCompatibilityChecker(bundle);
       this.listenerServiceActivator.getMulticaster().addApplicationListener(this.contextProcessor);
	super.start(context);
}
 
Example 46
Project: gemini.blueprint   File: BehaviorBaseTest.java   Source Code and License 5 votes vote down vote up
/**
 * Does the given bundle, publish an application context or not?
 * 
 * @param alive
 */
protected void assertContextServiceIs(Bundle bundle, boolean alive, long maxWait) {
	Assert.notNull(bundle);

	try {
		waitOnContextCreation(bundle.getSymbolicName(), maxWait / 1000 + 1);
		if (!alive)
			fail("appCtx should have NOT been published for bundle "
					+ OsgiStringUtils.nullSafeNameAndSymName(bundle));
	}
	catch (RuntimeException timeout) {
		if (alive)
			fail("appCtx should have been published for bundle " + OsgiStringUtils.nullSafeNameAndSymName(bundle));
	}
}
 
Example 47
Project: JahiaDF   File: JahiaUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Check if a path exists
 *
 * @param bundle The Bundle to fetch resource
 * @param path The path to check
 * @return true or false
 */
private static boolean pathExists(Bundle bundle, String path){
    boolean response = false;
    if (bundle != null && path != null){
        URL url = bundle.getResource(path);
        if ( url != null ){
            response = true;
        }
    }
    return response;
}
 
Example 48
Project: gemini.blueprint   File: CachingBundleClassLoaderFactory.java   Source Code and License 5 votes vote down vote up
public ClassLoader createClassLoader(Bundle bundle) {
	ClassLoader loader = null;
	// create a bundle identity object
	Object key = createKeyFor(bundle);

	Map<Object, WeakReference<ClassLoader>> loaders = null;
	// get associated class loaders (if any)
	synchronized (cache) {
		loaders = cache.get(bundle);
		if (loaders == null) {
			loaders = new HashMap<Object, WeakReference<ClassLoader>>(4);
			loader = createBundleClassLoader(bundle);
			loaders.put(key, new WeakReference<ClassLoader>(loader));
			return loader;
		}
	}
	// check the associated loaders
	synchronized (loaders) {
		WeakReference<ClassLoader> reference = loaders.get(key);
		if (reference != null)
			loader = (ClassLoader) reference.get();
		// loader not found (or already recycled)
		if (loader == null) {
			loader = createBundleClassLoader(bundle);
			loaders.put(key, new WeakReference<ClassLoader>(loader));
		}
		return loader;
	}
}
 
Example 49
Project: incubator-netbeans   File: IntegrationTest.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 50
Project: pgcodekeeper   File: FeedBackDialog.java   Source Code and License 5 votes vote down vote up
private static StringBuilder appendCodeKeeperPluginsInformation(StringBuilder sb) {
    Bundle codeKeeperBundle = Activator.getContext().getBundle();
    sb.append(codeKeeperBundle.getSymbolicName()).append(' ').append(codeKeeperBundle.getVersion()).append('\n');

    codeKeeperBundle = ru.taximaxim.codekeeper.apgdiff.Activator.getContext().getBundle();
    sb.append(codeKeeperBundle.getSymbolicName()).append(' ').append(codeKeeperBundle.getVersion()).append('\n');

    codeKeeperBundle = ru.taximaxim.codekeeper.mainapp.Activator.getDefault().getBundle();
    sb.append(codeKeeperBundle.getSymbolicName()).append(' ').append(codeKeeperBundle.getVersion()).append('\n');
    return sb;
}
 
Example 51
Project: aries-jpa   File: AbstractJPAItest.java   Source Code and License 5 votes vote down vote up
public Bundle getBundleByName(String symbolicName) {
    for (Bundle b : bundleContext.getBundles()) {
        if (b.getSymbolicName().equals(symbolicName)) {
            return b;
        }
    }
    return null;
}
 
Example 52
Project: gemini.blueprint   File: ServiceProviderTCCLInterceptor.java   Source Code and License 5 votes vote down vote up
private void setServiceProvidedClassLoader(Bundle serviceBundle) {
	synchronized (lock) {
		this.serviceBundle = serviceBundle;
		if (serviceBundle != null) {
			serviceClassLoader = ClassLoaderFactory.getBundleClassLoaderFor(serviceBundle);
		} else
			serviceClassLoader = null;
	}
}
 
Example 53
Project: gemini.blueprint   File: SyncNoWaitTest.java   Source Code and License 5 votes vote down vote up
public void testBehaviour() throws Exception {

		// locate bundle
		Bundle bundle = installBundle(bundleId);
		Bundle tail = installBundle(tailBundleId);

		// start bundle first
		bundle.start();

		assertTrue("bundle " + bundle + "hasn't been fully started", OsgiBundleUtils.isBundleActive(bundle));

		// followed by its tail
		tail.start();
		assertTrue("bundle " + tail + "hasn't been fully started", OsgiBundleUtils.isBundleActive(tail));

		// wait for the listener to get the bundles and wait for timeout

		// make sure the appCtx is not up
		// check that the appCtx is *not* published (it waits for the service to
		// appear)
		assertContextServiceIs(bundle, false, 3000);

		// wait for appCtx to timeout
		//Thread.sleep(3000);

		// check that the dependency service is actually started as the
		// dependency
		// bundle has started
		assertNotNull(bundleContext.getServiceReference(Shape.class.getName()));
	}
 
Example 54
Project: osc-core   File: DeploymentInstaller.java   Source Code and License 5 votes vote down vote up
/**
 * Wait for the next job to do from the two pending queues. Note that we
 * always favour the install queue, because performing an install/uninstall
 * will invalidate any completed resolves. Therefore the resolves are only
 * processed when the install queue is empty.
 */
private Job<?> waitForJob() throws InterruptedException {
    synchronized (this.processorThread) {
        while (true) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            // Try to get an InstallableUnit to install
            Job<List<Bundle>> installJob = this.pendingInstalls.poll();
            if (installJob != null) {
                return installJob;
            }

            // Try to get a File to resolve. An iterator is needed to remove the first entry from the LinkedHashMap.
            Iterator<Job<InstallableUnitImpl>> resolvesIter = this.pendingResolves.values().iterator();
            if (resolvesIter.hasNext()) {
                Job<InstallableUnitImpl> resolveJob = resolvesIter.next();
                resolvesIter.remove();
                return resolveJob;
            }

            // Wait for a notification
            this.processorThread.wait();
        }
    }
}
 
Example 55
Project: gemini.blueprint   File: NamespacePluginsTest.java   Source Code and License 5 votes vote down vote up
public void testCanResolveNamespaceFromBundleAfterAddingPlugin() throws IOException, SAXException {
	Bundle b = new MockBundle();
	this.namespacePlugins.addPlugin(b, false, true);
	NamespaceHandler handler = this.namespacePlugins.resolve("http://www.springframework.org/schema/testme");
	assertNotNull("should find handler", handler);
	assertTrue("should be TestHandler", handler instanceof TestHandler);
}
 
Example 56
Project: osc-core   File: InstallerIntegrationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAddRemoveBundles() throws Exception {
    // Precondition: no example bundles
    assertNull("example bundle already present - broken prior test?", findBundle("org.example.a"));
    assertNull("example bundle already present - broken prior test?", findBundle("org.example.b"));

    FrameworkInstaller installer = this.fwkInstallerTracker.getService();
    assertNotNull("installer service not found", installer);

    // Install bundles and check they were installed
    File fileA = new File(this.dataDir, "org.example.a.jar");
    File fileB = new File(this.dataDir, "org.example.b.jar");
    List<String> locations = Stream.of(fileA, fileB)
            .map(File::toURI)
            .map(URI::toString)
            .collect(Collectors.toList());
    Object sponsor = new Object();
    List<Bundle> installed = installer.addLocations(sponsor, locations);
    assertEquals(2, installed.size());
    assertEquals("org.example.a", installed.get(0).getSymbolicName());
    assertEquals("org.example.b", installed.get(1).getSymbolicName());

    assertNotNull("example bundle not present after install", findBundle("org.example.a"));
    assertNotNull("example bundle not present after install", findBundle("org.example.b"));

    // Uninstall bundles and check they are gone
    Set<String> removed = installer.removeSponsor(sponsor).stream().map(Bundle::getSymbolicName).collect(Collectors.toSet());
    assertEquals(2, removed.size());
    assertTrue(removed.contains("org.example.a"));
    assertTrue(removed.contains("org.example.b"));

    assertNull("example bundle still present after uninstall", findBundle("org.example.a"));
    assertNull("example bundle still present after uninstall", findBundle("org.example.b"));
}
 
Example 57
Project: ec4e   File: EditorConfigImages.java   Source Code and License 5 votes vote down vote up
private final static void declareRegistryImage(String key, String path) {
	ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor();
	Bundle bundle = Platform.getBundle(EditorConfigPlugin.PLUGIN_ID);
	URL url = null;
	if (bundle != null) {
		url = FileLocator.find(bundle, new Path(path), null);
		if (url != null) {
			desc = ImageDescriptor.createFromURL(url);
		}
	}
	imageRegistry.put(key, desc);
}
 
Example 58
Project: neoscada   File: Factories.java   Source Code and License 5 votes vote down vote up
public static Class<?> loadClass ( final BundleContext ctx, final IConfigurationElement ele, final String attribute )
{
    final String clazzName = ele.getAttribute ( attribute );
    if ( clazzName == null || clazzName.isEmpty () )
    {
        return null;
    }

    final String bundleName = ele.getContributor ().getName ();

    logger.debug ( "Locating classs {} from {}", clazzName, bundleName );

    for ( final Bundle bundle : ctx.getBundles () )
    {
        if ( bundle.getSymbolicName ().equals ( bundleName ) )
        {
            try
            {
                return bundle.loadClass ( clazzName );
            }
            catch ( final ClassNotFoundException e )
            {
                // we give other bundles a chance
            }
        }
    }

    return null;
}
 
Example 59
Project: AgentWorkbench   File: VersionInfo.java   Source Code and License 5 votes vote down vote up
/**
 * Loads the version information to this instance.
 */
public Version getVersion() {
	if (version==null) {
		Bundle bundle = Platform.getBundle(this.plugInID);
		version = bundle.getVersion();
	}
	return version;
}
 
Example 60
Project: gemini.blueprint   File: OsgiBundleResourcePatternResolver.java   Source Code and License 4 votes vote down vote up
/**
 * Searches each level inside the bundle for entries based on the search strategy chosen.
 * 
 * @param bundle the bundle to do the lookup
 * @param fullPattern matching pattern
 * @param dir directory inside the bundle
 * @param result set of results (used to concatenate matching sub dirs)
 * @param searchType the search strategy to use
 * @throws IOException
 */
private void doRetrieveMatchingBundleEntries(Bundle bundle, String fullPattern, String dir, Set<Resource> result,
		int searchType) throws IOException {

	Enumeration<?> candidates;

	switch (searchType) {
	case OsgiResourceUtils.PREFIX_TYPE_NOT_SPECIFIED:
	case OsgiResourceUtils.PREFIX_TYPE_BUNDLE_SPACE:
		// returns an enumeration of URLs
		candidates = bundle.findEntries(dir, null, false);
		break;
	case OsgiResourceUtils.PREFIX_TYPE_BUNDLE_JAR:
		// returns an enumeration of Strings
		candidates = bundle.getEntryPaths(dir);
		break;
	case OsgiResourceUtils.PREFIX_TYPE_CLASS_SPACE:
		// returns an enumeration of URLs
		throw new IllegalArgumentException("class space does not support pattern matching");
	default:
		throw new IllegalArgumentException("unknown searchType " + searchType);
	}

	// entries are relative to the root path - miss the leading /
	if (candidates != null) {
		boolean dirDepthNotFixed = (fullPattern.indexOf(FOLDER_WILDCARD) != -1);
		while (candidates.hasMoreElements()) {
			Object path = candidates.nextElement();
			String currPath;

			if (path instanceof String)
				currPath = handleString((String) path);
			else
				currPath = handleURL((URL) path);

			if (!currPath.startsWith(dir)) {
				// Returned resource path does not start with relative
				// directory:
				// assuming absolute path returned -> strip absolute path.
				int dirIndex = currPath.indexOf(dir);
				if (dirIndex != -1) {
					currPath = currPath.substring(dirIndex);
				}
			}

			if (currPath.endsWith(FOLDER_SEPARATOR)
					&& (dirDepthNotFixed || StringUtils.countOccurrencesOf(currPath, FOLDER_SEPARATOR) < StringUtils
							.countOccurrencesOf(fullPattern, FOLDER_SEPARATOR))) {
				// Search subdirectories recursively: we manually get the
				// folders on only one level

				doRetrieveMatchingBundleEntries(bundle, fullPattern, currPath, result, searchType);
			}
			if (getPathMatcher().match(fullPattern, currPath)) {
				if (path instanceof URL)
					result.add(new UrlContextResource((URL) path, currPath));
				else
					result.add(new OsgiBundleResource(bundle, currPath));

			}
		}
	}
}