@Override public byte[] processClass(String className, byte[] bytes, ClasspathEntry ce, BundleEntry be, ClasspathManager cm) { final BaseData bd = ce.getBaseData(); if (bd == null) { return bytes; } final Bundle b = bd.getBundle(); if (b == null) { return bytes; } BundleWiring w = b.adapt(org.osgi.framework.wiring.BundleWiring.class); if (w == null) { return bytes; } ClassLoader loader = w.getClassLoader(); return archive.patchByteCode(loader, className, ce.getDomain(), bytes); }
/** * Checks if is required bundle. * * @param bundle the bundle * @param className the class name * @return true, if is required bundle */ private boolean isRequiredBundle(Bundle bundle, String className) { // --- 1. Simply try to load the class ---------------------- try { Class<?> classInstance = bundle.loadClass(className); if (classInstance!=null) return true; } catch (ClassNotFoundException cnfEx) { //cnfEx.printStackTrace(); } // --- 2. Try to check the resources of the bundle ---------- String simpleClassName = className.substring(className.lastIndexOf(".")+1); String packagePath = className.substring(0, className.lastIndexOf(".")); packagePath = packagePath.replace(".", "/"); if (packagePath.startsWith("/")==false) packagePath = "/" + packagePath; if (packagePath.endsWith("/") ==false) packagePath = packagePath + "/"; BundleWiring bundleWiring = bundle.adapt(BundleWiring.class); Collection<String> resources = bundleWiring.listResources(packagePath, simpleClassName + ".class", BundleWiring.LISTRESOURCES_LOCAL); if (resources!=null && resources.size()>0) { return true; } return false; }
private boolean incompatibleExtender(Bundle bundle) { List<BundleWire> requiredWires = bundle.adapt(BundleWiring.class) .getRequiredWires(OSGI_EXTENDER_NS); for(BundleWire bw : requiredWires) { BundleCapability capability = bw.getCapability(); if(EntityManagerFactoryBuilder.JPA_CAPABILITY_NAME.equals( capability.getAttributes().get(OSGI_EXTENDER_NS))) { // If the persistence bundle requires a different revision for the // JPA extender then we are incompatible, otherwise we are return !capability.getRevision().equals(wiring.getRevision()); } } // If there is no requirement then we must assume that it's safe return false; }
public WrappingTransformer(ClassTransformer delegate, ServiceReference<?> persistenceProvider) { validate(delegate, persistenceProvider); this.delegate = delegate; Object packages = persistenceProvider.getProperty("org.apache.aries.jpa.container.weaving.packages"); if (packages instanceof String[]) { for (String s : (String[])packages) { packageImportsToAdd.add(s); } } else { Bundle provider = persistenceProvider.getBundle(); String suffix = ";" + Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE + "=" + provider.getSymbolicName() + ";" + Constants.BUNDLE_VERSION_ATTRIBUTE + "=" + provider.getVersion(); BundleRevision br = provider.adapt(BundleWiring.class).getRevision(); for (BundleCapability bc : br.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) { packageImportsToAdd.add(bc.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE) + suffix); } } }
@Override public void weave(WovenClass wovenClass) { BundleWiring wiring = wovenClass.getBundleWiring(); Bundle bundle = wiring.getBundle(); ClassLoader cl = wiring.getClassLoader(); Collection<ClassTransformer> transformersToTry = getTransformers(bundle); for (ClassTransformer transformer : transformersToTry) { if (transformClass(wovenClass, cl, transformer)) { LOGGER.info("Weaving " + wovenClass.getClassName() + " using " + transformer.getClass().getName()); break; } } Class<?> dClass = wovenClass.getDefinedClass(); if (transformersToTry.isEmpty() && dClass != null && dClass.getAnnotation(Entity.class) != null) { LOGGER.warn("Loading " + wovenClass.getClassName() + " before transformer is present"); } }
/** * Get all the relevant packages that the EclipseLink JPA provider exports or persistence packages it uses itself. These are needed * so that the woven proxy (for runtime enhancement) can be used later on :) * * Note that differently to OpenJPA the relevant classes are actually in more than just one bundle (org.eclipse.persistence.jpa and org.eclipse.persistence.core * at the time of this writing). Hence, we have to take more than just the packages of the JPA provider bundle into account ... * * @param jpaBundle * @return */ private String[] getJPAPackages(Bundle jpaBundle) { Set<String> result = new HashSet<String>(); for (Bundle b : context.getBundles()) { BundleWiring bw = b.adapt(BundleWiring.class); if (bw == null) { continue; } boolean isJpaBundle = b.equals(jpaBundle); List<BundleWire> wires = bw.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE); for (BundleWire w : wires) { String pkgName = (String)w.getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE); boolean add = isJpaBundle || pkgName.startsWith("org.eclipse.persistence"); if (add) { result.add(getPkg(b, pkgName)); } } } result.add(getPkg(context.getBundle(), "org.apache.aries.jpa.eclipselink.adapter.platform")); LOG.debug("Found JPA packages {}", result); return result.toArray(new String[0]); }
<T> List<Class<? extends T>> findSubTypesOf(Bundle bundle, Collection<Class<T>> superclasses) { BundleWiring wiring = bundle.adapt(BundleWiring.class); Collection<String> names = wiring .listResources("/", "*", BundleWiring.LISTRESOURCES_RECURSE); return names.stream().map(new Function<String, Class<?>>() { @Override @SneakyThrows public Class<?> apply(String name) { String n = name.replaceAll("\\.class$", "").replace('/', '.'); try { return bundle.loadClass(n); } catch (ClassNotFoundException | NoClassDefFoundError e) { return null; } } }).filter(c -> c != null) .filter(c -> superclasses.stream().anyMatch(sc -> sc.isAssignableFrom(c))) .filter(c -> c.isAnnotationPresent(GraphQLMutation.class)) .filter(c -> !c.isInterface() && !Modifier.isAbstract(c.getModifiers())) .map((Function<Class<?>, Class<? extends T>>) aClass -> (Class<? extends T>) aClass) .collect(Collectors.toList()); }
static Set<String> getClassNames(Bundle bundle) { BundleWiring bundleWiring = bundle.adapt(BundleWiring.class); if (bundleWiring == null) return Collections.emptySet(); Collection<String> resources = bundleWiring.listResources("/", "*.class", BundleWiring.LISTRESOURCES_RECURSE); Set<String> classNamesOfCurrentBundle = new HashSet<>(); for (String resource : resources) { URL localResource = bundle.getEntry(resource); // Bundle.getEntry() returns null if the resource is not located in the specific bundle if (localResource != null) { String className = resource.replaceAll("/", ".").replaceAll("^(.*?)(\\.class)$", "$1"); classNamesOfCurrentBundle.add(className); } } return classNamesOfCurrentBundle; }
private <T> List<Class<? extends T>> findSubTypesOf(Bundle bundle, Collection<Class<T>> superclasses) { BundleWiring wiring = bundle.adapt(BundleWiring.class); Collection<String> names = wiring .listResources("/", "*", BundleWiring.LISTRESOURCES_RECURSE); return names.stream().map(new Function<String, Class<?>>() { @Override @SneakyThrows public Class<?> apply(String name) { String n = name.replaceAll("\\.class$", "").replace('/', '.'); try { return bundle.loadClass(n); } catch (ClassNotFoundException | NoClassDefFoundError e) { return null; } } }).filter(c -> c != null).filter(c -> superclasses.stream().anyMatch(sc -> sc.isAssignableFrom(c))) .filter(c -> !c.isInterface() && !Modifier.isAbstract(c.getModifiers())) .map((Function<Class<?>, Class<? extends T>>) aClass -> (Class<? extends T>) aClass) .collect(Collectors.toList()); }
@SuppressWarnings({ "rawtypes" }) public void testGetService() throws ClassNotFoundException { final Object myTestProxyObject = new Object(); IMocksControl control = EasyMock.createControl(); EndpointDescription endpoint = createTestEndpointDesc(); ImportRegistrationImpl iri = new ImportRegistrationImpl(endpoint, null); BundleContext consumerContext = control.createMock(BundleContext.class); Bundle consumerBundle = control.createMock(Bundle.class); BundleWiring bundleWiring = control.createMock(BundleWiring.class); EasyMock.expect(bundleWiring.getClassLoader()).andReturn(this.getClass().getClassLoader()); EasyMock.expect(consumerBundle.adapt(BundleWiring.class)).andReturn(bundleWiring); EasyMock.expect(consumerBundle.getBundleContext()).andReturn(consumerContext); ServiceRegistration sreg = control.createMock(ServiceRegistration.class); DistributionProvider handler = mockDistributionProvider(myTestProxyObject); control.replay(); ClientServiceFactory csf = new ClientServiceFactory(endpoint, handler, iri); assertSame(myTestProxyObject, csf.getService(consumerBundle, sreg)); }
@Override public BundleClasses getBundleClasses(ComponentSpecification bundleSpec, Set<String> packagesToScan) { //Not written in an OO way since FelixFramework resides in JDisc core which for now is pure java, //and to load from classpath one needs classes from scalalib. //Temporary hack: Using class name since ClassLoaderOsgiFramework is not available at compile time in this bundle. if (osgiFramework.getClass().getName().equals("com.yahoo.application.container.impl.ClassLoaderOsgiFramework")) { Bundle syntheticClassPathBundle = first(osgiFramework.bundles()); ClassLoader classLoader = syntheticClassPathBundle.adapt(BundleWiring.class).getClassLoader(); return new BundleClasses( syntheticClassPathBundle, OsgiUtil.getClassEntriesForBundleUsingProjectClassPathMappings(classLoader, bundleSpec, packagesToScan)); } else { Bundle bundle = getBundle(bundleSpec); if (bundle == null) throw new RuntimeException("No bundle matching " + quote(bundleSpec)); return new BundleClasses(bundle, OsgiUtil.getClassEntriesInBundleClassPath(bundle, packagesToScan)); } }
public LayerFactoryImpl(Activator activator, BundleContext context, Module systemModule) { String layerTypeProp = context.getProperty("osgi.jpms.layer.type"); this.layerType = layerTypeProp == null ? LayerType.OneBundlePerLayerWithHierarchy : LayerType.valueOf(layerTypeProp); this.activator = activator; this.context = context; this.systemModule = systemModule; long startTime = System.nanoTime(); privatesCache = loadPrivatesCache(context, activator); System.out.println("Time loadPrivatesCache: " + TimeUnit.MILLISECONDS.convert((System.nanoTime() - startTime), TimeUnit.NANOSECONDS)); Bundle systemBundle = context.getBundle(Constants.SYSTEM_BUNDLE_LOCATION); fwkWiring = systemBundle.adapt(FrameworkWiring.class); ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); layersWrite = lock.writeLock(); layersRead = lock.readLock(); BundleWiring systemWiring = systemBundle.adapt(BundleWiring.class); addToResolutionGraph(Collections.singleton(systemWiring)); wiringToModule.put(systemWiring, systemModule); }
private Set<BundleWiring> getInUseBundleWirings() { Set<BundleWiring> wirings = new HashSet<>(); Collection<BundleCapability> bundles = fwkWiring.findProviders(ALL_BUNDLES_REQUIREMENT); for (BundleCapability bundleCap : bundles) { // Only pay attention to non JPMS boot modules. // NOTE this means we will not create a real JPMS Module or Layer for this bundle if (bundleCap.getAttributes().get(BOOT_JPMS_MODULE) == null) { BundleRevision revision = bundleCap.getRevision(); BundleWiring wiring = revision.getWiring(); if (wiring != null && wiring.isInUse()) { wirings.add(wiring); } if (revision.getBundle().getBundleId() == 0) { // also store the system.bundle fragments because they may have exports unknown to JPMS List<BundleWire> hostWires = wiring.getProvidedWires(HostNamespace.HOST_NAMESPACE); for (BundleWire hostWire : hostWires) { wirings.add(hostWire.getRequirerWiring()); } } } } return wirings; }
private void addReadsNest(Map<BundleWiring, Module> wiringToModule) { long addReadsNestStart = System.nanoTime(); Set<Module> bootModules = ModuleLayer.boot().modules(); Collection<Module> allBundleModules = wiringToModule.values(); // Not checking for existing edges for simplicity. for (Module module : allBundleModules) { if (!systemModule.equals(module)) { // First add reads to all boot modules. addReads(module, bootModules); // Now ensure bidirectional read of all bundle modules. addReads(module, allBundleModules); // Add read to the system.bundle module. addReads(module, Collections.singleton(systemModule)); } } System.out.println("Time to addReadsNest: " + TimeUnit.MILLISECONDS.convert((System.nanoTime() - addReadsNestStart), TimeUnit.NANOSECONDS)); }
private void addToResolutionGraph(Set<BundleWiring> currentWirings) { long startAddToGraph = System.nanoTime(); currentWirings.forEach((w) -> addToGraph(w)); System.out.println("Time addToGraph: " + TimeUnit.MILLISECONDS.convert((System.nanoTime() - startAddToGraph), TimeUnit.NANOSECONDS)); long startAddWires = System.nanoTime(); for (Iterator<ResolutionGraph.Node> nodes = graph.iterator(); nodes.hasNext();) { ResolutionGraph.Node n = nodes.next(); if (!currentWirings.contains(n.getValue()) && n.getValue().getBundle().getBundleId() != 0) { nodes.remove(); } else { addWires(n); } } System.out.println("Time addWires: " + TimeUnit.MILLISECONDS.convert((System.nanoTime() - startAddWires), TimeUnit.NANOSECONDS)); long startPopulateSources = System.nanoTime(); graph.populateSources(); System.out.println("Time populateSources: " + TimeUnit.MILLISECONDS.convert((System.nanoTime() - startPopulateSources), TimeUnit.NANOSECONDS)); }
private boolean extenderCapabilityWired(Bundle bundle) { BundleWiring wiring = bundle.adapt(BundleWiring.class); if (wiring == null) { return true; } List<BundleWire> requiredWires = wiring.getRequiredWires(EXTENDER_NAMESPACE); for (BundleWire requiredWire : requiredWires) { if (CAMEL_EXTENDER.equals(requiredWire.getCapability().getAttributes().get(EXTENDER_NAMESPACE))) { if (this.bundleId == requiredWire.getProviderWiring().getBundle().getBundleId()) { LOG.debug("Camel extender requirement of bundle {} correctly wired to this implementation", bundle.getBundleId()); return true; } else { LOG.info("Not processing bundle {} as it requires a camel extender but is not wired to the this implementation", bundle.getBundleId()); return false; } } } return true; }
private void prepareDependencies(final Bundle bundle) { final BundleWiring wiring = bundle.adapt(BundleWiring.class); final List<BundleWire> wires = wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE); if (wires != null) { for (final BundleWire wire : wires) { try { final Bundle dependency = wire.getProviderWiring().getBundle(); if (visited.add(dependency.getSymbolicName()) && hasComponents(dependency)) { if (!live(dependency)) { dependency.start(); } if (live(dependency)) { // pseudo-event to trigger bundle activation addingBundle(dependency, null /* unused */); } } } catch (final Exception e) { log.warn("MISSING {}", wire, e); } } } }
private Collection<BundleRequirement> resolveWiredRequirements(final Bundle bundle) { BundleWiring bundleWiring = bundle.adapt(BundleWiring.class); List<BundleRequirement> result = new ArrayList<>(); List<BundleWire> extenderWires = bundleWiring.getRequiredWires(ExtenderNamespace.EXTENDER_NAMESPACE); Bundle extenderBundle = context.getBundle(); for (BundleWire bundleWire : extenderWires) { if (extenderBundle.equals(bundleWire.getProviderWiring().getBundle())) { Map<String, Object> capabilityAttributes = bundleWire.getCapability().getAttributes(); if (ECMExtenderConstants.EXTENDER_SYMBOLIC_NAME .equals(capabilityAttributes.get(ExtenderNamespace.EXTENDER_NAMESPACE))) { BundleRequirement requirement = bundleWire.getRequirement(); result.add(requirement); } } } return result; }
@Override public void weave(WovenClass wovenClass) { BundleWiring wiring = wovenClass.getBundleWiring(); if (!wovenClass.getDynamicImports().contains(SERVICES_FILE_PACKAGE) && !hasRequirement(wiring, SERVICES_FILE_PACKAGE) && !hasFile(wiring, SERVICES_FILE)) { LOGGER.debug("Adding a {} dynamic import to {}", SERVICES_FILE_PACKAGE, wiring.getBundle().getSymbolicName()); wovenClass.getDynamicImports().add(SERVICES_FILE_PACKAGE); if (!wovenClass.getDynamicImports().contains(JSR_303_IMPORT)) { wovenClass.getDynamicImports().add(JSR_303_IMPORT); } if (!wovenClass.getDynamicImports().contains(CONSTRAINTS_IMPORT)) { wovenClass.getDynamicImports().add(CONSTRAINTS_IMPORT); } } }
public static Class<?> getClass(String srcClassName, EntityType type, BundleContext bundleContext) { String className; switch (type) { case HISTORY: className = ClassName.getHistoryClassName(srcClassName); break; case TRASH: className = ClassName.getTrashClassName(srcClassName); break; default: className = null; } try { ClassLoader entitiesClassLoader = bundleContext.getBundle().adapt(BundleWiring.class).getClassLoader(); return null == className ? null : entitiesClassLoader.loadClass(className); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); trashService = new TrashServiceImpl(); ((TrashServiceImpl) trashService).setSettingsService(settingsService); ((TrashServiceImpl) trashService).setMdsSchedulerService(schedulerService); ((TrashServiceImpl) trashService).setPersistenceManagerFactory(factory); ((TrashServiceImpl) trashService).setBundleContext(bundleContext); doReturn(manager).when(factory).getPersistenceManager(); doReturn(query).when(manager).newQuery(Record.class); doReturn(bundle).when(bundleContext).getBundle(); doReturn(bundleWiring).when(bundle).adapt(BundleWiring.class); doReturn(classLoader).when(bundleWiring).getClassLoader(); }
@Test public void shouldReturnCorrectElementList() throws Exception { File file = computeTestDataRoot(getClass()); String location = file.toURI().toURL().toString(); doReturn(location).when(bundle).getLocation(); doReturn(Sample.class).when(bundle).loadClass(Sample.class.getName()); doReturn(bundleWiring).when(bundle).adapt(BundleWiring.class); Set<? extends AnnotatedElement> actual = processor.getElementsToProcess(); assertEquals(6, actual.size()); assertContainsClass(actual, Sample.class.getName()); assertContainsClass(actual, RelatedSample.class.getName()); assertContainsClass(actual, AnotherSample.class.getName()); }
/** * Create a tracker for a specific object/filter combination. * * @param context The bundle context. Must be the context of the bundle we are extending * @param type The type of the service * @param subfilter The sub-filter for the service * @param waitTime The time, in ms, to wait for a service to become available * @throws InvalidSyntaxException In case the filter is incorrect */ Tracker(BundleContext context, Class<? extends T> type, String subfilter, long waitTime) throws InvalidSyntaxException { // Get the wiring. BundleWiring wiring = Helper.getWiring(context.getBundle()); // Get the filter from the class and the subfilter Filter filter = getFilter(type, subfilter); // Create a new proxy for this type. This proxy is used if a normal object is referenced. proxy = type.cast(Proxy.newProxyInstance( DelegatingClassLoader.from(Arrays.asList(wiring.getClassLoader(), type.getClassLoader())), new Class<?>[]{type}, new Wrapper<>(this::_getService))); // Construct the container for the tracked services that is i.e. returned by the collections variant. this.services = new CopyOnWriteArrayList<>(); this.trackedClass = type; this.waitTime = waitTime; // And start tracking the services. tracker = new ServiceTracker<>(context, filter, new Customizer<>(context, this.services)); tracker.open(); }
@Override public Object addingBundle(Bundle bundle, BundleEvent event) { // Get the wiring of the bundle. BundleWiring wiring = Helper.getWiring(bundle); // See it is wired to us as extender. List<BundleWire> requirements = wiring.getRequiredWires("osgi.extender"); Context context = null; if (requirements != null && requirements.stream().anyMatch((w) -> w.getProviderWiring().getBundle().equals(me))) { // Create the stuff. WeldContainer container = new WeldContainer(bundle); Hashtable<String, Object> dict = new Hashtable<>(); dict.put(Constants.BUNDLE_SYMBOLICNAME, bundle.getSymbolicName()); String cat = bundle.getHeaders().get(Constants.BUNDLE_CATEGORY); if (cat != null) { dict.put(Constants.BUNDLE_CATEGORY, cat); } ServiceRegistration<BeanManager> reg = bundle.getBundleContext().registerService(BeanManager.class, container.getManager(), dict); context = new Context(container, reg); } return context; }
private Bundle createMockWebPackageBundle( List<BundleCapability> capabilities, String bundleName, String bundleVersion, int bundleState ) { final Bundle mockBundle = this.createMockBundle( bundleName, bundleVersion, bundleState ); BundleWiring wiring = mock( BundleWiring.class ); List<BundleCapability> bundleCapabilities = new ArrayList<>(); capabilities.forEach( bundleCapability -> { bundleCapabilities.add( bundleCapability ); String root = bundleCapability.getAttributes().get( "root" ).toString(); while ( root.endsWith( "/" ) ) { root = root.substring( 0, root.length() - 1 ); } when( mockBundle.getResource( root + "/package.json" ) ).thenReturn( this.getClass().getClassLoader().getResource( "org/pentaho/js/require/" + root + "-package.json" ) ); } ); when( wiring.getCapabilities( RequireJsConfigManager.CAPABILITY_NAMESPACE ) ).thenReturn( bundleCapabilities ); when( mockBundle.adapt( BundleWiring.class ) ).thenReturn( wiring ); return mockBundle; }
/** * Retrieves the set of bundles from which given bundle depends. * * @param bundle * target bundle * @return set of ancestor bundles */ public static Set<Bundle> getAncestorBundles(Bundle bundle) { BundleWiring wiring = bundle.adapt(BundleWiring.class); // the set of bundles from which the bundle imports packages Set<Bundle> exporters = new HashSet<Bundle>(); if (wiring != null) { List<BundleWire> bundleWires = wiring.getRequiredWires(null); if (bundleWires != null) { for (BundleWire pkg : bundleWires) { Bundle providerBundle = pkg.getProviderWiring().getBundle(); exporters.add(providerBundle); } } } return exporters; }
private void calculateImporters() { importers.clear(); synchronized (importers) { // calculate importers Bundle bundle = m_bundleCapability.getRevision().getBundle(); if (bundle != null) { BundleWiring wiring = bundle.adapt(BundleWiring.class); if (wiring != null) { List<BundleWire> wires = wiring.getProvidedWires(PACKAGE_NAMESPACE); if (wires != null) { for (BundleWire wire : wires) { if (wire.getCapability().equals(m_bundleCapability)) { Bundle requirerBundle = wire.getRequirerWiring().getBundle(); importers.add(requirerBundle); } } } } } } }
@SuppressWarnings("unchecked") private List<QProgram> loadPrograms(Bundle bundle, String basePackage) { List<QProgram> programs = new ArrayList<>(); BundleWiring bundleWiring = bundle.adapt(BundleWiring.class); for(String resource: bundleWiring.listResources(basePackage.replace('.', '/'), null, BundleWiring.LISTRESOURCES_LOCAL)) { Class<?> klass = null; try { String resourceURI = resource.replace(".class", "").replace('/', '.'); if(resourceURI.contains("$")) continue; klass = bundle.loadClass(resourceURI); } catch (ClassNotFoundException e) { continue; } if(QCallableProgram.class.isAssignableFrom(klass) || klass.getAnnotation(Program.class) != null) programs.add(buildProgram(bundle, (Class<QCallableProgram>)klass)); } return programs; }
@SuppressWarnings("unchecked") private List<QModule> loadModules(Bundle bundle, String basePackage) { List<QModule> modules = new ArrayList<>(); BundleWiring bundleWiring = bundle.adapt(BundleWiring.class); for(String resource: bundleWiring.listResources(basePackage.replace('.', '/'), null, BundleWiring.LISTRESOURCES_LOCAL)) { Class<?> klass = null; try { klass = bundle.loadClass(resource.replace(".class", "").replace('/', '.')); } catch (ClassNotFoundException e) { e.printStackTrace(); continue; } if(QCallableProgram.class.isAssignableFrom(klass) || klass.getAnnotation(Module.class) != null) modules.add(buildModule(bundle, (Class<QCallableProgram>)klass)); } return modules; }
/** * A constructor that initializes the object and creates the necessary {@link ServiceTracker}. The {@link #open()} * function has to be called before using the {@link #proxyInstance}. * * @param context * The context of the bundle that needs the reference. * @param interfaces * The interfaces that the {@link #proxyInstance} should be able to be casted. * @param filter * The filter expression that the available services will be checked against. * @param timeout * The timeout until the functions calls on {@link #proxyInstance} will wait if no service is available. */ public Reference(final BundleContext context, final Class<?>[] interfaces, final Filter filter, final long timeout) { if (filter == null) { throw new IllegalArgumentException("The filter parameter cannot be null"); } if ((interfaces == null) || (interfaces.length == 0)) { throw new IllegalArgumentException("The number of required interfaces must be at least one."); } this.filter = filter; serviceTrackerCustomizer = new ReferenceTrackerCustomizer(context, interfaces); serviceTracker = new ServiceTracker<Object, Object>(context, filter, serviceTrackerCustomizer); referenceInvocationHandler = new ReferenceInvocationHandler(this, serviceTracker, filter.toString(), timeout); Bundle blueprintBundle = context.getBundle(); ClassLoader classLoader = blueprintBundle.adapt(BundleWiring.class).getClassLoader(); // TODO check if classloader is null and handle it. It could be null in case of special security circumstances. proxyInstance = Proxy.newProxyInstance(classLoader, interfaces, referenceInvocationHandler); }
private void loadProvider(final BundleContext bundleContext, final BundleWiring bundleWiring) { final String filter = "(APIVersion>=2.60)"; try { final Collection<ServiceReference<Provider>> serviceReferences = bundleContext.getServiceReferences(Provider.class, filter); Provider maxProvider = null; for (final ServiceReference<Provider> serviceReference : serviceReferences) { final Provider provider = bundleContext.getService(serviceReference); if (maxProvider == null || provider.getPriority() > maxProvider.getPriority()) { maxProvider = provider; } } if (maxProvider != null) { ProviderUtil.addProvider(maxProvider); } } catch (final InvalidSyntaxException ex) { LOGGER.error("Invalid service filter: " + filter, ex); } final List<URL> urls = bundleWiring.findEntries("META-INF", "log4j-provider.properties", 0); for (final URL url : urls) { ProviderUtil.loadProvider(url, bundleWiring.getClassLoader()); } }
@Override public void start(final BundleContext bundleContext) throws Exception { ProviderUtil.STARTUP_LOCK.lock(); lockingProviderUtil = true; final BundleWiring self = bundleContext.getBundle().adapt(BundleWiring.class); final List<BundleWire> required = self.getRequiredWires(LoggerContextFactory.class.getName()); for (final BundleWire wire : required) { loadProvider(bundleContext, wire.getProviderWiring()); } bundleContext.addBundleListener(this); final Bundle[] bundles = bundleContext.getBundles(); for (final Bundle bundle : bundles) { loadProvider(bundle); } unlockIfReady(); }
public OSGiRuntime(BundleContext context, PropertiesProvider propertiesProvider) { super(propertiesProvider); IllegalArgumentAssertion.assertNotNull(context, "context"); this.context = context; // Install system module Bundle sysbundle = context.getBundle(0); try { Resource resource = new DefaultResourceBuilder().addIdentityCapability(getSystemIdentity()).getResource(); BundleWiring wiring = sysbundle.adapt(BundleWiring.class); installModule(wiring.getClassLoader(), resource, sysbundle.getHeaders(), null); } catch (ModuleException ex) { throw new IllegalStateException("Cannot install system module", ex); } // Create the {@link URLStreamHandlerTracker} streamHandlerTracker = createURLStreamHandlerTracker(getModuleContext()); // Create the bundle resolve/uninstall listener installListener = createBundleInstallListener(); }
@Deployment public static Archive<?> deployment() { final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "simple-bundle-test"); archive.setManifest(new Asset() { @Override public InputStream openStream() { OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance(); builder.addBundleManifestVersion(2); builder.addBundleSymbolicName(archive.getName()); builder.addBundleVersion("1.0.0"); builder.addImportPackages(OSGiRuntimeLocator.class, Runtime.class, Resource.class); builder.addImportPackages(BundleWiring.class); return builder.openStream(); } }); return archive; }
private void updateContext(Bundle currentContext, String className) { Bundle contextToSet = (currentContext == null) ? bundle : currentContext; int idx = className.lastIndexOf('.'); String packageName = (idx == -1) ? "" : className.substring(0, idx); BundleWiring wiring = contextToSet.adapt(BundleWiring.class); for (BundleWire wire : wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE)) { if (wire.getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE).equals(packageName)) { contextToSet = wire.getProviderWiring().getBundle(); break; } } currentLoadingBundle.get().push(contextToSet); }
public PersistenceUnit(Bundle bundle, String persistenceUnitName, PersistenceUnitTransactionType transactionType) { this.bundle = bundle; this.persistenceUnitName = persistenceUnitName; this.transactionType = transactionType; this.props = new Properties(); this.classLoader = bundle.adapt(BundleWiring.class).getClassLoader(); this.classNames = new HashSet<String>(); this.mappingFileNames = new HashSet<String>(); }
public PersistenceBundleTracker(BundleWiring bundleWiring) { wiring = bundleWiring; trackers = new HashMap<Bundle, Collection<PersistenceProviderTracker>>(); this.typeMap = new HashMap<Integer, String>(); this.typeMap.put(BundleEvent.INSTALLED, "INSTALLED"); this.typeMap.put(BundleEvent.LAZY_ACTIVATION, "LAZY_ACTIVATION"); this.typeMap.put(BundleEvent.RESOLVED, "RESOLVED"); this.typeMap.put(BundleEvent.STARTED, "STARTED"); this.typeMap.put(BundleEvent.STARTING, "Starting"); this.typeMap.put(BundleEvent.STOPPED, "STOPPED"); this.typeMap.put(BundleEvent.UNINSTALLED, "UNINSTALLED"); this.typeMap.put(256, "UNRESOLVED"); this.typeMap.put(BundleEvent.UPDATED, "UPDATED"); }
/** * Sufficient Criteria for having/failing class space compatibility - * <ol> * <li>Sharing a contract for <code>JavaJPA</code></li> * <li>Sharing a provider of <code>javax.persistence</code></li> * <li>Sharing a provider of <code>org.osgi.service.jpa</code></li> * </ol> * * @param bundle * @return */ private boolean incompatibleClassSpace(Bundle bundle) { BundleWiring pbWiring = bundle.adapt(BundleWiring.class); BundleCapability pbContract = getUsedCapability(pbWiring, OSGI_CONTRACT_NS, JAVA_JPA_CONTRACT); if(pbContract != null) { LOGGER.debug("Matching JPA contract for possible persistence bundle {}", bundle.getSymbolicName()); BundleCapability implContract = getUsedCapability(pbWiring, OSGI_CONTRACT_NS, JAVA_JPA_CONTRACT); return !pbContract.equals(implContract); } // No contract required by the persistence bundle, try javax.persistence BundleCapability pbJavaxPersistence = getUsedCapability(pbWiring, OSGI_PACKAGE_NS, JAVAX_PERSISTENCE_PKG); if(pbJavaxPersistence != null) { LOGGER.debug("Matching JPA API package for possible persistence bundle {}", bundle.getSymbolicName()); BundleCapability implJavaxPersistence = getUsedCapability(pbWiring, OSGI_PACKAGE_NS, JAVAX_PERSISTENCE_PKG); return !pbJavaxPersistence.equals(implJavaxPersistence); } // No jpa package required by the persistence bundle, try org.osgi.service.jpa BundleCapability pbJpaService = getUsedCapability(pbWiring, OSGI_PACKAGE_NS, JPA_SERVICE_PKG); if(pbJpaService != null) { LOGGER.debug("Matching JPA service package for possible persistence bundle {}", bundle.getSymbolicName()); BundleCapability implJpaService = getUsedCapability(pbWiring, OSGI_PACKAGE_NS, JPA_SERVICE_PKG); return !pbJpaService.equals(implJpaService); } // If there is nothing to clash on then we must assume that it's safe return false; }
@Override public void start(BundleContext context) throws Exception { registerWeavingHook(context, TransformerRegistrySingleton.get()); PersistenceBundleTracker customizer = new PersistenceBundleTracker(context.getBundle().adapt(BundleWiring.class)); persistenceBundleManager = new BundleTracker<Bundle>(context, Bundle.STARTING | Bundle.ACTIVE, customizer); persistenceBundleManager.open(); }
@Override public Map<Resource, Wiring> getWirings() { Map<Resource, Wiring> wiringMap = new HashMap<>(); Bundle[] bundles = this.bundleContext.getBundles(); for (Bundle bundle : bundles) { // BundleRevision extends Resource BundleRevision revision = bundle.adapt(BundleRevision.class); // BundleWiring extends Wiring BundleWiring wiring = revision.getWiring(); if (wiring != null) { wiringMap.put(revision, wiring); } } return wiringMap; }