Java 类org.osgi.framework.BundleReference 实例源码

项目:carbon-jndi    文件:DefaultContextFactory.java   
/**
 * Returns a BundleContext obtained from the given ClassLoader or from an ancestor ClassLoader.
 * <p>
 * First check whether this ClassLoader implements the BundleReference interface, if so try to get BundleContext.
 * If not get from the parent ClassLoader. Repeat these steps until a not-null BundleContext is found or the parent
 * ClassLoader becomes null.
 *
 * @param classLoaderOptional an {@code Optional} describing a ClassLoader
 * @return BundleContext extracted from the give ClassLoader or from its ancestors ClassLoaders.
 */
private Optional<BundleContext> getCallersBundleContext(Optional<ClassLoader> classLoaderOptional) {

    if (!classLoaderOptional.isPresent()) {
        return Optional.empty();
    }

    Optional<BundleContext> bundleContextOptional = classLoaderOptional
            .filter(classLoader -> classLoader instanceof BundleReference)
            .map(classLoader -> (BundleReference) classLoader)
            .map(bundleReference -> bundleReference.getBundle().getBundleContext());

    if (bundleContextOptional.isPresent()) {
        return bundleContextOptional;
    } else {
        return getCallersBundleContext(Optional.ofNullable(classLoaderOptional.get().getParent()));
    }
}
项目:switchyard    文件:OSGICDISupport.java   
/**
 * Retrieve the BeanManager from the CdiContainer service.
 */
static BeanManager getBeanManager() throws Exception {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader instanceof BundleReference) {
        Bundle bundle = ((BundleReference) classLoader).getBundle();
        ServiceReference<?>[] refs = bundle.getBundleContext().getServiceReferences(
                "org.ops4j.pax.cdi.spi.CdiContainer", "(bundleId=" + bundle.getBundleId() + ")");
        if (refs != null && refs.length == 1) {
            Object cdiContainer = bundle.getBundleContext().getService(refs[0]);
            try {
                Method method = cdiContainer.getClass().getMethod("getBeanManager");
                return (BeanManager) method.invoke(cdiContainer);
            } finally {
                bundle.getBundleContext().ungetService(refs[0]);
            }
        }
    }
    return null;
}
项目:yar    文件:BundleTypeCleaner.java   
@Override
public void typeChanged(TypeEvent typeEvent) {
    switch (typeEvent.eventType()) {
        case ADDED:
            Type type = typeEvent.type();
            Class<?> rawType = getRawType(type);
            ClassLoader classLoader = rawType.getClassLoader();
            if (classLoader instanceof BundleReference) {
                Bundle bundle = ((BundleReference) classLoader).getBundle();
                cache.computeIfAbsent(bundle.getBundleId(), key -> new CopyOnWriteArraySet<>()).add(type);
            } else {
                LOG.warning(type + "'s class loader is not a BundleReference");
            }
            break;
        case REMOVED:
        default:
            // nothing to do
    }
}
项目:extended-objects    文件:OSGiUtil.java   
public static boolean isXOLoadedAsOSGiBundle() {
    if (loadedAsBundle == null) {
        ClassLoader classLoader = OSGiUtil.class.getClassLoader();
        try {
            classLoader.loadClass("org.osgi.framework.BundleReference");
        } catch (ClassNotFoundException e) {
            return false;
        }

        if (classLoader instanceof BundleReference) {
            loadedAsBundle = true;
        } else {
            loadedAsBundle = false;
        }
    }
    return loadedAsBundle;
}
项目:kie-wb-common    文件:Bpmn2JsonUnmarshaller.java   
public Bpmn2JsonUnmarshaller() {
    _helpers = new ArrayList<BpmnMarshallerHelper>();
    DroolsPackageImpl.init();
    BpsimPackageImpl.init();
    // load the helpers to place them in field
    if (getClass().getClassLoader() instanceof BundleReference) {
        BundleContext context = ((BundleReference) getClass().getClassLoader()).
                getBundle().getBundleContext();
        try {
            ServiceReference[] refs = context.getAllServiceReferences(
                    BpmnMarshallerHelper.class.getName(),
                    null);
            for (ServiceReference ref : refs) {
                BpmnMarshallerHelper helper = (BpmnMarshallerHelper) context.getService(ref);
                _helpers.add(helper);
            }
        } catch (InvalidSyntaxException e) {
        }
    }
}
项目:logging-log4j2    文件:BundleContextSelector.java   
@Override
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext,
                                final URI configLocation) {
    if (currentContext) {
        final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
        if (ctx != null) {
            return ctx;
        }
        return getDefault();
    }
    // it's quite possible that the provided ClassLoader may implement BundleReference which gives us a nice shortcut
    if (loader instanceof BundleReference) {
        return locateContext(((BundleReference) loader).getBundle(), configLocation);
    }
    final Class<?> callerClass = StackLocatorUtil.getCallerClass(fqcn);
    if (callerClass != null) {
        return locateContext(FrameworkUtil.getBundle(callerClass), configLocation);
    }
    final LoggerContext lc = ContextAnchor.THREAD_CONTEXT.get();
    return lc == null ? getDefault() : lc;
}
项目:agroal    文件:BasicOSGiTests.java   
/**
 * AgroalDataSource.from( ... ) wont't work due to limitations of ServiceLoader on OSGi environments.
 * For this test, and OSGi deployments in general, the datasource implementation is instantiated directly.
 */
