org.osgi.framework.Bundle#loadClass ( )源码实例Demo

下面列出了org.osgi.framework.Bundle#loadClass ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: eclipse-cs   文件: ExtensionClassLoader.java
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {

  Class<?> cl = null;

  for (Bundle bundle : mBundles) {

    try {
      cl = bundle.loadClass(name);
      if (cl != null) {
        break;
      }
    } catch (ClassNotFoundException e) {
      // try next
    }
  }

  if (cl == null) {
    throw new ClassNotFoundException(name);
  }

  return cl;
}
 
@Override
public void setInitializationData(IConfigurationElement config, String propertyName, Object data)
    throws CoreException {
    if (data == null || !(data instanceof String)) {
      throw new CoreException(StatusUtil.error(getClass(), "Data must be a class name"));
    }
    String className = (String) data;
    String bundleSymbolicName = config.getNamespaceIdentifier();
    Bundle bundle = Platform.getBundle(bundleSymbolicName);
    if (bundle == null) {
      throw new CoreException(StatusUtil.error(this, "Missing bundle " + bundleSymbolicName));
    }
    try {
      clazz = bundle.loadClass(className);
    } catch (ClassNotFoundException ex) {
      throw new CoreException(StatusUtil.error(this,
                                               "Could not load class " + className
                                               + " from bundle " + bundle.getSymbolicName(),
                                               ex));
    }
}
 
源代码3 项目: tmxeditor8   文件: SelfBaseHelpSystem.java
public static void runLiveHelp(String pluginID, String className, String arg) {	
	Bundle bundle = Platform.getBundle(pluginID);
	if (bundle == null) {
		return;
	}

	try {
		Class c = bundle.loadClass(className);
		Object o = c.newInstance();
		//Runnable runnable = null;
		if (o != null && o instanceof ILiveHelpAction) {
			ILiveHelpAction helpExt = (ILiveHelpAction) o;
			if (arg != null)
				helpExt.setInitializationString(arg);
			Thread runnableLiveHelp = new Thread(helpExt);
			runnableLiveHelp.setDaemon(true);
			runnableLiveHelp.start();
		}
	} catch (ThreadDeath td) {
		throw td;
	} catch (Exception e) {
	}
}
 
源代码4 项目: brooklyn-server   文件: ClassLoaderUtilsTest.java
@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);
}
 
源代码5 项目: vespa   文件: OsgiImpl.java
@SuppressWarnings("unchecked")
private static Class<Object> resolveFromBundle(BundleInstantiationSpecification spec, Bundle bundle) {
    try {
        ensureBundleActive(bundle);
        return (Class<Object>) bundle.loadClass(spec.classId.getName());
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("Could not load class '" + spec.classId.getName() +
                                           "' from bundle " + bundle, e);
    }
}
 
源代码6 项目: tmxeditor8   文件: SelfDisplayUtils.java
private static void invoke(String method) {
	try {
		Bundle bundle = Platform.getBundle(HELP_UI_PLUGIN_ID);
		if (bundle == null) {
			return;
		}
		Class c = bundle.loadClass(LOOP_CLASS_NAME);
		Method m = c.getMethod(method, new Class[]{});
		m.invoke(null, new Object[]{});
	} catch (Exception e) {
	}
}
 
@Test
public void testRenamedOsgiClassMovedBundle() 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;
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), bundlePath);
    
    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = installBundle(mgmt, bundleUrl);
    
    String oldBundlePrefix = "com.old.symbolicname";
    
    String bundlePrefix = bundle.getSymbolicName();
    Class<?> osgiObjectClazz = bundle.loadClass(classname);
    Object obj = Reflections.invokeConstructorFromArgs(osgiObjectClazz, "myval").get();

    serializer = new XmlMementoSerializer<Object>(mgmt.getCatalogClassLoader(),
            ImmutableMap.of(oldBundlePrefix + ":" + classname, bundlePrefix + ":" + 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, oldBundlePrefix + ":" + classname));
}
 
源代码8 项目: brooklyn-server   文件: XmlSerializerOsgiTest.java
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    int separator = name.indexOf(":");
    if (separator>=0) {
        Bundle bundle = Osgis.bundleFinder(framework).symbolicName(name.substring(0, separator)).find().get();
        return bundle.loadClass(name.substring(separator+1));
    } else {
        return super.loadClass(name, resolve);
    }
}
 
