Ejemplo n.º 1
0
 @Override
 public void undeployBundle(String bundleName) throws BundleException {
   if (bundleName == null) {
     // ignore
     return;
   }
   log.info(
       String.format(
           "Before undeploy bundle with name '%s'.\n" + "%s", bundleName, getRuntimeStatus()));
   BundleContext ctx = getBundleContext();
   ServiceReference ref = ctx.getServiceReference(PackageAdmin.class.getName());
   PackageAdmin srv = (PackageAdmin) ctx.getService(ref);
   try {
     for (Bundle b : srv.getBundles(bundleName, null)) {
       if (b != null && b.getState() == Bundle.ACTIVE) {
         Transaction tx = TransactionHelper.suspendTransaction();
         try {
           b.stop();
           b.uninstall();
         } finally {
           TransactionHelper.resumeTransaction(tx);
         }
       }
     }
   } finally {
     ctx.ungetService(ref);
   }
   log.info(String.format("Undeploy done.\n" + "%s", getRuntimeStatus()));
 }
Ejemplo n.º 2
0
  /**
   * This will try and find a resource of the given name using the bundle from which was originally
   * loaded the given class so as to try and detect if it is jarred. If <code>clazz</code> hasn't
   * been loaded from a bundle class loader, we'll resort to the default class loader mechanism.
   * This will only return <code>null</code> in the case where the resource at <code>resourcePath
   * </code> cannot be located at all.
   *
   * @param clazz Class which class loader will be used to try and locate the resource.
   * @param resourcePath Path of the resource we seek, relative to the class.
   * @return The URL of the resource as we could locate it.
   * @throws IOException This will be thrown if we fail to convert bundle-scheme URIs into
   *     file-scheme URIs.
   */
  public static URL getResourceURL(Class<?> clazz, String resourcePath) throws IOException {
    BundleContext context = AcceleoCommonPlugin.getDefault().getContext();
    ServiceReference packageAdminReference =
        context.getServiceReference(PackageAdmin.class.getName());
    PackageAdmin packageAdmin = null;
    if (packageAdminReference != null) {
      packageAdmin = (PackageAdmin) context.getService(packageAdminReference);
    }

    URL resourceURL = null;
    if (packageAdmin != null) {
      Bundle bundle = packageAdmin.getBundle(clazz);
      if (bundle != null) {
        final String pathSeparator = "/"; // $NON-NLS-1$
        // We found the appropriate bundle. We'll now try and determine whether the emtl is jarred
        resourceURL = getBundleResourceURL(bundle, pathSeparator, resourcePath);
      }
    }
    /*
     * We couldn't locate either the bundle which loaded the class or the resource. Resort to the class
     * loader and return null if it cannot locate the resource either.
     */
    if (resourceURL == null) {
      resourceURL = clazz.getResource(resourcePath);
    }

    if (packageAdminReference != null) {
      context.ungetService(packageAdminReference);
    }
    return resourceURL;
  }
