下面列出了org.osgi.framework.Bundle#loadClass ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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));
}
}
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) {
}
}
@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);
}
@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);
}
}
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));
}
@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);
}
}
/**
* 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);
}
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;
}
@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();
}
}
@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;
}
}
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;
}
}
@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);
}
}
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;
}
/**
* 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;
}
/**
* 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;
}
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);
}
}
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");
}