@Override
  public Iterator<Resource> iterateResources(String startPath, boolean recursive) {

    // Collect paths for substituted packages
    List<String> importedPaths = new ArrayList<String>();
    BundleWiring wiring = hostRev.getBundle().adapt(BundleWiring.class);
    List<BundleRequirement> preqs =
        wiring != null ? wiring.getRequirements(PackageNamespace.PACKAGE_NAMESPACE) : null;
    if (preqs != null) {
      for (BundleRequirement req : preqs) {
        XPackageRequirement preq = (XPackageRequirement) req;
        String packageName = preq.getPackageName();
        importedPaths.add(packageName.replace('.', '/'));
      }
    }
    Iterator<Resource> itres = delegate.iterateResources(startPath, recursive);
    if (importedPaths.isEmpty()) {
      return itres;
    }

    // Filter substituted packages
    List<Resource> filteredResources = new ArrayList<Resource>();
    while (itres.hasNext()) {
      Resource res = itres.next();
      String pathname = res.getName();
      int lastIndex = pathname.lastIndexOf('/');
      String respath = lastIndex > 0 ? pathname.substring(0, lastIndex) : pathname;
      if (!importedPaths.contains(respath)) {
        filteredResources.add(res);
      }
    }

    return filteredResources.iterator();
  }
Ejemplo n.º 2
0
 /**
  * Finds the {@link BundleWire} on the specified bundle for the package name
  *
  * @param bundleContext Context to use to lookup OSGi services
  * @param bundle Bundle to find the {@link BundleWire} on
  * @param packageName Name of the import package to find the wiring for
  * @return {@link BundleWire} for the specified package or <code>null</code> if none found
  */
 public static BundleWire getBundleWire(
     BundleContext bundleContext, Bundle bundle, String packageName) {
   try {
     BundleWire result = null;
     final PackageAdmin packageAdmin = getPackageAdmin(bundleContext);
     final BundleWiring wiring = bundle.adapt(BundleWiring.class);
     if (wiring != null) {
       for (BundleWire required : wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE)) {
         final org.osgi.service.packageadmin.ExportedPackage[] exportedPackages =
             packageAdmin.getExportedPackages(required.getProviderWiring().getBundle());
         for (org.osgi.service.packageadmin.ExportedPackage exportedPackage : exportedPackages) {
           if (packageName.equals(exportedPackage.getName())) {
             result = required;
             break;
           }
         }
         if (result != null) {
           break;
         }
       }
     }
     return result;
   } catch (Exception exception) {
     throw new RuntimeException(
         String.format(
             "Failed to determine bundle wiring for bundle: %s Package: %s", bundle, packageName),
         exception);
   }
 }
 @Override
 public ClassLoader getClassLoader(
     String componentName, String componentVersion, ComponentReference componentReference) {
   Bundle bundle = getBundle(componentName, componentVersion, componentReference);
   BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
   return bundleWiring.getClassLoader();
 }
  protected void verifyBundleWiring() {
    Bundle bundle = Mockito.verify(_bundle);

    bundle.adapt(BundleWiring.class);

    BundleWiring bundleWiring = Mockito.verify(_bundleWiring);

    bundleWiring.getClassLoader();
  }