源代码9 项目: depan   文件: PluginClassLoader.java
/**
 * Try to load classes from the known list of bundles, in order.
 * If all of those fail, delegate to the super class.
 */
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
  for (Bundle bundle: pluginBundles) {
    // try to load the class one plugin after the other. stop on the first
    // plugin providing the corresponding class.
    try {
      return bundle.loadClass(name);
    } catch (ClassNotFoundException e) {
    }
  }
  return super.loadClass(name);
}
 
源代码10 项目: neoscada   文件: DefaultExecutableFactory.java
private Class<?> findBundle ( final String symbolicName, final String clazzName )
{
    logger.debug ( "Find bundle with class - symbolicName: {}, className: {}", symbolicName, clazzName );

    final BundleContext context = FrameworkUtil.getBundle ( DefaultExecutableFactory.class ).getBundleContext ();

    for ( final Bundle bundle : context.getBundles () )
    {
        if ( !symbolicName.equals ( bundle.getSymbolicName () ) )
        {
            continue;
        }

        logger.debug ( "Checking bundle: {}", bundle.getSymbolicName () );

        Class<?> clazz;
        try
        {
            clazz = bundle.loadClass ( clazzName );
        }
        catch ( final ClassNotFoundException e )
        {
            logger.debug ( "Class could not be loaded", e );
            // we continue, since we might have multiple versions
            continue;
        }

        logger.debug ( "Success" );
        return clazz;
    }

    return null;
}
 
源代码11 项目: M2Doc   文件: EclipseClassProvider.java
@Override
public Class<?> getClass(String className, String bundleName) throws ClassNotFoundException {
    final Class<?> res;

    final Bundle bundle = bundles.get(bundleName);
    if (bundle != null) {
        res = bundle.loadClass(className);
    } else {
        res = super.getClass(className, bundleName);
    }

    return res;
}
 
@Test
public void testRegistryEventListener() throws Exception {
	loadBundles(Arrays.asList(getBundle("testresources", "jdt.ls.extension-0.0.1.jar")));
	String bundleLocation = getBundleLocation(getBundle("testresources", "jdt.ls.extension-0.0.1.jar"), true);

	BundleContext context = JavaLanguageServerPlugin.getBundleContext();
	Bundle installedBundle = context.getBundle(bundleLocation);
	try {
		assertNotNull(installedBundle);

		assertTrue(installedBundle.getState() == Bundle.STARTING || installedBundle.getState() == Bundle.ACTIVE);
		installedBundle.loadClass("jdt.ls.extension.Activator");
		assertEquals(installedBundle.getState(), Bundle.ACTIVE);

		Set<String> extensionCommands = WorkspaceExecuteCommandHandler.getInstance().getAllCommands();
		assertTrue(extensionCommands.contains("jdt.ls.extension.command1"));
		assertTrue(extensionCommands.contains("jdt.ls.extension.command2"));

		loadBundles(Arrays.asList(getBundle("testresources", "jdt.ls.extension-0.0.2.jar")));
		bundleLocation = getBundleLocation(getBundle("testresources", "jdt.ls.extension-0.0.2.jar"), true);

		installedBundle = context.getBundle(bundleLocation);
		assertNotNull(installedBundle);
		assertTrue(installedBundle.getState() == Bundle.STARTING || installedBundle.getState() == Bundle.ACTIVE);
		installedBundle.loadClass("jdt.ls.extension.Activator");
		assertEquals(installedBundle.getState(), Bundle.ACTIVE);

		extensionCommands = WorkspaceExecuteCommandHandler.getInstance().getAllCommands();
		assertTrue(extensionCommands.contains("jdt.ls.extension.command2"));
		assertTrue(extensionCommands.contains("jdt.ls.extension.command3"));
		assertFalse(extensionCommands.contains("jdt.ls.extension.command1"));
	} finally {
		// Uninstall the bundle to clean up the testing bundle context.
		installedBundle.uninstall();
	}
}
 
