Beispiel #1
0
  /*
   * See whether any registered extension provides the class requested. If not
   * throw an IOException.
   */
  public URLConnection openConnection(URL url) throws IOException {
    String path = url.getPath();

    if (path.trim().equals("/")) {
      return new URLHandlersBundleURLConnection(url);
    }

    Bundle[] extensions = m_extensionsCache;
    URL result = null;
    for (Bundle extBundle : extensions) {
      try {
        BundleRevisionImpl bri = (BundleRevisionImpl) extBundle.adapt(BundleRevision.class);
        if (bri != null) {
          result = bri.getResourceLocal(path);
        }
      } catch (Exception ex) {
        // Maybe the bundle went away, so ignore this exception.
      }
      if (result != null) {
        return result.openConnection();
      }
    }

    return new URLConnection(url) {
      public void connect() throws IOException {
        throw new IOException("Resource not provided by any extension!");
      }
    };
  }
 /**
  * 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();
 }
 public static boolean isBundleFragment(Bundle bundle) {
   boolean result = false;
   final BundleRevision revision = bundle.adapt(BundleRevision.class);
   if (revision != null) {
     result = (revision.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0;
   }
   return result;
 }
  protected void verifyBundleWiring() {
    Bundle bundle = Mockito.verify(_bundle);

    bundle.adapt(BundleWiring.class);

    BundleWiring bundleWiring = Mockito.verify(_bundleWiring);

    bundleWiring.getClassLoader();
  }
Beispiel #6
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;
 }
  @Test
  public void testUpdateHostToFragment() throws Exception {
    Bundle bundleA = installBundle(getHostA());
    try {
      bundleA.start();
      assertBundleState(Bundle.ACTIVE, bundleA.getState());
      BundleRevisions brevs = bundleA.adapt(BundleRevisions.class);
      assertEquals(1, brevs.getRevisions().size());
      BundleRevision brev = brevs.getRevisions().get(0);
      assertEquals(0, brev.getTypes());

      bundleA.update(toInputStream(getFragmentA()));
      brevs = bundleA.adapt(BundleRevisions.class);
      Assert.assertNotSame(brev, brevs.getRevisions().get(0));
      brev = brevs.getRevisions().get(0);
      assertEquals(BundleRevision.TYPE_FRAGMENT, brev.getTypes());
    } finally {
      bundleA.uninstall();
    }
  }
Beispiel #8
0
  private CharSequence print(Bundle bundle) {
    // [ ID ] [STATE      ] [ SL ] symname
    int level = bundle.adapt(BundleStartLevel.class).getStartLevel();

    return String.format(
        "%5d|%-11s|%5d|%s (%s)",
        bundle.getBundleId(),
        getState(bundle),
        level,
        bundle.getSymbolicName(),
        bundle.getVersion());
  }
Beispiel #9
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);
     }
   }
 }
  @Override
  public void setBundleStartLevel(long bundleId, int startLevel) throws PortalException {

    _checkPermission();

    Bundle bundle = getBundle(bundleId);

    if (bundle == null) {
      throw new PortalException("No bundle with ID " + bundleId);
    }

    BundleStartLevel bundleStartLevel = bundle.adapt(BundleStartLevel.class);

    bundleStartLevel.setStartLevel(startLevel);
  }
 /**
  * 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;
 }
 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;
 }
  @Override
  public ClassLoader getClassLoader(Bundle persistentUnitBundle) {
    ClassLoader cla = persistentUnitBundle.adapt(BundleWiring.class).getClassLoader();
    final ClassLoader clb = getClass().getClassLoader();

    return new ClassLoader(cla) {

      @Override
      protected Class<?> findClass(String className) throws ClassNotFoundException {

        return clb.loadClass(className);
      }

      @Override
      protected URL findResource(String resource) {
        return clb.getResource(resource);
      }

      @Override
      protected Enumeration<URL> findResources(String resource) throws IOException {
        return clb.getResources(resource);
      }
    };
  }
  protected ClassLoader getBundleClassLoader(Bundle bundle) {
    BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);

    return bundleWiring.getClassLoader();
  }
    public boolean isAssignableTo(Bundle requester, String className) {
      // Always return true if the requester is the same as the provider.
      if (requester == m_bundle) {
        return true;
      }

      // Boolean flag.
      boolean allow = true;
      // Get the package.
      String pkgName = Util.getClassPackage(className);
      // Get package wiring from service requester.
      BundleRevision requesterRevision = requester.adapt(BundleRevision.class);
      BundleWire requesterWire = Util.getWire(requesterRevision, pkgName);
      BundleCapability requesterCap = Util.getPackageCapability(requesterRevision, pkgName);
      // Get package wiring from service provider.
      BundleRevision providerRevision = m_bundle.adapt(BundleRevision.class);
      BundleWire providerWire = Util.getWire(providerRevision, pkgName);
      BundleCapability providerCap = Util.getPackageCapability(providerRevision, pkgName);

      // There are four situations that may occur here:
      //   1. Neither the requester, nor provider have wires for the package.
      //   2. The requester does not have a wire for the package.
      //   3. The provider does not have a wire for the package.
      //   4. Both the requester and provider have a wire for the package.
      // For case 1, if the requester does not have access to the class at
      // all, we assume it is using reflection and do not filter. If the
      // requester does have access to the class, then we make sure it is
      // the same class as the service. For case 2, we do not filter if the
      // requester is the exporter of the package to which the provider of
      // the service is wired. Otherwise, as in case 1, if the requester
      // does not have access to the class at all, we do not filter, but if
      // it does have access we check if it is the same class accessible to
      // the providing revision. For case 3, the provider will not have a wire
      // if it is exporting the package, so we determine if the requester
      // is wired to it or somehow using the same class. For case 4, we
      // simply compare the exporting revisions from the package wiring to
      // determine if we need to filter the service reference.

      // Case 1: Both requester and provider have no wire.
      if ((requesterWire == null) && (providerWire == null)) {
        // If requester has no access then true, otherwise service
        // registration must have same class as requester.
        try {
          Class requestClass =
              ((BundleWiringImpl) requesterRevision.getWiring()).getClassByDelegation(className);
          allow = getRegistration().isClassAccessible(requestClass);
        } catch (Exception ex) {
          // Requester has no access to the class, so allow it, since
          // we assume the requester is using reflection.
          allow = true;
        }
      }
      // Case 2: Requester has no wire, but provider does.
      else if ((requesterWire == null) && (providerWire != null)) {
        // If the requester exports the package, then the provider must
        // be wired to it.
        if (requesterCap != null) {
          allow = providerWire.getProviderWiring().getRevision().equals(requesterRevision);
        }
        // Otherwise, check if the requester has access to the class and,
        // if so, if it is the same class as the provider.
        else {
          try {
            // Try to load class from requester.
            Class requestClass =
                ((BundleWiringImpl) requesterRevision.getWiring()).getClassByDelegation(className);
            try {
              // If requester has access to the class, verify it is the
              // same class as the provider.
              allow =
                  (((BundleWiringImpl) providerRevision.getWiring()).getClassByDelegation(className)
                      == requestClass);
            } catch (Exception ex) {
              allow = false;
            }
          } catch (Exception ex) {
            // Requester has no access to the class, so allow it, since
            // we assume the requester is using reflection.
            allow = true;
          }
        }
      }
      // Case 3: Requester has a wire, but provider does not.
      else if ((requesterWire != null) && (providerWire == null)) {
        // If the provider exports the package, then the requester must
        // be wired to it.
        if (providerCap != null) {
          allow = requesterWire.getProviderWiring().getRevision().equals(providerRevision);
        }
        // If the provider is not the exporter of the requester's package,
        // then try to use the service registration to see if the requester's
        // class is accessible.
        else {
          try {
            // Load the class from the requesting bundle.
            Class requestClass =
                ((BundleWiringImpl) requesterRevision.getWiring()).getClassByDelegation(className);
            // Get the service registration and ask it to check
            // if the service object is assignable to the requesting
            // bundle's class.
            allow = getRegistration().isClassAccessible(requestClass);
          } catch (Exception ex) {
            // Filter to be safe.
            allow = false;
          }
        }
      }
      // Case 4: Both requester and provider have a wire.
      else {
        // Include service reference if the wires have the
        // same source revision.
        allow =
            providerWire
                .getProviderWiring()
                .getRevision()
                .equals(requesterWire.getProviderWiring().getRevision());
      }

      return allow;
    }
  private void _installInitialBundle(
      String location,
      List<Bundle> lazyActivationBundles,
      List<Bundle> startBundles,
      List<Bundle> refreshBundles) {

    boolean start = false;
    int startLevel = PropsValues.MODULE_FRAMEWORK_BEGINNING_START_LEVEL;

    int index = location.lastIndexOf(StringPool.AT);

    if (index != -1) {
      String[] parts = StringUtil.split(location.substring(index + 1), StringPool.COLON);

      for (String part : parts) {
        if (part.equals("start")) {
          start = true;
        } else {
          startLevel = GetterUtil.getInteger(part);
        }
      }

      location = location.substring(0, index);
    }

    InputStream inputStream = null;

    try {
      if (!location.startsWith("file:")) {
        location = "file:".concat(PropsValues.LIFERAY_LIB_PORTAL_DIR.concat(location));
      }

      URL initialBundleURL = new URL(location);

      try {
        inputStream = new BufferedInputStream(initialBundleURL.openStream());
      } catch (IOException ioe) {
        if (_log.isWarnEnabled()) {
          _log.warn(ioe.getMessage());
        }

        return;
      }

      Bundle bundle = (Bundle) addBundle(initialBundleURL.toString(), inputStream, false);

      if ((bundle == null) || _isFragmentBundle(bundle)) {
        return;
      }

      if (!start && _hasLazyActivationPolicy(bundle)) {
        lazyActivationBundles.add(bundle);

        return;
      }

      if (((bundle.getState() & Bundle.UNINSTALLED) == 0) && (startLevel > 0)) {

        BundleStartLevel bundleStartLevel = bundle.adapt(BundleStartLevel.class);

        bundleStartLevel.setStartLevel(startLevel);
      }

      if (start) {
        startBundles.add(bundle);
      }

      if ((bundle.getState() & Bundle.INSTALLED) != 0) {
        refreshBundles.add(bundle);
      }
    } catch (Exception e) {
      _log.error(e, e);
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
  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;
    }
  }