Java Code Examples for org.osgi.framework.Bundle#getSymbolicName()

The following examples show how to use org.osgi.framework.Bundle#getSymbolicName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XmlDocumentBundleTracker.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void parseDocuments(Bundle bundle, Collection<URL> filteredPaths) {
    int numberOfParsedXmlDocuments = 0;
    for (URL xmlDocumentURL : filteredPaths) {
        String moduleName = bundle.getSymbolicName();
        String xmlDocumentFile = xmlDocumentURL.getFile();
        logger.debug("Reading the XML document '{}' in module '{}'...", xmlDocumentFile, moduleName);
        try {
            T object = xmlDocumentTypeReader.readFromXML(xmlDocumentURL);
            addingObject(bundle, object);
            numberOfParsedXmlDocuments++;
        } catch (Exception ex) {
            // If we are not open, we can stop here.
            if (withLock(lockOpenState.readLock(), () -> openState != OpenState.OPENED)) {
                return;
            }
            logger.warn("The XML document '{}' in module '{}' could not be parsed: {}", xmlDocumentFile, moduleName,
                    ex.getLocalizedMessage(), ex);
        }
    }
    if (numberOfParsedXmlDocuments > 0) {
        addingFinished(bundle);
    }
}
 
Example 2
Source File: BundleUtil.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the javadoc location for the given bundle.
 *
 * <p>We can't use P2Utils and we can't use SimpleConfiguratorManipulator because of
 * API breakage between 3.5 and 4.2.
 * So we do a bit EDV (Computer data processing) ;-)
 *
 * @param bundle the bundle for which the javadoc location must be computed.
 * @param bundleLocation the location of the bundle, as replied by {@link #getBundlePath(Bundle)}.
 * @return the path to the javadoc folder of the bundle, or {@code null} if undefined.
 * @see #getBundlePath(Bundle)
 */
public static IPath getJavadocBundlePath(Bundle bundle, IPath bundleLocation) {
	IPath sourcesPath = null;
	// Not an essential functionality, make it robust
	try {
		final IPath srcFolderPath = getSourceRootProjectFolderPath(bundle);
		if (srcFolderPath == null) {
			//common case, jar file.
			final IPath bundlesParentFolder = bundleLocation.removeLastSegments(1);
			final String binaryJarName = bundleLocation.lastSegment();
			final String symbolicName = bundle.getSymbolicName();
			final String sourceJarName = binaryJarName.replace(symbolicName,
					symbolicName.concat(JAVADOC_SUFIX));
			final IPath potentialSourceJar = bundlesParentFolder.append(sourceJarName);
			if (potentialSourceJar.toFile().exists()) {
				sourcesPath = potentialSourceJar;
			}
		} else {
			sourcesPath = srcFolderPath;
		}
	} catch (Throwable t) {
		throw new RuntimeException(t);
	}
	return sourcesPath;
}
 
Example 3
Source File: AbstractResourceBundleProvider.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method provides common functionality for {@link ModuleTypeProvider} and {@link TemplateProvider} to process
 * uninstalling the bundles. For {@link RuleResourceBundleImporter} this method is overridden.
 * <p>
 * When some of the bundles that provides automation objects is uninstalled, this method will remove it from
 * {@link #waitingProviders}, if it is still there or from {@link #providerPortfolio} in the other case.
 * <p>
 * Will remove the provided objects from {@link #providedObjectsHolder} and will remove their persistence, injected
 * in the system from this bundle.
 *
 * @param bundle the uninstalled {@link Bundle}, provider of automation objects.
 */
@SuppressWarnings("unchecked")
protected void processAutomationProviderUninstalled(Bundle bundle) {
    waitingProviders.remove(bundle);
    Vendor vendor = new Vendor(bundle.getSymbolicName(), bundle.getVersion().toString());
    List<String> portfolio = providerPortfolio.remove(vendor);
    if (portfolio != null && !portfolio.isEmpty()) {
        for (String uid : portfolio) {
            E removedObject = providedObjectsHolder.remove(uid);
            if (listeners != null) {
                List<ProviderChangeListener<E>> snapshot = null;
                synchronized (listeners) {
                    snapshot = new LinkedList<ProviderChangeListener<E>>(listeners);
                }
                for (ProviderChangeListener<E> listener : snapshot) {
                    listener.removed((Provider<E>) this, removedObject);
                }
            }
        }
    }
}
 
Example 4
Source File: ClassLoaderUtilsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testVariousLoadersLoadClassInOsgiWhiteList() throws Exception {
    String bundlePath = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH;
    String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
    String classname = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_SIMPLE_ENTITY;
    
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), bundlePath);

    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = installBundle(mgmt, bundleUrl);
    Class<?> clazz = bundle.loadClass(classname);
    Entity entity = createSimpleEntity(bundleUrl, clazz);
    
    String whiteList = bundle.getSymbolicName()+":"+bundle.getVersion();
    System.setProperty(ClassLoaderUtils.WHITE_LIST_KEY, whiteList);
    
    ClassLoaderUtils cluMgmt = new ClassLoaderUtils(getClass(), mgmt);
    ClassLoaderUtils cluClass = new ClassLoaderUtils(clazz);
    ClassLoaderUtils cluEntity = new ClassLoaderUtils(getClass(), entity);
    
    assertLoadSucceeds(classname, clazz, cluMgmt, cluClass, cluEntity);
    assertLoadSucceeds(bundle.getSymbolicName() + ":" + classname, clazz, cluMgmt, cluClass, cluEntity);
}
 
Example 5
Source File: BundleUtil.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the source location for the given bundle.
 *
 * <p>The source location is usually the root folder where the source code of the bundle is located.
 *
 * <p>We can't use P2Utils and we can't use SimpleConfiguratorManipulator because of
 * API breakage between 3.5 and 4.2.
 * So we do a bit EDV (Computer data processing) ;-)
 *
 * @param bundle the bundle for which the source location must be computed.
 * @param bundleLocation the location of the bundle, as replied by {@link #getBundlePath(Bundle)}.
 * @return the path to the source folder of the bundle, or {@code null} if undefined.
 * @see #getBundlePath(Bundle)
 */
public static IPath getSourceBundlePath(Bundle bundle, IPath bundleLocation) {
	IPath sourcesPath = null;
	// Not an essential functionality, make it robust
	try {
		final IPath srcFolderPath = getSourceRootProjectFolderPath(bundle);
		if (srcFolderPath == null) {
			//common case, jar file.
			final IPath bundlesParentFolder = bundleLocation.removeLastSegments(1);
			final String binaryJarName = bundleLocation.lastSegment();
			final String symbolicName = bundle.getSymbolicName();
			final String sourceJarName = binaryJarName.replace(symbolicName,
					symbolicName.concat(SOURCE_SUFIX));
			final IPath potentialSourceJar = bundlesParentFolder.append(sourceJarName);
			if (potentialSourceJar.toFile().exists()) {
				sourcesPath = potentialSourceJar;
			}
		} else {
			sourcesPath = srcFolderPath;
		}
	} catch (Throwable t) {
		throw new RuntimeException(t);
	}

	return sourcesPath;
}
 
Example 6
Source File: FelixFramework.java    From vespa with Apache License 2.0 6 votes vote down vote up
private void installBundle(String bundleLocation, Set<String> mask, List<Bundle> out) throws BundleException {
    bundleLocation = BundleLocationResolver.resolve(bundleLocation);
    if (mask.contains(bundleLocation)) {
        log.finer("OSGi bundle from '" + bundleLocation + "' already installed.");
        return;
    }
    log.finer("Installing OSGi bundle from '" + bundleLocation + "'.");
    mask.add(bundleLocation);

    Bundle bundle = felix.getBundleContext().installBundle(bundleLocation);
    String symbol = bundle.getSymbolicName();
    if (symbol == null) {
        bundle.uninstall();
        throw new BundleException("Missing Bundle-SymbolicName in manifest from '" + bundleLocation + " " +
                                  "(it might not be an OSGi bundle).");
    }
    out.add(bundle);
    for (String preInstall : OsgiHeader.asList(bundle, OsgiHeader.PREINSTALL_BUNDLE)) {
        log.finer("OSGi bundle '" + symbol + "' requires install from '" + preInstall + "'.");
        installBundle(preInstall, mask, out);
    }
}
 
Example 7
Source File: ClassLoaderUtilsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadJustOneClassInOsgiWhiteList() throws Exception {
    String bundlePath = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH;
    String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
    String classname = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_SIMPLE_ENTITY;
    
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), bundlePath);

    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = installBundle(mgmt, bundleUrl);
    Class<?> clazz = bundle.loadClass(classname);
    Entity entity = createSimpleEntity(bundleUrl, clazz);
    
    String whiteList = bundle.getSymbolicName()+":"+bundle.getVersion();
    System.setProperty(ClassLoaderUtils.WHITE_LIST_KEY, whiteList);
    
    ClassLoaderUtils cluEntity = new ClassLoaderUtils(getClass(), entity);

    BundledName resource = new BundledName(classname).toResource();
    BundledName bn = new BundledName(resource.bundle, resource.version, "/" + resource.name);
    Asserts.assertSize(cluEntity.getResources(bn.toString()), 1);
}
 