public void probe(BundleReference bundleReference) throws SQLException {
    probeLogger.info( "In OSGi container running from a Bundle named " + bundleReference.getBundle().getSymbolicName() );

    try ( AgroalDataSource dataSource = AgroalDataSource.from( new AgroalDataSourceConfigurationSupplier() ) ) {
        try ( Connection connection = dataSource.getConnection() ) {
            probeLogger.info( format( "Got connection {0}", connection ) );
        }
    }
}
项目:arquillian-liferay    文件:LiferayTestEnricher.java   
private Bundle getBundle(Class<?> testCaseClass) {
    ClassLoader classLoader = testCaseClass.getClassLoader();

    if (classLoader instanceof BundleReference) {
        return ((BundleReference)classLoader).getBundle();
    }

    throw new RuntimeException("Test is not running inside BundleContext");
}
项目:dsl-devkit    文件:GrammarHelper.java   
/**
 * 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;
}
项目:brooklyn-tosca    文件:OsgiAwarePathMatchingResourcePatternResolver.java   
private Bundle getBundle() {
    Bundle bundle = FrameworkUtil.getBundle(getClass());
    if (bundle==null) {
        // it wrong jar is included, it may take the wrong bundle classloader
        LOG.warn("Cannot find bundle for "+this+", loader "+getClass().getClassLoader()+" of type "+getClass().getClassLoader().getClass()+"; is bundle reference? "+(getClass().getClassLoader() instanceof BundleReference));
        LOG.info("Classloaders are: "+getClass().getClassLoader().getClass().getClassLoader()+" / "+BundleReference.class.getClassLoader());
        //                throw new IllegalStateException("Cannot find bundle for "+this+", loader "+getClass().getClassLoader()+" of type "+getClass().getClassLoader().getClass());
    }
    return bundle;
}
项目:Lucee    文件:SystemUtil.java   
private static boolean isFromBundle(Class<?> clazz) {
    if(clazz == null)
        return false;
    if(!(clazz.getClassLoader() instanceof BundleReference))
        return false;

    BundleReference br = (BundleReference)clazz.getClassLoader();
    return !OSGiUtil.isFrameworkBundle(br.getBundle());
}
项目:osgi.ee    文件:PersistenceProviderImpl.java   
@Override
public synchronized EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map props) {
    Bundle bundle = ((BundleReference) info.getClassLoader()).getBundle();
    synchronized (bundles) {
        bundles.add(bundle);
    }
    return provider.createContainerEntityManagerFactory(info, props);
}
项目:wisdom-jdbc    文件:JPATransformer.java   
private List<String> getImports() throws IOException {
    Bundle bundle;
    if (persistenceProvider instanceof BundleReference) {
        bundle = ((BundleReference) persistenceProvider).getBundle();
    } else {
        bundle = FrameworkUtil.getBundle(persistenceProvider.getClass());
    }

    if (bundle != null) {
        // Get the export clauses of the JPA provider.
        Clauses clauses = Clauses.parse(bundle.getHeaders().get(Constants.EXPORT_PACKAGE));
        if (!clauses.isEmpty()) {
            List<String> list = new ArrayList<>();
            for (Map.Entry<String, Map<String, String>> e : clauses.entrySet()) {

                // Create a new clause
                StringBuilder sb = new StringBuilder();
                sb.append(e.getKey());
                for (Map.Entry<String, String> ee : e.getValue().entrySet()) {
                    if (ee.getKey().endsWith(":")) {
                        continue;
                    }

                    sb.append(";").append(ee.getKey()).append("=");
                    String v = ee.getValue();
                    if (WORD.matcher(v).matches()) {
                        sb.append(ee.getValue());
                    }  else {
                        sb.append("\"").append(ee.getValue()).append("\"");
                    }
                }
                list.add(sb.toString());
            }
            // To retrieve the transaction manager.
            list.add("org.wisdom.framework.jpa.accessor");
            return list;
        }
    }
    return Collections.emptyList();
}
项目:pentaho-osgi-bundles    文件:AgileBiPluginResourceLoader.java   
protected String getSymbolicName( ClassLoader classLoader ) {
  if ( classLoader instanceof BundleReference ) {
    Bundle bundle = BundleReference.class.cast( classLoader ).getBundle();
    return bundle.getSymbolicName();
  } else {
    return null;
  }
}
项目:arquillian-extension-liferay    文件:LiferayTestEnricher.java   
private Bundle getBundle(Class<?> testCaseClass) {
    ClassLoader classLoader = testCaseClass.getClassLoader();

    if (classLoader instanceof BundleReference) {
        return ((BundleReference)classLoader).getBundle();
    }

    throw new RuntimeException("Test is not running inside BundleContext");
}
项目:gravia    文件:ModuleAdaptor.java   
ModuleAdaptor(OSGiRuntime runtime, ClassLoader classLoader, Resource resource, Dictionary<String, String> headers) {
    super(runtime, classLoader, resource, headers);
    if (classLoader instanceof BundleReference) {
        bundle = ((BundleReference) classLoader).getBundle();
    } else {
        bundle = runtime.getSystemContext().getBundle();
    }
}
项目:subsystem-examples    文件:Pepperoni.java   
@Override
public String getName() {
    ClassLoader cl = getClass().getClassLoader();
    BundleReference br = (BundleReference) cl;
    return "Pepperoni (" + br.getBundle().getSymbolicName() + ")";
}
项目:subsystem-examples    文件:QuattroStagioni.java   
@Override
public String getName() {
    ClassLoader cl = getClass().getClassLoader();
    BundleReference br = (BundleReference) cl;
    return "Quattro Stagioni (" + br.getBundle().getSymbolicName() + ")";
}
项目:ManagedProperties    文件:ManagedPropertiesServiceFactory.java   
@Override
   public <T> T register(Class<T> type) throws InvalidTypeException, TypeFilterException, DoubleIDException, InvalidMethodException, InvocationException, ControllerPersistenceException {
BundleContext context = BundleReference.class.cast(type.getClassLoader()).getBundle().getBundleContext();
return register(type, context);
   }
项目:ManagedProperties    文件:ManagedPropertiesServiceFactory.java   
@Override
   public <I, T extends I> I register(Class<I> type, T defaults) throws InvalidTypeException, TypeFilterException, DoubleIDException, InvalidMethodException, InvocationException, ControllerPersistenceException {
BundleContext context = BundleReference.class.cast(type.getClassLoader()).getBundle().getBundleContext();
return register(type, defaults, context);
   }
项目:osgi.ee    文件:CompoundClassLoader.java   
@Override
public Bundle getBundle() {
    return ((BundleReference) getParent()).getBundle();
}
项目:bundles    文件:JPAManager.java   
/**
 * Calculate the imports of the persistence provider. Since this guy is
 * running, it must have satisfied all its imports. So we use those exact
 * imports and add them to our transformed classes, this will ensure that
 * any classes that the Persistence Provider needs from that class will be
 * satisfied.
 * 
 * @param pp Persistence Provider for this unit
 * @return A list of import clauses from the provider
 */

