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); } } }
/** * 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]); }
/** * Get the repository index for the specified resource, where 0 indicates an * existing OSGi bundle in the framework and -1 indicates not found. This * method is used by * {@link #insertHostedCapability(List, HostedCapability)}. */ private int findResourceRepositoryIndex(Resource resource) { if (resource instanceof BundleRevision) { return 0; } int index = 1; Repository repo = this.resourceRepositoryMap.get(resource); if (repo == null) { return -1; } for (Repository match : this.repositories.values()) { if (repo == match) { return index; } index++; } // Still not found return -1; }
public static void waitBundleStarted(Bundle bundle) { if ((bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) { return; } BundleContext ctx; int state; // 自旋锁 for (;;) { state = bundle.getState(); if (state != Bundle.STARTING && state != Bundle.ACTIVE) { return; } ctx = bundle.getBundleContext(); if (ctx == null) { Thread.yield(); } else { return; } } }
private ProxyClassLoader getDynamicClassLoader(Class<?> clazz) { // Find all bundles required to instanciate the class // and bridge their classloaders in case the abstract class or interface // lives in non-imported packages... Class<?> currClazz = clazz; List<BundleRevision> bundleRevs = new ArrayList<>(); Map<BundleRevision, BundleRevPath> revisions = revisionMap; BundleRevPath bundleRevPath = null; do { BundleRevision bundleRev = FrameworkUtil.getBundle(currClazz).adapt(BundleRevision.class); if (!bundleRevs.contains(bundleRev)) { bundleRevs.add(bundleRev); bundleRevPath = revisions.computeIfAbsent(bundleRev, k -> new BundleRevPath()); revisions = bundleRevPath .computeSubMapIfAbsent(() -> Collections.synchronizedMap(new WeakIdentityHashMap<>())); } currClazz = currClazz.getSuperclass(); } while (currClazz != null && currClazz != Object.class); return bundleRevPath.computeClassLoaderIfAbsent(() -> { // the bundles set is now prioritised ... ClassLoader[] classLoaders = bundleRevs.stream().map(b -> b.getWiring().getClassLoader()) .toArray(ClassLoader[]::new); return new ProxyClassLoader(new BridgingClassLoader(classLoaders)); }); }
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 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); } } } }
public static List<PackageQuery> getRequiredPackages(Bundle bundle) throws BundleException { List<PackageQuery> rtn=new ArrayList<PackageQuery>(); BundleRevision br = bundle.adapt(BundleRevision.class); List<Requirement> requirements = br.getRequirements(null); Iterator<Requirement> it = requirements.iterator(); Requirement r; Entry<String, String> e; String value; PackageQuery pd; while(it.hasNext()){ r = it.next(); Iterator<Entry<String, String>> iit = r.getDirectives().entrySet().iterator(); inner:while(iit.hasNext()){ e = iit.next(); if(!"filter".equals(e.getKey())) continue; value=e.getValue(); pd=toPackageQuery(value); if(pd!=null)rtn.add(pd); } } return rtn; }
/** * Returns all capabilities published by the core plugin that are associated with the Hobson API. * * @return an array of Capability objects (or null if a bundle lookup failure occurred) */ protected Capability[] getAPICapabilities() { Bundle coreBundle = FrameworkUtil.getBundle(getClass()); if (coreBundle != null) { List<Capability> apiCapabilities = new ArrayList<>(); BundleRevision revision = coreBundle.adapt(BundleRevision.class); List<BundleCapability> caps = revision.getDeclaredCapabilities(null); for (BundleCapability bc : caps) { Object pkgName = bc.getAttributes().get("osgi.wiring.package"); Object version = bc.getAttributes().get("bundle-version"); if (pkgName != null && version != null && pkgName.toString().startsWith("com.whizzosoftware.hobson.api")) { apiCapabilities.add(new HobsonApiCapability(pkgName.toString(), version.toString())); } } return apiCapabilities.toArray(new Capability[apiCapabilities.size()]); } return null; }
public void addPackagesFrom(Bundle bundle) { synchronized (m_packageResourceByPackageIdMap) { BundleRevision revision = bundle.adapt(BundleRevision.class); if (revision != null) { List<BundleCapability> bundleCapabilities = revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); if (!bundleCapabilities.isEmpty()) { for (BundleCapability bc : bundleCapabilities) { PackageResource packageResource = new PackageResource(bc); String uniquePackageId = packageResource.getUniquePackageId(); PackageResource oldPackage = m_packageResourceByPackageIdMap.put(uniquePackageId, packageResource); if (oldPackage != null) { Everest.postResource(ResourceEvent.UPDATED, packageResource); } else { Everest.postResource(ResourceEvent.CREATED, packageResource); } } } } } }
/** * Return the BundleCapability of a bundle exporting the package packageName. * * @param context The BundleContext * @param packageName The package name * @return the BundleCapability of a bundle exporting the package packageName */ private static BundleCapability getExportedPackage(BundleContext context, String packageName) { List<BundleCapability> packages = new ArrayList<BundleCapability>(); for (Bundle bundle : context.getBundles()) { BundleRevision bundleRevision = bundle.adapt(BundleRevision.class); for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) { String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE); if (pName.equalsIgnoreCase(packageName)) { packages.add(packageCapability); } } } Version max = Version.emptyVersion; BundleCapability maxVersion = null; for (BundleCapability aPackage : packages) { Version version = (Version) aPackage.getAttributes().get("version"); if (max.compareTo(version) <= 0) { max = version; maxVersion = aPackage; } } return maxVersion; }
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); }
@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; }
String getLocation(Resource resource) { String location; if (resource instanceof BundleRevision) { location = ((BundleRevision) resource).getBundle().getLocation(); } else { location = this.resourceLocationMap.get(resource); } return location; }
private boolean isFragment(Bundle bundle) { BundleRevision bundleRevision = bundle.adapt(BundleRevision.class); if (bundleRevision == null) throw new NullPointerException("Null bundle revision means that bundle has probably been uninstalled: " + bundle.getSymbolicName() + ":" + bundle.getVersion()); return (bundleRevision.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0; }
public synchronized Map<BundleRevision, BundleRevPath> computeSubMapIfAbsent( Supplier<Map<BundleRevision, BundleRevPath>> subMapSupplier) { if (subMap == null) { subMap = subMapSupplier.get(); } return subMap; }
public BundleInformation ( final Bundle bundle ) { this.bundle = bundle; this.bundleRevision = bundle.adapt ( BundleRevision.class ); this.aboutHtml = bundle.getEntry ( "about.html" ); this.licenseTxt = bundle.getEntry ( "META-INF/LICENSE.txt" ); this.noticeTxt = bundle.getEntry ( "META-INF/NOTICE.txt" ); this.licenses = LicenseInformation.parse ( bundle.getHeaders ().get ( Constants.BUNDLE_LICENSE ) ); }
public static String toWiringString(Bundle bundle){ String str = ""; BundleWiring bw = bundle.adapt(BundleWiring.class); if (null != bw) { for (BundleWire wire : bw.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE)) { String packagee = (String) wire.getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE); Bundle b = wire.getProviderWiring().getBundle(); // str = str + "package: " + packagee + " bundle: " + b + "\n"; str = str + "package: " + packagee + " " + BundleDetailFragment.SCHEMA_PLUGIN + "://?id=" + b.getBundleId() + "\n"; } } return str; }
private Bundle createMockBundle(long bundleId, String version) { Bundle bundle = mock(Bundle.class); when(bundle.getBundleId()).thenReturn(bundleId); when(bundle.getVersion()).thenReturn(new Version(version)); BundleRevision mockRevision = mock(BundleRevision.class); when(bundle.adapt(BundleRevision.class)).thenReturn(mockRevision); when(mockRevision.getTypes()).thenReturn(0); return bundle; }
private void debugBundle(Bundle b) { BundleRevision br = b.adapt(BundleRevision.class); br.getCapabilities(null).forEach(System.out::println); b.adapt(BundleWiring.class).getProvidedWires(null).forEach(System.out::println); ; }
/** * Constructor for service resource * * @param serviceReference the service reference */ public ServiceResource(ServiceReference serviceReference) { super(SERVICES_PATH.addElements(Long.toString((Long) serviceReference.getProperty(Constants.SERVICE_ID)))); m_serviceReference = serviceReference; List<Relation> relations = new ArrayList<Relation>(); // Bundle from which this service is registered Bundle bundle = m_serviceReference.getBundle(); Path bundlePath = BundleResourceManager.getInstance().getPath().addElements(Long.toString(bundle.getBundleId())); relations.add(new DefaultRelation(bundlePath, Action.READ, FROM_BUNDLE_NAME)); //Package of the bundle that is exposed for this service String[] packageNames = packageNamesFromService(m_serviceReference); BundleRevision rev = bundle.adapt(BundleRevision.class); List<BundleCapability> capabilities = rev.getDeclaredCapabilities(PACKAGE_NAMESPACE); BundleCapability capability = null; //TODO go find the package for (BundleCapability cap : capabilities) { for (String packageName : packageNames) { if (cap.getAttributes().get(PACKAGE_NAMESPACE).equals(packageName)) { //System.out.println(serviceReference.getProperty(Constants.OBJECTCLASS)+" - "+packageName); capability = cap; } } } if (capability != null) { Path packagePath = PackageResourceManager.getInstance().getPath().add(Path.from(Path.SEPARATOR + uniqueCapabilityId(capability))); relations.add(new DefaultRelation(packagePath, Action.READ, FROM_PACKAGE_NAME)); } // Create relations setRelations(relations); }
@Override public List<Capability> findProviders(Requirement requirement) { List<Capability> resultCaps = new LinkedList<>(); // Find from installed bundles Bundle[] bundles = this.bundleContext.getBundles(); for (Bundle bundle : bundles) { if (bundle.getState() == Bundle.UNINSTALLED) { continue; // Skip UNINSTALLED bundles } BundleRevision revision = bundle.adapt(BundleRevision.class); List<Capability> bundleCaps = revision.getCapabilities(requirement.getNamespace()); if (bundleCaps != null) { for (Capability bundleCap : bundleCaps) { if (match(requirement, bundleCap, this.log)) { resultCaps.add(bundleCap); } } } } // Find from repositories for (Entry<URI, Repository> repoEntry : this.repositories.entrySet()) { Repository repository = repoEntry.getValue(); Map<Requirement, Collection<Capability>> providers = repository.findProviders(Collections.singleton(requirement)); if (providers != null) { Collection<Capability> repoCaps = providers.get(requirement); if (repoCaps != null) { resultCaps.addAll(repoCaps); for (Capability repoCap : repoCaps) { // Get the list of physical URIs for this resource. Resource resource = repoCap.getResource(); // Keep track of which repositories own which resources. this.resourceRepositoryMap.putIfAbsent(resource, repository); // Resolve the Resource's URI relative to the Repository Index URI and save for later. URI repoIndexUri = repoEntry.getKey(); URI resolvedUri = resolveResourceLocation(resource, repoIndexUri); if (resolvedUri != null) { // Cache the resolved URI into the resource URI map, which will be used after resolve. this.resourceLocationMap.put(resource, resolvedUri.toString()); } } } } } return resultCaps; }
private static boolean isFragment(Bundle bundle) { return (bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) > 0; }
private void updateDependenciesState(Map<MavenArtifact, ArtifactLoader> artifact2loader, Set<PluginDescription> toInstall, Set<PluginDescription> toUninstall) { Objects.requireNonNull(artifact2loader); Objects.requireNonNull(toInstall); Objects.requireNonNull(toUninstall); LOGGER.fine(format("Update state: toInstall=%s, toUninstall=%s", toInstall, toUninstall)); IllegalStateException startExCollection = null; try { synchronized (lock) { try { performActions(computeActions(toInstall, toUninstall), artifact2loader); checkDependenciesState(); } finally { FrameworkWiring frameworkWiring = bundleContext.getBundle(0).adapt(FrameworkWiring.class); CountDownLatch latch = new CountDownLatch(1); frameworkWiring.refreshBundles(null, event -> latch.countDown()); latch.await(); Set<Bundle> bundles = bundle2artifact.keySet(); frameworkWiring.resolveBundles(bundles); for (Bundle bundle : bundles) { if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING && (bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) == 0) { try { bundle.start(Bundle.START_ACTIVATION_POLICY); } catch (Throwable exStart) { LOGGER.log(Level.WARNING, format("Bundle %s couldn't start", bundle), exStart); if (startExCollection == null) startExCollection = new IllegalStateException("One or more bundles couldn't start"); startExCollection.addSuppressed(exStart); } } } } } } catch (Throwable ex) { LOGGER.log(Level.SEVERE, "Couldn't finish updating dependencies state", ex); IllegalStateException exToThrow = new IllegalStateException("Couldn't finish updating dependencies state", ex); if (startExCollection != null) exToThrow.addSuppressed(startExCollection); throw exToThrow; } if (startExCollection != null) throw startExCollection; }
@Override public ResolverHook begin(Collection<BundleRevision> bundleRevisions) { return new JacksonJaxrsResolverHook(); }
@Override public void filterResolvable(Collection<BundleRevision> bundleRevisions) {}
private static boolean isFragment(BundleWiring wiring) { return (wiring.getRevision().getTypes() & BundleRevision.TYPE_FRAGMENT) != 0; }
public BundleRevision getBundleRevision () { return this.bundleRevision; }
public boolean isFragment () { return ( this.bundleRevision.getTypes () & BundleRevision.TYPE_FRAGMENT ) > 0; }
private boolean isFragment(Bundle bundle) { return (bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0; }
public static boolean isFragment(Bundle bundle) { return (bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0; }
public static List<BundleDefinition> getRequiredBundles(Bundle bundle) throws BundleException { List<BundleDefinition> rtn=new ArrayList<BundleDefinition>(); BundleRevision br = bundle.adapt(BundleRevision.class); List<Requirement> requirements = br.getRequirements(null); Iterator<Requirement> it = requirements.iterator(); Requirement r; Entry<String, String> e; String value,name; int index,start,end,op; BundleDefinition bd; while(it.hasNext()){ r = it.next(); Iterator<Entry<String, String>> iit = r.getDirectives().entrySet().iterator(); while(iit.hasNext()){ e = iit.next(); if(!"filter".equals(e.getKey())) continue; value=e.getValue(); // name index=value.indexOf("(osgi.wiring.bundle"); if(index==-1) continue; start=value.indexOf('=',index); end=value.indexOf(')',index); if(start==-1 || end==-1 || end<start) continue; name=value.substring(start+1,end).trim(); rtn.add(bd=new BundleDefinition(name)); // version op=-1; index=value.indexOf("(bundle-version"); if(index==-1) continue; end=value.indexOf(')',index); start=value.indexOf("<=",index); if(start!=-1 && start<end) { op=VersionDefinition.LTE; start+=2; } else { start=value.indexOf(">=",index); if(start!=-1 && start<end) { op=VersionDefinition.GTE; start+=2; } else { start=value.indexOf("=",index); if(start!=-1 && start<end) { op=VersionDefinition.EQ; start++; } } } if(op==-1 || start==-1 || end==-1 || end<start) continue; bd.setVersion(op,value.substring(start,end).trim()); } } return rtn; // (&(osgi.wiring.bundle=slf4j.api)(bundle-version>=1.6.4)) }
public BundleInformation ( final Bundle bundle ) { this.bundle = bundle; this.bundleRevision = bundle.adapt ( BundleRevision.class ); }
/** * Constructor for bundle capability resource * * @param path * @param bundleCapability */ public BundleCapabilityResource(Path path, BundleWiring hostWiring, BundleCapability bundleCapability) { super(path.addElements(uniqueCapabilityId(bundleCapability))); m_capability = bundleCapability; isPackage = m_capability.getNamespace().equals(OsgiResourceUtils.PackageNamespace.PACKAGE_NAMESPACE); List<Relation> relations = new ArrayList<Relation>(); // calculate wires coming from this capability BundleRevision revision = m_capability.getRevision(); if (revision != null) { String bundleId = Long.toString(revision.getBundle().getBundleId()); //BundleWiring wiring = revision.getWiring(); BundleWiring wiring = hostWiring; if (wiring != null) { List<BundleWire> allWires = wiring.getProvidedWires(m_capability.getNamespace()); for (BundleWire wire : allWires) { if (wire.getCapability().equals(m_capability)) { // and add a relation link m_wires.add(wire); String wireId = uniqueWireId(wire); Path wirePath = BundleResourceManager.getInstance().getPath().addElements(Long.toString(hostWiring.getBundle().getBundleId()), BundleResource.WIRES_PATH, wireId ); relations.add(new DefaultRelation(wirePath, Action.READ, wireId)); } } } if (isPackage) { // add relation to package String packageId = uniqueCapabilityId(m_capability); Path packagePath = PackageResourceManager.getInstance().getPath().addElements(packageId); relations.add(new DefaultRelation(packagePath, Action.READ, PACKAGE_RELATION)); // add relation to bundle export package header Path exportPackagePath = BundleResourceManager.getInstance().getPath() .addElements(bundleId, BundleHeadersResource.HEADERS_PATH, BundleHeadersResource.EXPORT_PACKAGE, packageId); relations.add(new DefaultRelation(exportPackagePath, Action.READ, BundleHeadersResource.EXPORT_PACKAGE)); } setRelations(relations); } }