Example 8
Source File: XmlMementoSerializerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testRenamedOsgiClassWithoutBundlePrefixInRename() throws Exception {
    String bundlePath = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_PATH;
    String bundleUrl = "classpath:" + bundlePath;
    String classname = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_OBJECT;
    String oldClassname = "com.old.package.name.OldClassName";
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), bundlePath);
    
    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = installBundle(mgmt, bundleUrl);
    
    String bundlePrefix = bundle.getSymbolicName();
    
    Class<?> osgiObjectClazz = bundle.loadClass(classname);
    Object obj = Reflections.invokeConstructorFromArgs(osgiObjectClazz, "myval").get();

    serializer = new XmlMementoSerializer<Object>(mgmt.getCatalogClassLoader(),
            ImmutableMap.of(oldClassname, classname));
    serializer.setLookupContext(newEmptyLookupManagementContext(mgmt, true));

    // i.e. prepended with bundle name
    String serializedForm = Joiner.on("\n").join(
            "<"+bundlePrefix+":"+classname+">",
            "  <val>myval</val>",
            "</"+bundlePrefix+":"+classname+">");

    runRenamed(serializedForm, obj, ImmutableMap.<String, String>of(
            bundlePrefix + ":" + classname, bundlePrefix + ":" + oldClassname));
}
 