Ejemplo n.º 3
0
 private static Bundle getBundleForPackage(final String packageStr) {
   ExportedPackage pkg = null;
   final String pkgString;
   String versionString = null;
   final String[] tokens = StringUtils.splitString(packageStr, ";");
   pkgString = tokens[0];
   for (int j = 0; j < tokens.length; j++) {
     if (tokens[j].startsWith("version")) {
       versionString = tokens[j].substring("version=".length());
       break;
     }
   }
   if (RemoteOSGiServiceImpl.IS_R4 && versionString != null) {
     final ExportedPackage[] pkgs = pkgAdmin.getExportedPackages(pkgString);
     if (pkgs == null) {
       return null;
     }
     for (int j = 0; j < pkgs.length; j++) {
       final boolean matches = StringUtils.isVersionInRange(pkgs[j].getVersion(), versionString);
       if (matches && (pkg == null || pkgs[j].getVersion().compareTo(pkg.getVersion()) > 0)) {
         pkg = pkgs[j];
       }
     }
   } else {
     pkg = pkgAdmin.getExportedPackage(pkgString);
   }
   return pkg == null ? null : pkg.getExportingBundle();
 }
  @Test
  public void testAttachedFragmentEar() throws Exception {
    ModelControllerClient client =
        FrameworkUtils.waitForService(context, ModelControllerClient.class);
    ServerDeploymentHelper server = new ServerDeploymentHelper(client);

    // Deploy the fragment
    InputStream input = deployer.getDeployment(GOOD_FRAGMENT_EAR);
    String earName = server.deploy(GOOD_FRAGMENT_EAR, input);

    // Find the deployed fragment
    Bundle fragment = packageAdmin.getBundles(GOOD_FRAGMENT, null)[0];
    Assert.assertEquals("Bundle RESOLVED", Bundle.RESOLVED, fragment.getState());

    // Find the deployed bundle
    Bundle host = packageAdmin.getBundles(GOOD_BUNDLE, null)[0];
    Assert.assertEquals("Bundle ACTIVE", Bundle.ACTIVE, host.getState());

    Class<?> clazz =
        host.loadClass("org.jboss.as.test.integration.osgi.deployment.bundle.AttachedType");
    Assert.assertNotNull("Class not null", clazz);
    Assert.assertSame(host, ((BundleReference) clazz.getClassLoader()).getBundle());

    server.undeploy(earName);
    Assert.assertEquals("Bundle UNINSTALLED", Bundle.UNINSTALLED, fragment.getState());
    Assert.assertEquals("Bundle UNINSTALLED", Bundle.UNINSTALLED, host.getState());
  }
  @Test
  public void testUnattachedFragment() throws Exception {
    ModelControllerClient client =
        FrameworkUtils.waitForService(context, ModelControllerClient.class);
    ServerDeploymentHelper server = new ServerDeploymentHelper(client);

    // Deploy the bundle
    InputStream input = deployer.getDeployment(GOOD_BUNDLE);
    String hostName = server.deploy("bundle-host", input);

    // Find the deployed bundle
    Bundle host = packageAdmin.getBundles(GOOD_BUNDLE, null)[0];
    Assert.assertEquals("Bundle ACTIVE", Bundle.ACTIVE, host.getState());

    // Deploy the fragment
    input = deployer.getDeployment(GOOD_FRAGMENT);
    String fragmentName = server.deploy("bundle-fragment", input);

    // Find the deployed bundle
    Bundle fragment = packageAdmin.getBundles(GOOD_FRAGMENT, null)[0];
    Assert.assertEquals("Bundle INSTALLED", Bundle.INSTALLED, fragment.getState());

    try {
      host.loadClass("org.jboss.as.test.integration.osgi.deployment.bundle.AttachedType");
      Assert.fail("ClassNotFoundException expected");
    } catch (ClassNotFoundException ex) {
      // expected
    }

    server.undeploy(fragmentName);
    Assert.assertEquals("Bundle UNINSTALLED", Bundle.UNINSTALLED, fragment.getState());

    server.undeploy(hostName);
    Assert.assertEquals("Bundle UNINSTALLED", Bundle.UNINSTALLED, host.getState());
  }
  @Test
  public void testRedeployAfterUndeploy() throws Exception {
    ModelControllerClient client =
        FrameworkUtils.waitForService(context, ModelControllerClient.class);
    ServerDeploymentHelper server = new ServerDeploymentHelper(client);

    // Deploy the bundle
    InputStream input = deployer.getDeployment(GOOD_BUNDLE);
    String runtimeName = server.deploy("redeploy", input);

    // Find the deployed bundle
    Bundle bundle = packageAdmin.getBundles(GOOD_BUNDLE, null)[0];
    Assert.assertEquals("Bundle ACTIVE", Bundle.ACTIVE, bundle.getState());

    server.undeploy(runtimeName);
    Assert.assertEquals("Bundle UNINSTALLED", Bundle.UNINSTALLED, bundle.getState());

    // Redeploy the same bundle
    input = deployer.getDeployment(GOOD_BUNDLE);
    runtimeName = server.deploy("redeploy", input);

    // Find the deployed bundle
    bundle = packageAdmin.getBundles(GOOD_BUNDLE, null)[0];
    Assert.assertEquals("Bundle ACTIVE", Bundle.ACTIVE, bundle.getState());

    server.undeploy(runtimeName);
    Assert.assertEquals("Bundle UNINSTALLED", Bundle.UNINSTALLED, bundle.getState());
  }