Ejemplo n.º 5
0
 /**
  * We consider a bundle to be a candidate for objects if it imports at least one of the packages
  * of our interfaces
  *
  * @param bundle
  * @return true if the bundle is improting.
  */
 private boolean isImportingUs(Bundle bundle) {
   BundleWiring wiring = bundle.adapt(BundleWiring.class);
   List<BundleWire> imports = wiring.getRequiredWires(PACKAGE_NAMESPACE);
   for (BundleWire importWire : imports) {
     if (packageCapabilities.contains(importWire.getCapability())) {
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 6
0
 /** Display bundle dependencies. */
 public static void logBundleWires(final BundleContext context) {
   for (final Bundle bundle : context.getBundles()) {
     final BundleWiring wiring = bundle.adapt(BundleWiring.class);
     System.out.println("#   bundle=" + bundle);
     final List<BundleWire> provided = wiring.getProvidedWires(null);
     for (final BundleWire wire : provided) {
       System.out.println("#      provided=" + wire);
     }
     final List<BundleWire> required = wiring.getRequiredWires(null);
     for (final BundleWire wire : required) {
       System.out.println("#      required=" + wire);
     }
   }
 }
 /**
  * Retrieve the set of dependencies for a given bundle symbolic name.
  *
  * @param bundleSymbolicName the bundle symbolic name.
  * @return a set of bundle symbolic names which are dependencies. An empty set if the bundle has
  *     not been found.
  */
 protected Set<String> getBundleDependencies(String bundleSymbolicName) {
   Set<String> dependencies = Sets.newLinkedHashSet();
   Bundle currentBundle = Platform.getBundle(bundleSymbolicName);
   if (currentBundle != null) {
     BundleWiring wiring = currentBundle.adapt(BundleWiring.class);
     if (wiring != null) {
       for (BundleWire wire : wiring.getRequiredWires(BundleRevision.BUNDLE_NAMESPACE)) {
         if (wire.getProvider() != null && wire.getProvider().getBundle() != null) {
           dependencies.add(wire.getProvider().getBundle().getSymbolicName());
         }
       }
     }
   }
   return dependencies;
 }
Ejemplo n.º 8
0
  /**
   * Caches the package capabilities that are needed for a set of interface classes
   *
   * @param classes interfaces we want to track
   */
  private void cachePackageCapabilities(Class<?>... classes) {
    BundleWiring ourWiring = bundleContext.getBundle().adapt(BundleWiring.class);
    Set<String> packageNames = new HashSet<String>();
    for (Class<?> clazz : classes) {
      packageNames.add(clazz.getPackage().getName());
    }

    List<BundleCapability> ourExports = ourWiring.getCapabilities(PACKAGE_NAMESPACE);
    for (BundleCapability ourExport : ourExports) {
      String ourPkgName = (String) ourExport.getAttributes().get(PACKAGE_NAMESPACE);
      if (packageNames.contains(ourPkgName)) {
        packageCapabilities.add(ourExport);
      }
    }
  }
  @Activate
  @Modified
  protected void activate(ComponentContext componentContext) {
    _freemarkerEngineConfiguration =
        Configurable.createConfigurable(
            FreeMarkerEngineConfiguration.class, componentContext.getProperties());

    BundleContext bundleContext = componentContext.getBundleContext();

    _bundle = bundleContext.getBundle();

    BundleWiring bundleWiring = _bundle.adapt(BundleWiring.class);

    _classLoader = bundleWiring.getClassLoader();
  }
Ejemplo n.º 10
0
 private boolean checkPackage(String packageName, String version) {
   VersionRange range = VersionRange.parseVersionRange(version);
   Bundle[] bundles = bundleContext.getBundles();
   for (int i = 0; (bundles != null) && (i < bundles.length); i++) {
     BundleWiring wiring = bundles[i].adapt(BundleWiring.class);
     List<BundleCapability> caps =
         wiring != null ? wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE) : null;
     if (caps != null) {
       for (BundleCapability cap : caps) {
         String n = getAttribute(cap, BundleRevision.PACKAGE_NAMESPACE);
         String v = getAttribute(cap, Constants.VERSION_ATTRIBUTE);
         if (packageName.equals(n) && range.contains(VersionTable.getVersion(v))) {
           return true;
         }
       }
     }
   }
   return false;
 }
Ejemplo n.º 11
0
 private BundleWiringDTO getBundleWiringDTO(BundleWiring wiring) {
   if (wiring == null) {
     return null;
   }
   BundleWiringDTO dto = new BundleWiringDTO();
   dto.bundle = wiring.getBundle().getBundleId();
   dto.root = getWiringId(wiring);
   dto.nodes = new HashSet<BundleWiringDTO.NodeDTO>(wiringnodes.values());
   dto.resources = new HashSet<BundleRevisionDTO>(resources.values());
   return dto;
 }
Ejemplo n.º 12
0
 private Bundle findDependencyBundle(Bundle bundle, String dependencyName, Set<Bundle> visited) {
   BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
   if (bundleWiring == null) {
     return null;
   }
   ArrayList<BundleWire> dependencies = new ArrayList<BundleWire>();
   dependencies.addAll(bundleWiring.getRequiredWires(BundleNamespace.BUNDLE_NAMESPACE));
   dependencies.addAll(bundleWiring.getRequiredWires(PackageNamespace.PACKAGE_NAMESPACE));
   for (BundleWire wire : dependencies) {
     Bundle requiredBundle = wire.getProviderWiring().getBundle();
     if (requiredBundle != null && visited.add(requiredBundle)) {
       if (dependencyName.equals(requiredBundle.getSymbolicName())) {
         return requiredBundle;
       }
       Bundle required = findDependencyBundle(requiredBundle, dependencyName, visited);
       if (required != null) {
         return required;
       }
     }
   }
   return null;
 }
Ejemplo n.º 13
0
  @Activate
  public void activate(BundleContext context) {
    BundleWiring wiring = context.getBundle().adapt(BundleWiring.class);
    Collection<String> clazzes =
        wiring.listResources(
            "be/iminds/iot/things/api", "*.class", BundleWiring.LISTRESOURCES_RECURSE);
    for (String s : clazzes) {
      String className = s.substring(0, s.length() - 6).replaceAll("/", ".");
      try {
        Class clazz = wiring.getClassLoader().loadClass(className);
        if (Thing.class.isAssignableFrom(clazz) && Thing.class != clazz) {
          // We have a Thing
          String[] packageParts = className.split("\\.");
          String name = packageParts[packageParts.length - 2];
          types.put(name, clazz);
        }

      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
  }
  @Test
  public void testInstallModule() throws Exception {

    // Try to start the bundle and verify the expected ResolutionException
    XBundle bundleA = (XBundle) installBundle(getBundleA());
    try {
      bundleA.start();
      Assert.fail("BundleException expected");
    } catch (BundleException ex) {
      ResolutionException cause = (ResolutionException) ex.getCause();
      Collection<Requirement> reqs = cause.getUnresolvedRequirements();
      Assert.assertEquals(1, reqs.size());
      Requirement req = reqs.iterator().next();
      String namespace = req.getNamespace();
      Assert.assertEquals(PackageNamespace.PACKAGE_NAMESPACE, namespace);
    }

    Module moduleB = loadModule(getModuleB());
    XBundleRevision brevB = installResource(moduleB);
    try {
      XBundle bundleB = brevB.getBundle();
      Assert.assertEquals(bundleA.getBundleId() + 1, bundleB.getBundleId());

      bundleA.start();
      assertLoadClass(bundleA, ModuleServiceX.class.getName(), bundleB);

      // verify wiring for A
      XBundleRevision brevA = bundleA.getBundleRevision();
      Assert.assertSame(bundleA, brevA.getBundle());
      BundleWiring wiringA = brevA.getWiring();
      List<BundleWire> requiredA = wiringA.getRequiredWires(null);
      Assert.assertEquals(1, requiredA.size());
      BundleWire wireA = requiredA.get(0);
      Assert.assertSame(brevA, wireA.getRequirer());
      Assert.assertSame(bundleB, wireA.getProvider().getBundle());
      List<BundleWire> providedA = wiringA.getProvidedWires(null);
      Assert.assertEquals(0, providedA.size());

      // verify wiring for B
      Assert.assertSame(bundleB, brevB.getBundle());
      BundleWiring wiringB = brevB.getWiring();
      List<BundleWire> requiredB = wiringB.getRequiredWires(null);
      Assert.assertEquals(0, requiredB.size());
      List<BundleWire> providedB = wiringB.getProvidedWires(null);
      Assert.assertEquals(1, providedB.size());
      BundleWire wireB = providedB.get(0);
      Assert.assertSame(brevA, wireB.getRequirer());
      Assert.assertSame(bundleB, wireB.getProvider().getBundle());
    } finally {
      removeModule(moduleB);
    }
  }
Ejemplo n.º 15
0
 private BundleWiringDTO.NodeDTO getBundleWiringNodeDTO(BundleWiring wiring) {
   if (wiring == null) {
     return null;
   }
   BundleWiringDTO.NodeDTO dto = wiringnodes.get(wiring);
   if (dto != null) {
     return dto;
   }
   dto = new BundleWiringDTO.NodeDTO();
   dto.id = identifier(wiring);
   wiringnodes.put(wiring, dto);
   dto.current = wiring.isCurrent();
   dto.inUse = wiring.isInUse();
   dto.resource = getResourceId(wiring.getRevision());
   dto.capabilities = getListCapabilityRefDTO(wiring.getCapabilities(null));
   dto.requirements = getListRequirementRefDTO(wiring.getRequirements(null));
   dto.providedWires = getListBundleWireDTO(wiring.getProvidedWires(null));
   dto.requiredWires = getListBundleWireDTO(wiring.getRequiredWires(null));
   return dto;
 }
  protected ClassLoader getBundleClassLoader(Bundle bundle) {
    BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);

    return bundleWiring.getClassLoader();
  }
Ejemplo n.º 17
0
  protected com.liferay.portal.model.Portlet addingPortlet(
      ServiceReference<Portlet> serviceReference,
      Portlet portlet,
      String portletName,
      String portletId) {

    warnPorletProperties(portletName, serviceReference);

    Bundle bundle = serviceReference.getBundle();

    BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);

    ServiceRegistrations serviceRegistrations = getServiceRegistrations(bundle);

    BundlePortletApp bundlePortletApp =
        createBundlePortletApp(bundle, bundleWiring.getClassLoader(), serviceRegistrations);

    com.liferay.portal.model.Portlet portletModel = buildPortletModel(bundlePortletApp, portletId);

    portletModel.setPortletName(portletName);

    String displayName =
        GetterUtil.getString(
            serviceReference.getProperty("javax.portlet.display-name"), portletName);

    portletModel.setDisplayName(displayName);

    Class<?> portletClazz = portlet.getClass();

    portletModel.setPortletClass(portletClazz.getName());

    collectJxPortletFeatures(serviceReference, portletModel);
    collectLiferayFeatures(serviceReference, portletModel);

    PortletContextBag portletContextBag =
        new PortletContextBag(bundlePortletApp.getServletContextName());

    PortletContextBagPool.put(bundlePortletApp.getServletContextName(), portletContextBag);

    PortletBagFactory portletBagFactory = new BundlePortletBagFactory(portlet);

    portletBagFactory.setClassLoader(bundleWiring.getClassLoader());
    portletBagFactory.setServletContext(bundlePortletApp.getServletContext());
    portletBagFactory.setWARFile(true);

    try {
      portletBagFactory.create(portletModel);

      checkWebResources(
          bundle.getBundleContext(),
          bundlePortletApp.getServletContextName(),
          bundleWiring.getClassLoader(),
          serviceRegistrations);

      checkResourceBundles(
          bundle.getBundleContext(),
          bundleWiring.getClassLoader(),
          portletModel,
          serviceRegistrations);

      List<Company> companies = _companyLocalService.getCompanies();

      deployPortlet(serviceReference, portletModel, companies);

      checkResources(serviceReference, portletModel, companies);

      portletModel.setReady(true);

      if (_log.isInfoEnabled()) {
        _log.info("Added " + serviceReference);
      }

      serviceRegistrations.addServiceReference(serviceReference);

      return portletModel;
    } catch (Exception e) {
      _log.error("Portlet " + portletId + " from " + bundle + " failed to initialize", e);

      return null;
    }
  }
Ejemplo n.º 18
0
  private List<Definition> resolveAspectsForBundle(
      final List<String> fingerprintElements,
      final Bundle bundle,
      final BundleRevision bundleRevision) {
    final List<Definition> result = new ArrayList<Definition>();
    final BundleWiring wiring = bundleRevision.getWiring();

    if (wiring != null && weavingBundleContext != null) {

      Definition aspects = null;

      // fragments
      for (final BundleWire hostWire : wiring.getProvidedWires(HostNamespace.HOST_NAMESPACE)) {
        final Bundle fragmentBundle = hostWire.getRequirer().getBundle();
        if (fragmentBundle != null) {
          aspects = aspectAdmin.getAspectDefinition(fragmentBundle);
          if (aspects != null) {
            result.add(aspects);
            fingerprintElements.add(
                fragmentBundle.getSymbolicName()
                    + ":" //$NON-NLS-1$
                    + hostWire.getRequirer().getVersion().toString());
          }
        }
      }

      // required bundles
      final List<BundleWire> requiredBundles =
          wiring.getRequiredWires(BundleNamespace.BUNDLE_NAMESPACE);
      ManifestElement[] requireHeaders = null;
      if (!requiredBundles.isEmpty()) {
        try {
          requireHeaders =
              ManifestElement.parseHeader(
                  Constants.REQUIRE_BUNDLE,
                  bundle.getHeaders("").get(Constants.REQUIRE_BUNDLE)); // $NON-NLS-1$
        } catch (final BundleException e) {
        }
      }
      for (final BundleWire requiredBundleWire : requiredBundles) {
        final Bundle requiredBundle = requiredBundleWire.getProvider().getBundle();
        if (requiredBundle != null) {
          final int applyPolicy =
              getApplyAspectsPolicy(requireHeaders, requiredBundle.getSymbolicName());

          aspects = aspectAdmin.resolveRequiredBundle(requiredBundle, applyPolicy);

          if (aspects != null) {
            result.add(aspects);
            fingerprintElements.add(
                requiredBundle.getSymbolicName()
                    + ":" //$NON-NLS-1$
                    + requiredBundleWire.getProvider().getVersion().toString());
          }
        }
      }

      // imported packages
      final List<BundleWire> importedPackages =
          wiring.getRequiredWires(PackageNamespace.PACKAGE_NAMESPACE);
      ManifestElement[] importHeaders = null;
      if (!importedPackages.isEmpty()) {
        try {
          importHeaders =
              ManifestElement.parseHeader(
                  Constants.IMPORT_PACKAGE,
                  bundle.getHeaders("").get(Constants.IMPORT_PACKAGE)); // $NON-NLS-1$
        } catch (final BundleException e) {
        }
      }
      for (final BundleWire importPackageWire : importedPackages) {
        final Bundle exportingBundle = importPackageWire.getProvider().getBundle();
        if (exportingBundle != null) {
          final String importedPackage =
              (String)
                  importPackageWire
                      .getCapability()
                      .getAttributes()
                      .get(PackageNamespace.PACKAGE_NAMESPACE);

          final int applyPolicy = getApplyAspectsPolicy(importHeaders, importedPackage);

          aspects =
              aspectAdmin.resolveImportedPackage(exportingBundle, importedPackage, applyPolicy);

          if (aspects != null) {
            result.add(aspects);
            final Object v =
                importPackageWire
                    .getCapability()
                    .getAttributes()
                    .get(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE);
            final String version = v == null ? Version.emptyVersion.toString() : v.toString();
            fingerprintElements.add(
                importedPackage
                    + ":" //$NON-NLS-1$
                    + version);
          }
        }
      }

      // supplementers
      final Supplementer[] supplementers =
          this.supplementerRegistry.getSupplementers(bundleRevision.getBundle().getBundleId());

      for (int i = 0; i < supplementers.length; i++) {
        aspects =
            aspectAdmin.getExportedAspectDefinitions(supplementers[i].getSupplementerBundle());
        if (aspects != null) {
          result.add(aspects);
          fingerprintElements.add(
              supplementers[i].getSymbolicName()
                  + ":" //$NON-NLS-1$
                  + getBundleVersion(supplementers[i].getSupplementerBundle()));
        }
      }

      // this bundle
      aspects = aspectAdmin.getAspectDefinition(bundle);
      if (aspects != null) {
        final String finishedValue =
            bundle
                .getHeaders("")
                .get( //$NON-NLS-1$
                    AspectAdmin.AOP_BUNDLE_FINISHED_HEADER);
        if (finishedValue == null || !AspectAdmin.AOP_BUNDLE_FINISHED_VALUE.equals(finishedValue)) {
          result.add(aspects);
          fingerprintElements.add(
              bundle.getSymbolicName()
                  + ":" //$NON-NLS-1$
                  + bundleRevision.getVersion().toString());
        }
      }
    }

    return result;
  }