Example 9
Source File: SyntheticBundleInstaller.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean isBundleAvailable(BundleContext context, String bsn) {
    for (Bundle bundle : context.getBundles()) {
        final String bsnCurrentBundle = bundle.getSymbolicName();
        if (bsnCurrentBundle != null) {
            if (bsnCurrentBundle.equals(bsn) && bundle.getState() == Bundle.ACTIVE) {
                return true;
            }
        }
    }
    return false;
}
 
Example 10
Source File: GrammarHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the bundle symbolic name.
 * 
 * @param classe
 *          the class
 * @return the bundle symbolic name
 */
protected String getBundleSymbolicName(final Class<?> classe) {
  ClassLoader cl = classe.getClassLoader();
  if (cl instanceof BundleReference) {
    Bundle bundle = ((BundleReference) cl).getBundle();
    if (bundle != null) {
      return bundle.getSymbolicName();
    }
  }
  return null;
}
 
Example 11
Source File: XmlDocumentBundleTracker.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void unregisterReadyMarker(Bundle bundle) {
    String bsn = bundle.getSymbolicName();
    ReadyMarker readyMarker = bundleReadyMarkerRegistrations.remove(bsn);
    if (readyMarker != null) {
        readyService.unmarkReady(readyMarker);
    }
}
 
Example 12
Source File: StartupOrderResolverUtils.java    From carbon-kernel with Apache License 2.0 5 votes vote down vote up
/**
 * Creates {@code ManifestElement} instances from CARBON_COMPONENT_HEADER in the given bundle.
 *
 * @param bundle from the which the header value should retrieved.
 * @return the created list of {@code ManifestElement} instances
 */
static List<ManifestElement> getManifestElements(Bundle bundle) {
    String headerValue = AccessController.doPrivileged((PrivilegedAction<String>) () ->
            bundle.getHeaders().get(CARBON_COMPONENT_HEADER));

    try {
        return ManifestElement.parseHeader(CARBON_COMPONENT_HEADER, headerValue, bundle);
    } catch (ManifestElementParserException e) {
        String message = "Error occurred while parsing the " + CARBON_COMPONENT_HEADER + " header in bundle(" +
                bundle.getSymbolicName() + ":" + bundle.getVersion() + "). " + "Header value: " + headerValue;
        throw new StartOrderResolverException(message, e);
    }
}
 
Example 13
Source File: AbstractTabDescriptor.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object clone() {
	try {
		return super.clone();
	} catch (CloneNotSupportedException exception) {
		Bundle bundle = FrameworkUtil.getBundle(AbstractTabDescriptor.class);
		IStatus status = new Status(IStatus.ERROR,
				bundle.getSymbolicName(), 666, exception
				.getMessage(), exception);
		Platform.getLog(bundle).log(status);
	}
	return null;
}
 
