/** * 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())); } }
/** * 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; }
@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 } }
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; }
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) { } } }
@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; }
/** * 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 ) ); } } }
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"); }
/** * 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; }
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; }
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()); }
@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); }
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(); }
protected String getSymbolicName( ClassLoader classLoader ) { if ( classLoader instanceof BundleReference ) { Bundle bundle = BundleReference.class.cast( classLoader ).getBundle(); return bundle.getSymbolicName(); } else { return null; } }
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(); } }
@Override public String getName() { ClassLoader cl = getClass().getClassLoader(); BundleReference br = (BundleReference) cl; return "Pepperoni (" + br.getBundle().getSymbolicName() + ")"; }
@Override public String getName() { ClassLoader cl = getClass().getClassLoader(); BundleReference br = (BundleReference) cl; return "Quattro Stagioni (" + br.getBundle().getSymbolicName() + ")"; }
@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); }
@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); }
@Override public Bundle getBundle() { return ((BundleReference) getParent()).getBundle(); }
/** * 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(); }
@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()); } }