private List<String> getImports(PersistenceProvider pp) throws IOException {
    //
    // Check if this pp is a bridge that is aware of
    // what we're doing
    //
    if (pp instanceof JPABridgePersistenceProvider) {
        List<String> wovenImports = ((JPABridgePersistenceProvider) pp).getWovenImports();
        if (wovenImports != null)
            return wovenImports;
    }

    //
    // Get the pp's class's bundle's context
    //
    Bundle b;
    if (pp instanceof BundleReference)
        b = ((BundleReference) pp).getBundle();
    else
        b = FrameworkUtil.getBundle(pp.getClass());

    if (b != null) {
        //
        // Get the import clauses
        //
        Clauses clauses = Clauses.parse(b.getHeaders().get("Export-Package"), null);
        if (!clauses.isEmpty()) {
            List<String> list = new ArrayList<String>();
            for (Entry<String, Map<String, String>> e : clauses.entrySet()) {

                //
                // Create a new clause
                //
                StringBuilder sb = new StringBuilder();
                sb.append(e.getKey());
                for (Entry<String, String> ee : e.getValue().entrySet()) {
                    if (ee.getKey().endsWith(":"))
                        continue;

                    sb.append(";").append(ee.getKey()).append("=");
                    String v = ee.getValue();
                    if (WORD.matcher(v).matches())
                        sb.append(ee.getValue());
                    else
                        sb.append("\"").append(ee.getValue()).append("\"");
                }
                list.add(sb.toString());
            }
            return list;
        }
    }
    return Collections.emptyList();
}
项目:gravia    文件:FragmentTest.java   
@Test
public void testAttachedFragment() throws Exception {

    Runtime runtime = RuntimeLocator.getRequiredRuntime();
    ModuleContext rtcontext = runtime.getModuleContext();

    final List<String> events = new ArrayList<String>();
    ModuleListener listener = new SynchronousModuleListener() {
        @Override
        public void moduleChanged(ModuleEvent event) {
            Module module = event.getModule();
            String modid = module.getIdentity().toString();
            String evtid = ConstantsHelper.moduleEvent(event.getType());
            String message = modid + ":" + evtid;
            events.add(message);
        }
    };
    rtcontext.addModuleListener(listener);

    // Deploy the fragment
    InputStream input = deployer.getDeployment(GOOD_FRAGMENT);
    Bundle fragment = bundleContext.installBundle(GOOD_FRAGMENT, input);
    try {
        Assert.assertTrue(events.isEmpty());

        // Deploy the bundle
        input = deployer.getDeployment(GOOD_BUNDLE);
        Bundle host = bundleContext.installBundle("bundle-host-attached", input);
        try {
            Class<?> clazz = OSGiTestHelper.assertLoadClass(host, "org.jboss.test.gravia.runtime.osgi.sub.a.AttachedType");
            Assert.assertSame(host, ((BundleReference) clazz.getClassLoader()).getBundle());
            Assert.assertEquals(1, events.size());
            Assert.assertEquals("good-bundle:0.0.0:INSTALLED", events.remove(0));
        } finally {
            host.uninstall();
            Assert.assertEquals(1, events.size());
            Assert.assertEquals("good-bundle:0.0.0:UNINSTALLED", events.remove(0));
        }
    } finally {
        fragment.uninstall();
        Assert.assertTrue(events.isEmpty());
    }
}