Ejemplo n.º 7
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);
   }
 }
 /**
  * Returns the bundle id of the bundle that contains the provided object, or <code>null</code> if
  * the bundle could not be determined.
  */
 public String getBundleId(Object object) {
   if (bundleTracker == null) {
     if (JobManager.DEBUG) JobMessages.message("Bundle tracker is not set"); // $NON-NLS-1$
     return null;
   }
   PackageAdmin packageAdmin = (PackageAdmin) bundleTracker.getService();
   if (object == null) return null;
   if (packageAdmin == null) return null;
   Bundle source = packageAdmin.getBundle(object.getClass());
   if (source != null && source.getSymbolicName() != null) return source.getSymbolicName();
   return null;
 }
 protected Bundle getBundle(String symbolicName) {
   PackageAdmin packageAdmin = packageAdminTracker.getService();
   if (packageAdmin == null) return null;
   Bundle[] bundles = packageAdmin.getBundles(symbolicName, null);
   if (bundles == null) return null;
   // Return the first bundle that is not installed or uninstalled
   for (int i = 0; i < bundles.length; i++) {
     if ((bundles[i].getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) {
       return bundles[i];
     }
   }
   return null;
 }
Ejemplo n.º 10
0
 public Bundle getBundle(String bundleName) {
   PackageAdmin packageAdmin = getPackageAdmin();
   if (packageAdmin == null) return null;
   Bundle[] bundles = packageAdmin.getBundles(bundleName, null);
   if (bundles == null) return null;
   // Return the first bundle that is not installed or uninstalled
   for (int i = 0; i < bundles.length; i++) {
     if ((bundles[i].getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) {
       return bundles[i];
     }
   }
   return null;
 }
Ejemplo n.º 11
0
  static byte[] getBundle(final Bundle bundle) throws IOException {
    final byte[] buffer = new byte[BUFFER_SIZE];
    final CRC32 crc = getEntry == null ? null : new CRC32();
    final ByteArrayOutputStream out =
        getEntry == null ? new ByteArrayOutputStream(BUFFER_SIZE) : null;

    if (getEntry == null) {
      return getBundleConcierge(bundle, buffer, out);
    }

    try {
      // workaround for Eclipse
      final String prefix =
          getEntry.invoke(
                      bundle,
                      new Object[] {
                        pkgAdmin.getExportedPackages(bundle)[0].getName().replace('.', '/')
                      })
                  == null
              ? "/bin" //$NON-NLS-1$
              : ""; //$NON-NLS-1$

      return generateBundle(bundle, prefix, buffer, crc);
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(e.getMessage());
    }
  }
Ejemplo n.º 12
0
  /**
   * Stop the bundles in the supplied crates. Inter-crate dependencies are NOT expanded.
   *
   * @param context a bundle context
   * @param crates the list of crates to be stopped
   * @return the list of stopped Bundles
   * @throws CrateException wrapping any other exceptions that happen
   */
  public static List<Bundle> stopBundles(BundleContext context, Crate... crates)
      throws CrateException {
    Logger logger = Logger.getLogger(CrateStarterElf.class);

    // get the set of currently installed bundles...
    Map<String, Bundle> installed = new HashMap<String, Bundle>();
    for (Bundle bundle : context.getBundles()) {
      installed.put(bundle.getSymbolicName(), bundle);
    }

    ServiceReference reference = context.getServiceReference(PackageAdmin.class.getName());
    PackageAdmin packageAdmin = (PackageAdmin) context.getService(reference);

    List<Bundle> stoppedBundles = new ArrayList<Bundle>();

    // Shutdown in reverse order...
    List<Crate> cratesReversed = Arrays.asList(crates);
    Collections.reverse(cratesReversed);

    for (Crate crate : cratesReversed) {
      // Shutdown in reverse order...
      List<CrateBundle> bundles = crate.getBundles();
      Collections.reverse(bundles);

      for (CrateBundle cb : bundles) {
        Bundle bundle = installed.get(cb.getId());
        if (bundle != null && !bundle.getSymbolicName().startsWith("org.eclipse")) {
          try {
            Dictionary<?, ?> dict = bundle.getHeaders();
            String bundleVersion = (String) dict.get("Bundle-Version");
            if (bundleVersion != null && bundleVersion.equals(cb.getVersion())) {
              if (packageAdmin.getBundleType(bundle) != PackageAdmin.BUNDLE_TYPE_FRAGMENT) {
                logger.debug("Stopping bundle " + bundle.getSymbolicName() + " " + bundleVersion);
                bundle.stop();
              }
            }
          } catch (BundleException be) {
            logger.warn("Error stopping bundle " + cb.getId(), be);
          }
        }
      }
    }

    return stoppedBundles;
  }
Ejemplo n.º 13
0
  /**
   * Returns the bundles with the given name.
   *
   * @param bundleName The bundle name.
   * @return The bundles with the given name.
   */
  public static Bundle[] getBundles(String bundleName) {
    Bundle[] bundle = null;
    BundleContext context = AcceleoCommonPlugin.getDefault().getContext();
    ServiceReference packageAdminReference =
        context.getServiceReference(PackageAdmin.class.getName());
    PackageAdmin packageAdmin = null;
    if (packageAdminReference != null) {
      packageAdmin = (PackageAdmin) context.getService(packageAdminReference);
    }

    if (packageAdmin != null) {
      bundle = packageAdmin.getBundles(bundleName, null);
    }
    if (packageAdminReference != null) {
      context.ungetService(packageAdminReference);
    }
    return bundle;
  }
Ejemplo n.º 14
0
 private static Bundle getBundle(PackageAdmin packageAdmin, String symbolicName) {
   Bundle[] bundles = packageAdmin.getBundles(symbolicName, null);
   if (bundles == null) return null;
   for (int i = 0; i < bundles.length; i++) {
     Bundle bundle = bundles[i];
     if ((bundle.getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) return bundle;
   }
   return null;
 }
  /**
   * Refresh the persistence bundle. If persistence units have already been registered they should
   * have been unregistered before making this refresh call.
   *
   * @param b the bundle the p-units are in
   */
  public void refreshBundle(Bundle b) {
    debug("Extender.refreshBundle: ", b);

    // Add the list of currently refreshing bundles.
    // (It will be removed when the UNRESOLVED event is fired on it)
    addToRefreshingBundles(b);

    // Call refresh on all of the packages
    PackageAdmin admin = getPackageAdmin(mgr.getBundleContext());
    admin.refreshPackages(new Bundle[] {b});

    /* New 4.3 code to use to refresh bundle */
    /*
    Bundle systemBundle = mgr.getBundleContext().getBundle(0);
    FrameworkWiring fw = systemBundle.adapt(FrameworkWiring.class);
    fw.refreshBundles(Arrays.asList(b));
    */
  }
Ejemplo n.º 16
0
  @Test
  public void testAttachedFragment() throws Exception {
    Bundle hostA = installBundle(getHostA());
    assertBundleState(Bundle.INSTALLED, hostA.getState());

    Bundle fragA = installBundle(getFragmentA());
    assertBundleState(Bundle.INSTALLED, fragA.getState());

    hostA.start();
    assertBundleState(Bundle.ACTIVE, hostA.getState());
    assertBundleState(Bundle.RESOLVED, fragA.getState());

    URL entryURL = hostA.getEntry("resource.txt");
    assertNull("Entry URL null", entryURL);

    URL resourceURL = hostA.getResource("resource.txt");
    assertEquals("bundle", resourceURL.getProtocol());
    assertEquals("/resource.txt", resourceURL.getPath());

    BufferedReader br = new BufferedReader(new InputStreamReader(resourceURL.openStream()));
    assertEquals("fragA", br.readLine());

    // Load class provided by the fragment
    assertLoadClass(hostA, FragBeanA.class.getName());

    // Load a private class from host
    assertLoadClass(hostA, SubBeanA.class.getName());

    // PackageAdmin.getBundleType
    PackageAdmin pa = getPackageAdmin();
    assertEquals("Bundle type", 0, pa.getBundleType(hostA));
    assertEquals("Bundle type", PackageAdmin.BUNDLE_TYPE_FRAGMENT, pa.getBundleType(fragA));

    // PackageAdmin.getHosts
    Bundle[] hosts = pa.getHosts(hostA);
    assertNull("Not a fragment", hosts);

    hosts = pa.getHosts(fragA);
    assertNotNull("Hosts not null", hosts);
    assertEquals("Hosts length", 1, hosts.length);
    assertEquals("Hosts equals", hostA, hosts[0]);

    // PackageAdmin.getFragments
    Bundle[] fragments = pa.getFragments(fragA);
    assertNull("Not a host", fragments);

    fragments = pa.getFragments(hostA);
    assertNotNull("Fragments not null", fragments);
    assertEquals("Fragments length", 1, fragments.length);
    assertEquals("Fragments equals", fragA, fragments[0]);

    hostA.uninstall();
    assertBundleState(Bundle.UNINSTALLED, hostA.getState());
    assertBundleState(Bundle.RESOLVED, fragA.getState());

    fragA.uninstall();
    assertBundleState(Bundle.UNINSTALLED, fragA.getState());
  }
Ejemplo n.º 17
0
  /**
   * This can be used to check whether the given class is located in a dynamically installed bundle.
   *
   * @param clazz The class of which we need to determine the originating bundle.
   * @return <code>true</code> if the given class has been loaded from a dynamic bundle, <code>false
   *     </code> otherwise.
   */
  public boolean isInDynamicBundle(Class<?> clazz) {
    BundleContext context = AcceleoCommonPlugin.getDefault().getContext();
    ServiceReference packageAdminReference =
        context.getServiceReference(PackageAdmin.class.getName());
    PackageAdmin packageAdmin = null;
    if (packageAdminReference != null) {
      packageAdmin = (PackageAdmin) context.getService(packageAdminReference);
    }

    if (packageAdmin != null) {
      Bundle bundle = packageAdmin.getBundle(clazz);
      if (workspaceInstalledBundles.values().contains(bundle)) {
        return true;
      }
    }

    if (packageAdminReference != null) {
      context.ungetService(packageAdminReference);
    }

    return false;
  }
    protected String getPathsToRequiredBundles(String requireTldBundles) throws Exception {
      if (requireTldBundles == null) return null;

      ServiceReference ref =
          _bundle
              .getBundleContext()
              .getServiceReference(org.osgi.service.packageadmin.PackageAdmin.class.getName());
      PackageAdmin packageAdmin =
          (ref == null) ? null : (PackageAdmin) _bundle.getBundleContext().getService(ref);
      if (packageAdmin == null)
        throw new IllegalStateException(
            "Unable to get PackageAdmin reference to locate required Tld bundles");

      StringBuilder paths = new StringBuilder();
      String[] symbNames = requireTldBundles.split(", ");

      for (String symbName : symbNames) {
        Bundle[] bs = packageAdmin.getBundles(symbName, null);
        if (bs == null || bs.length == 0) {
          throw new IllegalArgumentException(
              "Unable to locate the bundle '"
                  + symbName
                  + "' specified by "
                  + OSGiWebappConstants.REQUIRE_TLD_BUNDLE
                  + " in manifest of "
                  + (_bundle == null ? "unknown" : _bundle.getSymbolicName()));
        }

        File f =
            BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(bs[0]);
        if (paths.length() > 0) paths.append(", ");
        paths.append(f.toURI().toURL().toString());
        LOG.debug(
            "getPathsToRequiredBundles: bundle path=" + bs[0].getLocation() + " uri=" + f.toURI());
      }

      return paths.toString();
    }
Ejemplo n.º 19
0
 /** On start, we do two things We register a listener for bundles and we start our JPA server */
 public void start(BundleContext context) throws Exception {
   Activator.context = context;
   String initializer = null;
   ServiceReference packageAdminRef =
       context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin");
   PackageAdmin packageAdmin = (PackageAdmin) context.getService(packageAdminRef);
   Bundle[] fragments = packageAdmin.getFragments(context.getBundle());
   if (fragments != null) {
     for (int i = 0; i < fragments.length; i++) {
       Bundle fragment = fragments[i];
       initializer = (String) fragment.getHeaders().get("JPA-Initializer");
       if (initializer != null) {
         AbstractSessionLog.getLog()
             .log(
                 SessionLog.CONFIG,
                 LoggingLocalization.buildMessage("osgi_initializer", new Object[] {initializer}));
         break;
       }
     }
   }
   osgiProvider = new PersistenceProvider(initializer);
   registerBundleListener();
 }
Ejemplo n.º 20
0
 private boolean isFragment(Bundle b) {
   return padmin != null && padmin.getBundleType(b) == PackageAdmin.BUNDLE_TYPE_FRAGMENT;
 }
Ejemplo n.º 21
0
  /**
   * @param systemContext
   * @throws MalformedURLException
   * @throws FileNotFoundException
   * @throws IOException
   */
  private void update() throws Exception {
    trace("Updating framework with %s", parms.runbundles);

    // Turn the bundle location paths into files
    List<File> desired = new ArrayList<File>();
    for (Object o : parms.runbundles) {
      File file = new File((String) o).getAbsoluteFile();
      if (!file.exists()) error("Bundle files does not exist: " + file);
      else desired.add(file);
    }

    // deleted = old - new
    List<File> tobedeleted = new ArrayList<File>(installedBundles.keySet());
    tobedeleted.removeAll(desired);

    // updated = old /\ new
    List<File> tobeupdated = new ArrayList<File>(installedBundles.keySet());
    tobeupdated.retainAll(desired);

    // install = new - old
    List<File> tobeinstalled = new ArrayList<File>(desired);
    tobeinstalled.removeAll(installedBundles.keySet());

    List<Bundle> tobestarted = new ArrayList<Bundle>();

    for (File f : tobedeleted)
      try {
        trace("uninstalling %s", f);
        installedBundles.get(f).uninstall();
        installedBundles.remove(f);
      } catch (Exception e) {
        error("Failed to uninstall bundle %s, exception %s", f, e);
      }

    for (File f : tobeinstalled)
      try {
        trace("installing %s", f);
        Bundle b = install(f);
        installedBundles.put(f, b);
        tobestarted.add(b);
      } catch (Exception e) {
        error("Failed to uninstall bundle %s, exception %s", f, e);
      }

    for (File f : tobeupdated)
      try {
        Bundle b = installedBundles.get(f);
        if (b.getLastModified() < f.lastModified()) {
          trace("updating %s", f);
          if (b.getState() == Bundle.ACTIVE) {
            tobestarted.add(b);
            b.stop();
          }
          b.update();
        } else trace("bundle is still current according to timestamp %s", f);
      } catch (Exception e) {
        error("Failed to update bundle %s, exception %s", f, e);
      }

    if (padmin != null) padmin.refreshPackages(null);

    trace("bundles administered %s", installedBundles.keySet());

    // From now on, the bundles are on their own. They have
    // by default AllPermission, but if they install bundles
    // they will not automatically get AllPermission anymore

    // Get the resolved status
    if (padmin != null && padmin.resolveBundles(null) == false) {
      error("could not resolve the bundles");
      // return LauncherConstants.RESOLVE_ERROR;
    }

    // Now start all the installed bundles in the same order
    // (unless they're a fragment)

    trace("Will start bundles: %s", tobestarted);
    for (Bundle b : tobestarted) {
      try {
        trace("starting %s", b.getSymbolicName());
        if (!isFragment(b)) b.start(Bundle.START_ACTIVATION_POLICY);
        trace("started  %s", b.getSymbolicName());
      } catch (BundleException e) {
        error("Failed to start bundle %s-%s, exception %s", b.getSymbolicName(), b.getVersion(), e);
      }
    }
  }
Ejemplo n.º 22
0
 public Bundle[] getHosts(Bundle bundle) {
   PackageAdmin packageAdmin = getPackageAdmin();
   if (packageAdmin == null) return null;
   return packageAdmin.getHosts(bundle);
 }
Ejemplo n.º 23
0
 public boolean isFragment(Bundle bundle) {
   PackageAdmin packageAdmin = getPackageAdmin();
   if (packageAdmin == null) return false;
   return (packageAdmin.getBundleType(bundle) & PackageAdmin.BUNDLE_TYPE_FRAGMENT) > 0;
 }
  /** @see junit.framework.TestCase#setUp() */
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    adaptorProvider = EasyMock.createNiceMock(IAdaptorProvider.class);
    context = EasyMock.createNiceMock(BundleContext.class);
    bundle = EasyMock.createMock(Bundle.class);
    otherBundle = EasyMock.createMock(Bundle.class);
    supplementerBundle1 = EasyMock.createMock(Bundle.class);
    supplementerBundle2 = EasyMock.createMock(Bundle.class);
    supplementerBundle3 = EasyMock.createMock(Bundle.class);
    supplementedBundle1 = EasyMock.createMock(Bundle.class);
    supplementedBundle2 = EasyMock.createMock(Bundle.class);
    supplementedBundle3 = EasyMock.createMock(Bundle.class);

    packageAdmin = EasyMock.createMock(PackageAdmin.class);

    EasyMock.expect(packageAdmin.getHosts(bundle)).andStubReturn(null);
    EasyMock.expect(packageAdmin.getHosts(supplementedBundle1)).andStubReturn(null);
    EasyMock.expect(packageAdmin.getHosts(supplementedBundle2)).andStubReturn(null);
    EasyMock.expect(packageAdmin.getHosts(supplementedBundle3)).andStubReturn(null);
    EasyMock.expect(packageAdmin.getHosts(supplementerBundle1)).andStubReturn(null);
    EasyMock.expect(packageAdmin.getHosts(supplementerBundle2)).andStubReturn(null);
    EasyMock.expect(packageAdmin.getHosts(supplementerBundle3)).andStubReturn(null);

    registry = new SupplementerRegistry(adaptorProvider);
    registry.setBundleContext(context);
    registry.setPackageAdmin(packageAdmin);

    EasyMock.expect(bundle.getBundleId()).andStubReturn(1l);
    EasyMock.expect(otherBundle.getBundleId()).andStubReturn(2l);
    EasyMock.expect(supplementerBundle1.getBundleId()).andStubReturn(3l);
    EasyMock.expect(supplementerBundle2.getBundleId()).andStubReturn(4l);
    EasyMock.expect(supplementerBundle3.getBundleId()).andStubReturn(5l);
    EasyMock.expect(supplementedBundle1.getBundleId()).andStubReturn(6l);
    EasyMock.expect(supplementedBundle2.getBundleId()).andStubReturn(7l);
    EasyMock.expect(supplementedBundle3.getBundleId()).andStubReturn(8l);

    EasyMock.expect(bundle.getSymbolicName()).andStubReturn("symbolic-name-bundle");
    EasyMock.expect(otherBundle.getSymbolicName()).andStubReturn("symbolic-name-otherBundle");
    EasyMock.expect(supplementerBundle1.getSymbolicName())
        .andStubReturn("symbolic-name-supplementerBundle1");
    EasyMock.expect(supplementerBundle2.getSymbolicName())
        .andStubReturn("symbolic-name-supplementerBundle2");
    EasyMock.expect(supplementerBundle3.getSymbolicName())
        .andStubReturn("symbolic-name-supplementerBundle3");
    EasyMock.expect(supplementedBundle1.getSymbolicName())
        .andStubReturn("symbolic-name-supplementedBundle1");
    EasyMock.expect(supplementedBundle2.getSymbolicName())
        .andStubReturn("symbolic-name-supplementedBundle2");
    EasyMock.expect(supplementedBundle3.getSymbolicName()).andStubReturn("different-symbolic-name");

    mocks =
        new Object[] {
          adaptorProvider,
          packageAdmin,
          context,
          bundle,
          otherBundle,
          supplementedBundle1,
          supplementedBundle2,
          supplementedBundle3,
          supplementerBundle1,
          supplementerBundle2,
          supplementerBundle3
        };
  }
  /**
   * test different supplementers and removed supplementers
   *
   * @throws Exception
   */
  public void testSupplementerRegistryWithDifferentRemovedSupplementers() throws Exception {
    Hashtable headers = new Hashtable();
    headers.put("Eclipse-SupplementImporter", "test.import1");
    EasyMock.expect(supplementerBundle1.getHeaders()).andStubReturn(headers);

    headers = new Hashtable();
    headers.put("Eclipse-SupplementExporter", "test.export1");
    EasyMock.expect(supplementerBundle2.getHeaders()).andStubReturn(headers);

    headers = new Hashtable();
    headers.put("Eclipse-SupplementBundle", "symbolic-name-supplementedBundle*");
    EasyMock.expect(supplementerBundle3.getHeaders()).andStubReturn(headers);

    EasyMock.expect(context.getBundles())
        .andStubReturn(
            new Bundle[] {supplementerBundle1, supplementerBundle2, supplementerBundle3});

    headers = new Hashtable();
    headers.put("Import-Package", "test.import1");
    headers.put("Export-Package", "test.export1");
    EasyMock.expect(supplementedBundle1.getHeaders()).andStubReturn(headers);

    headers = new Hashtable();
    EasyMock.expect(supplementedBundle2.getHeaders()).andStubReturn(headers);

    EasyMock.expect(supplementedBundle1.getState()).andStubReturn(Bundle.RESOLVED);
    EasyMock.expect(supplementedBundle2.getState()).andStubReturn(Bundle.RESOLVED);

    packageAdmin.refreshPackages(EasyMock.aryEq(new Bundle[] {supplementedBundle1}));
    packageAdmin.refreshPackages(
        EasyMock.aryEq(new Bundle[] {supplementedBundle1, supplementedBundle2}));

    IWeavingAdaptor adaptor = EasyMock.createNiceMock(IWeavingAdaptor.class);
    EasyMock.expect(adaptorProvider.getAdaptor(6l)).andStubReturn(adaptor);
    EasyMock.expect(adaptorProvider.getAdaptor(7l)).andStubReturn(adaptor);

    EasyMock.replay(mocks);

    registry.addBundle(supplementerBundle1);
    registry.addBundle(supplementerBundle2);
    registry.addBundle(supplementerBundle3);
    registry.addBundle(supplementedBundle1);
    registry.addBundle(supplementedBundle2);

    registry.removeBundle(supplementerBundle1);
    registry.removeBundle(supplementerBundle3);

    Supplementer[] supplementers = registry.getSupplementers(supplementedBundle1);
    assertEquals(1, supplementers.length);
    assertFalse(containsSupplementer(supplementers, supplementerBundle1));
    assertTrue(containsSupplementer(supplementers, supplementerBundle2));
    assertFalse(containsSupplementer(supplementers, supplementerBundle3));

    supplementers = registry.getSupplementers(supplementedBundle2);
    assertEquals(0, supplementers.length);
    assertFalse(containsSupplementer(supplementers, supplementerBundle1));
    assertFalse(containsSupplementer(supplementers, supplementerBundle2));
    assertFalse(containsSupplementer(supplementers, supplementerBundle3));

    EasyMock.verify(mocks);
  }
Ejemplo n.º 26
0
 /*
  * (non-Javadoc)
  *
  * @see org.araqne.bundle.BundleManager#refresh()
  */
 @Override
 public void refresh() {
   ServiceReference<?> ref = context.getServiceReference(PackageAdmin.class.getName());
   PackageAdmin packageAdmin = (PackageAdmin) context.getService(ref);
   packageAdmin.refreshPackages(null);
 }
Ejemplo n.º 27
0
 public Bundle getProvider(BundleContext context) {
   ServiceReference sref = context.getServiceReference(PackageAdmin.class.getName());
   PackageAdmin packageAdmin = (PackageAdmin) context.getService(sref);
   Bundle provider = packageAdmin.getBundle(getClass());
   return provider;
 }
Ejemplo n.º 28
0
  /**
   * Install all bundles contained in the specified crates from the given crate location.
   *
   * @param context The bundle context to use for interacting with OSGi.
   * @param location The location containing the crates.
   * @param crates The set of crates to activate.
   * @return an ordered list of bundles whose 'start' flag is set to true in their containing crate
   * @throws CrateException on read error.
   */
  public static List<Bundle> installBundles(
      BundleContext context, InstallLocation location, Crate... crates) throws CrateException {
    Logger logger = Logger.getLogger(CrateStarterElf.class);

    List<Crate> toLoad = expandDependencies(location, crates);

    Map<String, Bundle> installed = new HashMap<String, Bundle>();
    for (Bundle bundle : context.getBundles()) {
      installed.put(bundle.getSymbolicName(), bundle);
    }

    // prevent osgi from trying to be installed.
    installed.put("org.eclipse.osgi", null);

    ServiceReference reference = context.getServiceReference(StartLevel.class.getName());
    StartLevel start = (StartLevel) context.getService(reference);

    List<Bundle> bundles = new ArrayList<Bundle>();
    List<Bundle> toStart = new LinkedList<Bundle>();

    for (Crate crate : toLoad) {
      for (CrateBundle bundle : crate.getBundles()) {
        if (installed.containsKey(bundle.getId())) {
          if (bundle.isStart()) {
            Bundle alreadyInstalledBundle = installed.get(bundle.getId());
            if (alreadyInstalledBundle != null) {
              int state = alreadyInstalledBundle.getState();
              if (state != Bundle.ACTIVE && state != Bundle.STARTING) {
                toStart.add(alreadyInstalledBundle);
              }
            }
          }

          continue;
        }

        installed.put(bundle.getId(), null);

        // exclude fragments not applicable for the platform.
        if (!location.isApplicable(bundle)) {
          continue;
        }

        File file = getFileForBundle(location.getRoot(), bundle);

        try {
          Bundle b = context.installBundle("reference:file:" + file.toString());
          bundles.add(b);

          if (bundle.getStartLevel() > 0) {
            start.setBundleStartLevel(b, bundle.getStartLevel());
          }

          if (bundle.isStart()) {
            toStart.add(b);
          }

          logger.debug("Installed bundle: " + bundle.getId());
        } catch (BundleException e) {
          logger.warn("Error installing bundle: " + bundle.getId(), e);
        }
      }
    }
    context.ungetService(reference);

    reference = context.getServiceReference(PackageAdmin.class.getName());

    PackageAdmin packageAdmin = (PackageAdmin) context.getService(reference);
    packageAdmin.resolveBundles(bundles.toArray(new Bundle[bundles.size()]));

    context.ungetService(reference);

    return toStart;
  }
Ejemplo n.º 29
0
  /**
   * Refreshes all exported packages of the given bundles. This must be called after installing the
   * bundle.
   *
   * @param bundles Bundles which exported packages are to be refreshed.
   */
  @SuppressWarnings("restriction")
  void refreshPackages(Bundle[] bundles) {
    BundleContext context = AcceleoCommonPlugin.getDefault().getContext();
    ServiceReference packageAdminReference =
        context.getServiceReference(PackageAdmin.class.getName());
    PackageAdmin packageAdmin = null;
    if (packageAdminReference != null) {
      packageAdmin = (PackageAdmin) context.getService(packageAdminReference);
    }

    if (packageAdmin != null) {
      final boolean[] flag =
          new boolean[] {
            false,
          };
      FrameworkListener listener =
          new FrameworkListener() {
            public void frameworkEvent(FrameworkEvent event) {
              if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) {
                synchronized (flag) {
                  flag[0] = true;
                  flag.notifyAll();
                }
              }
            }
          };

      /*
       * Hack-ish : Make sure the contributions from this bundle won't be parsed. When installing a
       * bundle, the EclipseBundleListener will _always_ parse the plugin.xml and notify the extension
       * registry (and its listeners) of the new contributions. Problem is : some bundles listen to new
       * contributions, but ignore the event of contribution removals (when we uninstall the bundle). We
       * would thus end with "invalid registry object" exceptions thrown ... with no way to prevent or
       * fix them whatsoever. Equinox does not provide us with an API to disable the contributions from
       * the bundle we're installing, temporarily disable the extension listeners... or any other way to
       * workaround this registry issue. We'll then make use of the fact that the EclipseBundleListener
       * does not add contributions from a contributor which has already been added: we'll add the
       * contributor beforehand with an empty plugin.xml, disabling all potential contributions this
       * bundle would have made otherwise.
       */

      if (bundles != null && Platform.getExtensionRegistry() instanceof IDynamicExtensionRegistry) {
        IExtensionRegistry registry = Platform.getExtensionRegistry();
        for (Bundle bundle : bundles) {
          IContributor contributor = ContributorFactoryOSGi.createContributor(bundle);
          if (!((IDynamicExtensionRegistry) registry).hasContributor(contributor)) {
            registry.addContribution(
                new ByteArrayInputStream(EMPTY_PLUGIN_XML.getBytes()),
                contributor,
                false,
                null,
                null,
                ((ExtensionRegistry) registry).getTemporaryUserToken());
          }
        }
      }

      context.addFrameworkListener(listener);
      packageAdmin.refreshPackages(bundles);
      synchronized (flag) {
        while (!flag[0]) {
          try {
            flag.wait(OSGI_TIMEOUT);
          } catch (InterruptedException e) {
            // discard
            break;
          }
        }
      }
      context.removeFrameworkListener(listener);
      if (packageAdminReference != null) {
        context.ungetService(packageAdminReference);
      }
    }
  }