源代码13 项目: Pydev   文件: JythonPlugin.java
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Class loadClass(String className) throws ClassNotFoundException {
    try {
        return super.loadClass(className);
    } catch (ClassNotFoundException e) {
        String searchedClass = e.getMessage();
        for (int i = 0; i < PACKAGES_MUST_START_WITH.length; i++) {
            if (searchedClass.startsWith(PACKAGES_MUST_START_WITH[i])) {

                // Look for the class from the bundles.
                int len = bundles.length;
                for (int j = 0; j < len; ++j) {
                    try {
                        Bundle bundle = bundles[j];
                        if (bundle.getState() == Bundle.ACTIVE) {
                            return bundle.loadClass(className);
                        }
                    } catch (Throwable e2) {
                    }
                }

                break;
            }
        }
        // Didn't find the class anywhere, rethrow e.
        throw e;
    }
}
 
源代码14 项目: nexus-public   文件: FeatureFlaggedIndex.java
private static boolean isFeatureFlagDisabled(final Bundle bundle, final String clazzName) {
  try {
    Class<?> clazz = bundle.loadClass(clazzName);
    FeatureFlag flag = clazz.getAnnotation(FeatureFlag.class);
    return !getBoolean(flag.name(), flag.enabledByDefault());
  }
  catch (Exception | LinkageError e) {
    log.debug("Cannot determine feature-flag for {}; assuming false", clazzName, e);
    return false;
  }
}
 
源代码15 项目: brooklyn-server   文件: XmlSerializerOsgiTest.java
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
    int separator = name.indexOf(":");
    if (separator>=0) {
        Bundle bundle = Osgis.bundleFinder(framework).symbolicName(name.substring(0, separator)).find().get();
        return bundle.loadClass(name.substring(separator+1));
    } else {
        return super.findClass(name);
    }
}
 
源代码16 项目: logging-log4j2   文件: AbstractLoadBundleTest.java
private PrintStream setupStream(final Bundle api, final PrintStream newStream) throws ReflectiveOperationException {
    // use reflection to access the classes internals and in the context of the api bundle

    final Class<?> statusLoggerClass = api.loadClass("org.apache.logging.log4j.status.StatusLogger");

    final Field statusLoggerField = statusLoggerClass.getDeclaredField("STATUS_LOGGER");
    statusLoggerField.setAccessible(true);
    final Object statusLoggerFieldValue = statusLoggerField.get(null);

    final Field loggerField = statusLoggerClass.getDeclaredField("logger");
    loggerField.setAccessible(true);
    final Object loggerFieldValue = loggerField.get(statusLoggerFieldValue);

    final Class<?> simpleLoggerClass = api.loadClass("org.apache.logging.log4j.simple.SimpleLogger");

    final Field streamField = simpleLoggerClass.getDeclaredField("stream");
    streamField.setAccessible(true);

    final PrintStream oldStream = (PrintStream) streamField.get(loggerFieldValue);

    streamField.set(loggerFieldValue, newStream);

    return oldStream;
}
 
源代码17 项目: birt   文件: BirtWizardUtil.java
/**
 * get default resource folder setting
 * 
 * @return
 */
public static String getDefaultResourceFolder( )
{
	String resourceFolder = ""; //$NON-NLS-1$

	try
	{
		// check if load plugin
		Bundle bundle = Platform.getBundle( REPORT_PLUGIN_ID );
		if ( bundle == null )
			return resourceFolder;

		// get class
		Class reportPluginClass = bundle.loadClass( REPORT_PLUGIN_CLASS );
		if ( reportPluginClass != null )
		{
			// get instance
			Method method = reportPluginClass.getMethod( "getDefault", new Class[0] ); //$NON-NLS-1$
			Object instance = null;
			if ( method != null )
			{
				instance = method.invoke( null, new Object[0] );
				method = reportPluginClass.getMethod( "getResourcePreference", new Class[0] ); //$NON-NLS-1$
			}

			if ( method != null && instance != null )
			{
				// invode "getResourcePreference" method
				resourceFolder = (String) method.invoke( instance,
						new Object[0] );
			}
		}
	}
	catch ( Exception e )
	{
		e.printStackTrace( );
	}

	if ( resourceFolder == null )
		resourceFolder = ""; //$NON-NLS-1$

	return resourceFolder;
}
 
源代码18 项目: birt   文件: BirtWizardUtil.java
/**
 * get default resource folder setting
 * 
 * @return
 */