Example 14
Source File: ClassLoaderUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadClassInOsgiWhiteListWithInvalidBundlePresent() throws Exception {
    String bundlePath = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH;
    String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
    String classname = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_SIMPLE_ENTITY;
    
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), bundlePath);

    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = installBundle(mgmt, bundleUrl);
    
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    JarOutputStream target = new JarOutputStream(buffer, manifest);
    target.close();
    
    OsgiManager osgiManager = ((ManagementContextInternal)mgmt).getOsgiManager().get();
    Framework framework = osgiManager.getFramework();
    Bundle installedBundle = framework.getBundleContext().installBundle("stream://invalid", new ByteArrayInputStream(buffer.toByteArray()));
    assertNotNull(installedBundle);
    
    Class<?> clazz = bundle.loadClass(classname);
    Entity entity = createSimpleEntity(bundleUrl, clazz);
    
    String whileList = bundle.getSymbolicName()+":"+bundle.getVersion();
    System.setProperty(ClassLoaderUtils.WHITE_LIST_KEY, whileList);
    
    ClassLoaderUtils cluMgmt = new ClassLoaderUtils(getClass(), mgmt);
    ClassLoaderUtils cluClass = new ClassLoaderUtils(clazz);
    ClassLoaderUtils cluEntity = new ClassLoaderUtils(getClass(), entity);
    
    assertLoadSucceeds(classname, clazz, cluMgmt, cluClass, cluEntity);
    assertLoadSucceeds(bundle.getSymbolicName() + ":" + classname, clazz, cluMgmt, cluClass, cluEntity);
}
 
Example 15
Source File: BundleManager.java    From vespa with Apache License 2.0 5 votes vote down vote up
private boolean isFragment(Bundle bundle) {
    BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);
    if (bundleRevision == null)
        throw new NullPointerException("Null bundle revision means that bundle has probably been uninstalled: " +
                                       bundle.getSymbolicName() + ":" + bundle.getVersion());
    return (bundleRevision.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0;
}
 
Example 16
Source File: BundleManager.java    From vespa with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves and starts (calls the Bundles BundleActivator) all bundles. Bundle resolution must take place
 * after all bundles are installed to ensure that the framework can resolve dependencies between bundles.
 */
private void startBundles() {
    for (List<Bundle> bundles : reference2Bundles.values()) {
        for (Bundle bundle : bundles) {
            try {
                if ( ! isFragment(bundle))
                    bundle.start();  // NOP for already ACTIVE bundles
            } catch(Exception e) {
                throw new RuntimeException("Could not start bundle '" + bundle.getSymbolicName() + "'", e);
            }
        }
    }
}
 
Example 17
Source File: XmlDocumentBundleTracker.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void registerReadyMarker(Bundle bundle) {
    String bsn = bundle.getSymbolicName();
    if (!bundleReadyMarkerRegistrations.containsKey(bsn)) {
        ReadyMarker readyMarker = new ReadyMarker(readyMarkerKey, bsn);
        readyService.markReady(readyMarker);
        bundleReadyMarkerRegistrations.put(bsn, readyMarker);
    }
}
 
Example 18
Source File: ClassLoaderUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * When two guava versions installed, want us to load from the *brooklyn* version rather than 
 * a newer version that happens to be in Karaf.
 */
@Test(groups={"Integration"})
public void testLoadsFromRightGuavaVersion() throws Exception {
    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    ClassLoaderUtils clu = new ClassLoaderUtils(getClass(), mgmt);
    
    String bundleUrl = MavenRetriever.localUrl(MavenArtifact.fromCoordinate("com.google.guava:guava:jar:18.0"));
    Bundle bundle = installBundle(mgmt, bundleUrl);
    String bundleName = bundle.getSymbolicName();
    
    String classname = bundleName + ":" + ImmutableList.class.getName();
    assertLoadSucceeds(clu, classname, ImmutableList.class);
}
 
Example 19
Source File: HtmlFolder.java    From olca-app with Mozilla Public License 2.0 4 votes vote down vote up
public static File getDir(Bundle bundle) {
	File htmlDir = new File(App.getWorkspace(), "html");
	return new File(htmlDir, bundle.getSymbolicName());
}
 
Example 20
Source File: ClassLoaderUtils.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public boolean apply(Bundle input) {
    return input.getSymbolicName() != null && input.getVersion() != null &&
            symbolicName.matcher(input.getSymbolicName()).matches() &&
            (version == null || version.matcher(input.getVersion().toString()).matches());
}