public static String getDefaultResourceFolder( )
{
	String resourceFolder = ""; //$NON-NLS-1$

	try
	{
		// check if load plugin
		Bundle bundle = Platform.getBundle( REPORT_PLUGIN_ID );
		if ( bundle == null )
			return resourceFolder;

		// get class
		Class reportPluginClass = bundle.loadClass( REPORT_PLUGIN_CLASS );
		if ( reportPluginClass != null )
		{
			// get instance
			Method method = reportPluginClass.getMethod(
					"getDefault", new Class[0] ); //$NON-NLS-1$
			Object instance = null;
			if ( method != null )
			{
				instance = method.invoke( null, new Object[0] );
				method = reportPluginClass.getMethod(
						"getResourcePreference", new Class[0] ); //$NON-NLS-1$
			}

			if ( method != null && instance != null )
			{
				// invode "getResourcePreference" method
				resourceFolder = (String) method.invoke( instance,
						new Object[0] );
			}
		}
	}
	catch ( Exception e )
	{
		e.printStackTrace( );
	}

	if ( resourceFolder == null )
		resourceFolder = ""; //$NON-NLS-1$

	return resourceFolder;
}
 
源代码19 项目: incubator-tamaya   文件: OSGIServiceLoader.java
private void processEntryPath(Bundle bundle, String entryPath) {
    try {
        String serviceName = entryPath.substring(META_INF_SERVICES.length());
        if (!serviceName.startsWith("org.apache.tamaya")) {
            // Ignore non Tamaya entries...
            return;
        }
        Class<?> serviceClass = bundle.loadClass(serviceName);
        URL child = bundle.getEntry(entryPath);
        InputStream inStream = child.openStream();
        LOG.info("Loading Services " + serviceClass.getName() + " from bundle...: " + bundle.getSymbolicName());
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8))) {
            String line = br.readLine();
            while (line != null) {
                String implClassName = getImplClassName(line);
                if (implClassName.length() > 0) {
                    try {
                        // Load the service class
                        LOG.fine("Loading Class " + implClassName + " from bundle...: " + bundle.getSymbolicName());
                        Class<?> implClass = bundle.loadClass(implClassName);
                        if (!serviceClass.isAssignableFrom(implClass)) {
                            LOG.warning("Configured service: " + implClassName + " is not assignable to "
                                    + serviceClass.getName());
                            continue;
                        }
                        LOG.info("Loaded Service Factory (" + serviceName + "): " + implClassName);
                        // Provide service properties
                        Hashtable<String, String> props = new Hashtable<>();
                        props.put(Constants.VERSION_ATTRIBUTE, bundle.getVersion().toString());
                        String vendor = bundle.getHeaders().get(Constants.BUNDLE_VENDOR);
                        props.put(Constants.SERVICE_VENDOR, (vendor != null ? vendor : "anonymous"));
                        // Translate annotated @Priority into a service ranking
                        props.put(Constants.SERVICE_RANKING,
                                String.valueOf(PriorityServiceComparator.getPriority(implClass)));

                        // Register the service factory on behalf of the intercepted bundle
                        JDKUtilServiceFactory factory = new JDKUtilServiceFactory(implClass);
                        BundleContext bundleContext = bundle.getBundleContext();
                        bundleContext.registerService(serviceName, factory, props);
                        LOG.info("Registered Tamaya service class: " + implClassName + "(" + serviceName + ")");
                    } catch (NoClassDefFoundError | Exception err) {
                        LOG.log(Level.SEVERE, "Failed to load service: " + implClassName, err);
                    }
                }
                line = br.readLine();
            }
        }
    } catch (RuntimeException rte) {
        throw rte;
    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Failed to read services from: " + entryPath, e);
    }
}
 
源代码20 项目: logging-log4j2   文件: AbstractLoadBundleTest.java
private void log(final Bundle dummy) throws ReflectiveOperationException {
    // use reflection to log in the context of the dummy bundle

    final Class<?> logManagerClass = dummy.loadClass("org.apache.logging.log4j.LogManager");
    final Method getLoggerMethod = logManagerClass.getMethod("getLogger", Class.class);

    final Class<?> loggerClass = dummy.loadClass("org.apache.logging.log4j.configuration.CustomConfiguration");

    final Object logger = getLoggerMethod.invoke(null, loggerClass);
    final Method errorMethod = logger.getClass().getMethod("error", Object.class);

    errorMethod.invoke(logger, "Test OK");
}