/**
   * Register the p-units of a given bundle.
   *
   * @param b the bundle the p-units are in
   */
  public void registerPersistenceUnitsInBundle(Bundle b) {

    debug("Extender.registerPersistenceUnitsInBundle: ", b);
    if (!isAssigned(b)) {
      warning("Register called on bundle " + b.getSymbolicName(), " but bundle was not assigned");
      return;
    }
    if (areCompatibleBundles(b, mgr.getBundle())) {
      debug("Extender provider compatible with bundle: ", b);

      mgr.registerPersistenceUnits(unitsByBundle.get(b));

    } else {
      warning(
          "Cannot support bundle "
              + b.getSymbolicName()
              + " because it is not JPA-compatible with the EclipseLink bundles. "
              + "This is because there are multiple bundles exporting javax.persistence "
              + "and the persistence unit bundle has resolved to a different one than "
              + "the EclipseLink bundles. "
              + "\nTo fix this, uninstall one of the bundles containing javax.persistence "
              + "so that both the persistence unit bundle and the provider bundles resolve "
              + "to the same javax.persistence package.");
      unassignPersistenceUnitsInBundle(b);
      // No point in updating or refreshing.
      // It would likely just re-resolve to the same JPA interface package.
    }
  }
  /**
   * Loads the class <code>qualifiedName</code> from the specified <code>bundle</code> if possible.
   *
   * @param bundle The bundle from which to load the sought class.
   * @param qualifiedName Qualified name of the class that is to be loaded.
   * @return An instance of the class if it could be loaded, <code>null</code> otherwise.
   */
  private Class<?> internalLoadClass(Bundle bundle, String qualifiedName) {
    try {
      WorkspaceClassInstance workspaceInstance = workspaceLoadedClasses.get(qualifiedName);
      final Class<?> clazz;
      if (workspaceInstance == null) {
        clazz = bundle.loadClass(qualifiedName);
        workspaceLoadedClasses.put(
            qualifiedName, new WorkspaceClassInstance(clazz, bundle.getSymbolicName()));
      } else if (workspaceInstance.isStale()) {
        clazz = bundle.loadClass(qualifiedName);
        workspaceInstance.setStale(false);
        workspaceInstance.setClass(clazz);
      } else {
        clazz = workspaceInstance.getClassInstance();
      }

      return clazz;
    } catch (ClassNotFoundException e) {
      e.fillInStackTrace();
      AcceleoCommonPlugin.log(
          AcceleoCommonMessages.getString(
              "BundleClassLookupFailure", //$NON-NLS-1$
              qualifiedName,
              bundle.getSymbolicName()),
          e,
          false);
    }
    return null;
  }
Beispiel #3
0
  @Override
  public boolean uninstall(OTEStatusCallback<ConfigurationStatus> statusCallback) {
    boolean result = true;
    for (Bundle bundle : installedBundles) {
      try {
        bundle.uninstall();
      } catch (BundleException ex) {
        result = false;
        statusCallback.error("Failed to uninstall " + bundle.getSymbolicName(), ex);
      }
    }
    installedBundles.clear();

    for (Bundle bundle : runningBundles) {
      try {
        String entry = bundle.getHeaders().get("Fragment-Host");
        if (entry == null) {
          bundle.stop();
        }
        bundle.uninstall();
      } catch (BundleException ex) {
        result = false;
        statusCallback.error("Failed to stop and uninstall " + bundle.getSymbolicName(), ex);
      }
    }
    runningBundles.clear();

    return result;
  }
Beispiel #4
0
  /**
   * Register namespaces defined in the bundle in the namespace table.
   *
   * @param bundle The bundle.
   */
  private void registerNamespaces(Bundle bundle) {
    final String definition = (String) bundle.getHeaders().get(NAMESPACES_BUNDLE_HEADER);
    if (definition != null) {
      log.debug(
          "registerNamespaces: Bundle {} tries to register: {}",
          bundle.getSymbolicName(),
          definition);
      final StringTokenizer st = new StringTokenizer(definition, ",");
      final List<NamespaceEntry> entries = new ArrayList<NamespaceEntry>();

      while (st.hasMoreTokens()) {
        final String token = st.nextToken().trim();
        int pos = token.indexOf('=');
        if (pos == -1) {
          log.warn(
              "registerNamespaces: Bundle {} has an invalid namespace manifest header entry: {}",
              bundle.getSymbolicName(),
              token);
        } else {
          final String prefix = token.substring(0, pos).trim();
          final String namespace = token.substring(pos + 1).trim();
          entries.add(new NamespaceEntry(prefix, namespace));
        }
      }
      if (entries.size() > 0) {
        this.namespaceTable.put(
            bundle.getBundleId(), entries.toArray(new NamespaceEntry[entries.size()]));
      }
    }
  }
Beispiel #5
0
 @Override
 public boolean start(OTEStatusCallback<ConfigurationStatus> statusCallback) {
   boolean pass = true;
   sortBundles(installedBundles);
   Iterator<Bundle> iter = installedBundles.iterator();
   while (iter.hasNext()) {
     Bundle bundle = iter.next();
     try {
       String entry = bundle.getHeaders().get("Fragment-Host");
       if (entry == null) {
         int bundleState = bundle.getState();
         if (bundleState != Bundle.ACTIVE) {
           bundle.start();
         }
       }
       // We got here because bundle.start did not exception
       runningBundles.add(bundle);
       iter.remove();
       statusCallback.log("started " + bundle.getSymbolicName());
     } catch (BundleException ex) {
       pass = false;
       statusCallback.error("Failed to start " + bundle.getSymbolicName(), ex);
     } finally {
       statusCallback.incrememtUnitsWorked(1);
     }
   }
   return pass;
 }
  @Test
  public void shouldUseCorrectClassLoaderWhenCreatingInstances() throws ClassNotFoundException {
    mockSampleFields();
    mockEntity();
    mockDataService();

    Bundle ddeBundle = mock(Bundle.class);
    Bundle entitiesBundle = mock(Bundle.class);
    when(bundleContext.getBundles()).thenReturn(new Bundle[] {ddeBundle, entitiesBundle});

    when(entity.getBundleSymbolicName()).thenReturn("org.motechproject.test");

    when(entitiesBundle.getSymbolicName())
        .thenReturn(Constants.BundleNames.MDS_ENTITIES_SYMBOLIC_NAME);
    when(ddeBundle.getSymbolicName()).thenReturn("org.motechproject.test");

    Class testClass = TestSample.class;
    when(entitiesBundle.loadClass(testClass.getName())).thenReturn(testClass);
    when(ddeBundle.loadClass(testClass.getName())).thenReturn(testClass);

    EntityRecord entityRecord =
        new EntityRecord(null, ENTITY_ID, Collections.<FieldRecord>emptyList());

    when(entity.isDDE()).thenReturn(true);
    instanceService.saveInstance(entityRecord);
    verify(ddeBundle).loadClass(TestSample.class.getName());

    when(entity.isDDE()).thenReturn(false);
    instanceService.saveInstance(entityRecord);
    verify(entitiesBundle).loadClass(TestSample.class.getName());

    verify(motechDataService, times(2)).create(any(TestSample.class));
  }
Beispiel #7
0
  @Override
  public boolean start(URI uri) {
    final String warName = extractDecodedWarNameFromString(uri.toString());
    String extractionFolderName =
        WebBundleUtils.calculateCorrectSymbolicName(
            extractDecodedWarNameFromString(uri.toString()));
    Bundle bundle = getInstalledBundle(extractionFolderName);
    if (bundle == null) {
      this.eventLogger.log(WARDeployerLogEvents.NANO_STARTING_ERROR, uri);
      logger.error(
          "Cannot start deployable with URI + ["
              + uri
              + "]. There is no bundle installed with this URI.");
      return false;
    }
    StatusFileModificator.deleteStatusFile(warName, this.pickupDir);
    final long lastModified = new File(uri).lastModified();
    this.eventLogger.log(
        WARDeployerLogEvents.NANO_WEB_STARTING, bundle.getSymbolicName(), bundle.getVersion());
    try {
      bundle.start();
    } catch (Exception e) {
      this.eventLogger.log(
          WARDeployerLogEvents.NANO_STARTING_ERROR,
          e,
          bundle.getSymbolicName(),
          bundle.getVersion());
      StatusFileModificator.createStatusFile(
          warName,
          this.pickupDir,
          StatusFileModificator.OP_DEPLOY,
          STATUS_ERROR,
          bundle.getBundleId(),
          lastModified);
      return STATUS_ERROR;
    }
    this.eventLogger.log(
        WARDeployerLogEvents.NANO_WEB_STARTED, bundle.getSymbolicName(), bundle.getVersion());

    // now update bundle's info
    if (!updateBundlesInfo(bundle, getLocationForBundlesInfo(extractionFolderName))) {
      StatusFileModificator.createStatusFile(
          warName,
          this.pickupDir,
          StatusFileModificator.OP_DEPLOY,
          STATUS_ERROR,
          bundle.getBundleId(),
          lastModified);
      return STATUS_ERROR;
    }
    StatusFileModificator.createStatusFile(
        warName,
        this.pickupDir,
        StatusFileModificator.OP_DEPLOY,
        STATUS_OK,
        bundle.getBundleId(),
        lastModified);
    return STATUS_OK;
  }
Beispiel #8
0
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
   */
  public void start(BundleContext context) throws Exception {
    super.start(context);
    plugin = this;
    // create a new RobotDeviceListener
    Bundle[] bundles = context.getBundles();
    // ("org.eclipse.equinox.event");
    Bundle r_osgi = null;
    for (int i = 0; i < bundles.length; i++) {
      Bundle bundle = bundles[i];
      System.out.println("Bundle.getSymbolicName(): " + bundle.getSymbolicName());
      if ("org.eclipse.equinox.event".equals(bundle.getSymbolicName())) {
        bundle.start();
      } else if ("org.eclipse.equinox.log".equals(bundle.getSymbolicName())) {
        bundle.start();
      } else if ("ch.ethz.iks.r_osgi.remote".equals(bundle.getSymbolicName())) {
        r_osgi = bundle;
      } else if ("org.leibnix.device.clocktimer.interfaces".equals(bundle.getSymbolicName())) {
        bundle.start();
      }
    }
    if (r_osgi != null) {
      r_osgi.start();
    }
    // ServiceReference ref = context
    // .getServiceReference(RemoteOSGiService.class.getName());
    // if (ref != null) {
    // remote = (RemoteOSGiService) context.getService(ref);
    //
    // DeviceListener listener = new DeviceListener(context, remote);
    //
    // // register for discovery
    // context.registerService(DiscoveryListener.class.getName(),
    // listener, null);
    // }

    //		ServiceReference ref = context
    //				.getServiceReference(RemoteOSGiService.class.getName());
    //		if (ref != null) {
    //			RemoteOSGiService rs = (RemoteOSGiService) context.getService(ref);
    //			ServiceURL[] serviceURLs = rs.connect(InetAddress.getLocalHost(),
    //					9278, null); // FIXME use remote host from preferences
    //
    //			for (ServiceURL service : serviceURLs) {
    //				ServiceType serviceType = service.getServiceType();
    //
    //				System.out.println(serviceType.getConcreteTypeName());
    //				if (serviceType.getConcreteTypeName().endsWith("ClockTimer")) {
    //					rs.fetchService(service);
    //					Object remoteService = rs.getFetchedService(service);
    //					// if (remoteService instanceof IClockTimer) {
    //						IClockTimer clock = (IClockTimer) remoteService;
    //						clock.addTimer("1");
    //					// }
    //					break;
    //				}
    //			}
    //		}

  }
 public void assertPluginsResolved(Bundle[] bundles) {
   for (Bundle bundle : bundles) {
     assertTrue(
         "Plugin '" + bundle.getSymbolicName() + "' is not resolved", // $NON-NLS-1$ //$NON-NLS-2$
         isPluginResolved(bundle.getSymbolicName()));
     System.out.println(bundle.getSymbolicName() + " was resolved and activated");
   }
 }
 public synchronized RuntimeContext createContext(Bundle bundle) throws Exception {
   RuntimeContext ctx = contexts.get(bundle.getSymbolicName());
   if (ctx == null) {
     // hack to handle fragment bundles
     ctx = new OSGiRuntimeContext(bundle);
     contexts.put(bundle.getSymbolicName(), ctx);
     loadComponents(bundle, ctx);
   }
   return ctx;
 }
 protected Bundle getInstalledBundle(String symbolicName) {
   for (Bundle b : bundleContext.getBundles()) {
     if (b.getSymbolicName().equals(symbolicName)) {
       return b;
     }
   }
   for (Bundle b : bundleContext.getBundles()) {
     System.err.println("Bundle: " + b.getSymbolicName());
   }
   throw new RuntimeException("Bundle " + symbolicName + " does not exist");
 }
Beispiel #12
0
  private Map<String, Bundle> getBundlesToRestart(Set<String> bundleSymbolicNames) {
    Map<String, Bundle> bundlesToRestart = new HashMap<>();

    for (Bundle bundle : bundleCtx.getBundles()) {
      if (bundleSymbolicNames.contains(bundle.getSymbolicName())) {
        bundlesToRestart.put(bundle.getSymbolicName(), bundle);
      }
    }

    return bundlesToRestart;
  }
  /**
   * Go through the p-units in a given bundle and assign the ones that do not have a provider, or
   * have a provider specified as this one.
   *
   * @param b the bundle to look for p-units in
   */
  public void tryAssigningPersistenceUnitsInBundle(Bundle b) {

    debug("Extender.tryAssigningPersistenceUnitsInBundle: ", b);
    // If we have already assigned it then bail
    if (isAssigned(b)) {
      warning("Attempted to assign a bundle that was already assigned: ", b.toString());
      return;
    }

    // Look for all of the persistence descriptor files in the bundle
    List<PersistenceDescriptorInfo> descriptorInfos = bundleUtil.persistenceDescriptorInfos(b);

    if (descriptorInfos.isEmpty()) {
      // There were no descriptors specified in the manifest - check if there is any config from
      // config admin
      PersistenceUnitConfiguration config =
          mgr.getConfigAdminListener().configForBundle(b.getSymbolicName());
      if (config != null) {
        // There is a config to go with this bundle.
        // Create a special descriptorInfo with the descriptor string right inside it
        debug("No persistence descriptors, but found a config for bundle ", b);
        descriptorInfos.add(new InlinedDescriptorInfo(config));
      } else {
        // We can't assign it just yet. Add to the limbo list
        warning("No persistence descriptors found in persistence bundle ", b.getSymbolicName());
        debug("Putting bundle ", b, " in limbo");
        inLimbo.put(b.getSymbolicName(), b);
        // The bundle will be removed from being in limbo by the config admin listener when
        // a config comes along that contains the bsn of this bundle. It will then be refreshed.
        return;
      }
    }

    // Do a partial parse of the descriptors
    Set<PUnitInfo> pUnitInfos = bundleUtil.persistenceUnitInfoFromXmlFiles(descriptorInfos);

    // Cycle through each p-unit info and see if a provider was specified
    for (PUnitInfo info : pUnitInfos) {
      if ((info.getProvider() == null)
          || (EclipseLinkProvider.ECLIPSELINK_PROVIDER_CLASS_NAME.equals(info.getProvider()))) {
        // We can be the provider; claim the p-unit and add it to our list
        info.setBundle(b);
        info.setAssignedProvider(mgr.getProvider());
        debug("Assigning punit ", info.getUnitName(), " to this provider");
        addToBundleUnits(unitsByBundle, b, info);
      }
    }
    // If we found any that were for us then move on to do the preResolve work
    List<PUnitInfo> unitsFound = unitsByBundle.get(b);
    if ((unitsFound != null) && (unitsFound.size() != 0)) {
      mgr.preResolve(b, unitsByBundle.get(b));
    }
  }
  @Test
  public void testOSGi() throws Exception {
    Assert.assertNotNull(bundleContext);

    Bundle bundle = bundleContext.getBundle();
    System.out.println("symbolic name " + bundle.getSymbolicName());
    System.out.println("vendor " + bundleContext.getProperty(Constants.FRAMEWORK_VENDOR));

    for (Bundle b : bundleContext.getBundles()) {
      System.out.println(b.getSymbolicName() + " " + b.getBundleId());
    }
  }
 /**
  * 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;
 }
 public void assertPluginsResolved(String[] ids) {
   for (String id : ids) {
     Bundle bundle = Platform.getBundle(id);
     assertNotNull(MessageFormat.format("Could not get bundle {0} instance", id), bundle);
     assertTrue(
         MessageFormat.format(
             "Plugin '{0}' is not resolved",
             bundle.getSymbolicName()), // $NON-NLS-1$ //$NON-NLS-2$
         isPluginResolved(bundle.getSymbolicName()));
     System.out.println(
         MessageFormat.format("{0} was resolved and activated", bundle.getSymbolicName()));
   }
 }
 /**
  * see {@link
  * org.eclipse.objectteams.otequinox.hook.IAspectRegistry#getAdaptingAspectPlugins(Bundle)}
  */
 public String[] getAdaptingAspectPlugins(Bundle baseBundle) {
   InitState state = checkInitialization(baseBundle.getSymbolicName());
   if (state == InitState.NOT_YET) return new String[0];
   String[] result = this.otEquinox.getAdaptingAspectPlugins(baseBundle);
   if (result.length > 0) {
     if (state == InitState.TOO_LATE)
       throw new RuntimeException(
           "Boot order problem: base bundle "
               + baseBundle.getSymbolicName()
               + " was loaded before the transformer plug-in was ready!");
   }
   return result;
 }
 @Override
 public void bundleChanged(BundleEvent event) {
   Bundle bundle = event.getBundle();
   if (event.getType() == BundleEvent.STARTED) {
     logger.info(
         String.format(
             "Starting %s [%d] bundle.", bundle.getSymbolicName(), bundle.getBundleId()));
   } else if (event.getType() == BundleEvent.STOPPED) {
     logger.info(
         String.format(
             "Stopping %s [%d] bundle.", bundle.getSymbolicName(), bundle.getBundleId()));
   }
 }
 public static Bundle getBundleByNameOrId(BundleContext bundleContext, String bundleId) {
   Bundle result = null;
   if (isLong(bundleId)) {
     result = bundleContext.getBundle(Long.valueOf(bundleId));
   } else {
     for (Bundle bundle : bundleContext.getBundles()) {
       if (bundle.getSymbolicName() != null && bundle.getSymbolicName().equals(bundleId)) {
         result = bundle;
         break;
       }
     }
   }
   return result;
 }
  /**
   * You will get a list of bundles installed by default plus your testcase, wrapped into a bundle
   * called pax-exam-probe
   */
  @Test
  public void listBundles() {
    for (Bundle b : bundleContext.getBundles()) {
      if (b.getState() != Bundle.ACTIVE && b.getState() != Bundle.RESOLVED)
        fail("Bundle should be active: " + b);

      Dictionary headers = b.getHeaders();
      String ctxtPath = (String) headers.get(WEB_CONTEXT_PATH);
      if (ctxtPath != null)
        System.out.println(
            "Bundle " + b.getBundleId() + " : " + b.getSymbolicName() + " : " + ctxtPath);
      else System.out.println("Bundle " + b.getBundleId() + " : " + b.getSymbolicName());
    }
  }
  @Override
  public Enumeration<URL> getResources(String name) throws IOException {
    log.warn(
        "BundleClassLoaderProxy.getResources:" + name + "  at Bundle:" + bundle.getSymbolicName());
    // 如果是读取class文件,则交给真正的ClassLoader去处理
    if (name.endsWith(".class")) {
      return super.getResources(name);
    }

    List<URL> list = new ArrayList<URL>();

    Enumeration<URL> urlEnum = bundleClassLoader.getResources(name);
    if (urlEnum != null) {
      while (urlEnum.hasMoreElements()) {
        list.add(urlEnum.nextElement());
      }
    }
    urlEnum = springClassLoader.getResources(name);
    if (urlEnum != null) {
      while (urlEnum.hasMoreElements()) {
        list.add(urlEnum.nextElement());
      }
    }
    return Collections.enumeration(list);
  }
 protected void loadComponents(Bundle bundle, RuntimeContext ctx) throws Exception {
   String list = getComponentsList(bundle);
   String name = bundle.getSymbolicName();
   log.debug("Bundle: " + name + " components: " + list);
   if (list == null) {
     return;
   }
   StringTokenizer tok = new StringTokenizer(list, ", \t\n\r\f");
   while (tok.hasMoreTokens()) {
     String path = tok.nextToken();
     URL url = bundle.getEntry(path);
     log.debug("Loading component for: " + name + " path: " + path + " url: " + url);
     if (url != null) {
       try {
         ctx.deploy(url);
       } catch (Exception e) {
         // just log error to know where is the cause of the
         // exception
         log.error("Error deploying resource: " + url);
         Framework.handleDevError(e);
         throw e;
       }
     } else {
       String message = "Unknown component '" + path + "' referenced by bundle '" + name + "'";
       log.error(message + ". Check the MANIFEST.MF");
       Framework.handleDevError(null);
       warnings.add(message);
     }
   }
 }
  @Test
  public void testNullSymbolicName() throws Exception {

    final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "null-symbolic-name");
    archive.setManifest(
        new Asset() {
          public InputStream openStream() {
            OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance();
            builder.addBundleName(archive.getName());
            return builder.openStream();
          }
        });

    Bundle bundle = installBundle(archive);
    try {
      assertBundleState(Bundle.INSTALLED, bundle.getState());
      assertNull("Null symbolic name", bundle.getSymbolicName());
      assertEquals("null-symbolic-name:0.0.0", bundle.toString());
      bundle.start();
      assertBundleState(Bundle.ACTIVE, bundle.getState());
    } finally {
      bundle.uninstall();
      assertBundleState(Bundle.UNINSTALLED, bundle.getState());
    }
  }
Beispiel #24
0
 public void startBundle(String bundleSymbolicName) throws BundleException {
   for (Bundle bundle : bundleCtx.getBundles()) {
     if (bundleSymbolicName.equals(bundle.getSymbolicName())) {
       bundle.start();
     }
   }
 }
  /**
   * @param appContext
   * @return
   */
  private URI determineApplicationModelURI(IApplicationContext appContext) {
    Optional<String> appModelPath = getArgValue(IWorkbench.XMI_URI_ARG, appContext, false);

    String appModelPathValue =
        appModelPath
            .filter(path -> !path.isEmpty())
            .orElseGet(
                () -> {
                  Bundle brandingBundle = appContext.getBrandingBundle();
                  if (brandingBundle != null) {
                    return brandingBundle.getSymbolicName()
                        + "/"
                        + E4Application.APPLICATION_MODEL_PATH_DEFAULT;
                  } else {
                    Logger logger = new WorkbenchLogger(PLUGIN_ID);
                    logger.error(
                        new Exception(),
                        "applicationXMI parameter not set and no branding plugin defined. "); //$NON-NLS-1$
                  }
                  return null;
                });

    URI applicationModelURI = null;

    // check if the appModelPath is already a platform-URI and if so use it
    if (URIHelper.isPlatformURI(appModelPathValue)) {
      applicationModelURI = URI.createURI(appModelPathValue, true);
    } else {
      applicationModelURI = URI.createPlatformPluginURI(appModelPathValue, true);
    }
    return applicationModelURI;
  }
  /**
   * test the supplementer registry with a supplemented bundle
   *
   * @throws Exception
   */
  public void testSupplementerRegistryWithCombinedSupplementer() throws Exception {
    Hashtable headers = new Hashtable();
    headers.put("Eclipse-SupplementImporter", "test.import1");
    headers.put("Eclipse-SupplementExporter", "test.export1");
    headers.put("Eclipse-SupplementBundle", "symbolic-name-supplementedBundle1");
    EasyMock.expect(bundle.getHeaders()).andStubReturn(headers);
    EasyMock.expect(bundle.getSymbolicName()).andStubReturn("supplementer");
    EasyMock.expect(context.getBundles()).andReturn(new Bundle[] {bundle});

    EasyMock.expect(supplementedBundle1.getHeaders()).andStubReturn(new Hashtable());

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

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

    EasyMock.replay(mocks);

    registry.addBundle(bundle);
    registry.addBundle(supplementedBundle1);
    registry.addBundle(supplementedBundle2);
    registry.addBundle(supplementedBundle3);

    Supplementer[] supplementers = registry.getSupplementers(supplementedBundle1);
    assertSame(bundle, supplementers[0].getSupplementerBundle());
    supplementers = registry.getSupplementers(supplementedBundle2);
    assertSame(bundle, supplementers[0].getSupplementerBundle());
    supplementers = registry.getSupplementers(supplementedBundle3);
    assertSame(bundle, supplementers[0].getSupplementerBundle());

    EasyMock.verify(mocks);
  }
 /*
  * Parses the specified content extension XML file into model elements.
  */
 public ContentExtension[] parse(Bundle bundle, String path)
     throws IOException, SAXException, ParserConfigurationException {
   if (reader == null) {
     reader = new DocumentReader();
   }
   URL url = FileLocator.find(bundle, new Path(path), null);
   if (url != null) {
     InputStream in = url.openStream();
     UAElement extension = reader.read(in);
     if (processor == null) {
       processor =
           new DocumentProcessor(
               new ProcessorHandler[] {
                 new ValidationHandler(getRequiredAttributes(), getDeprecatedElements())
               });
     }
     processor.process(extension, '/' + bundle.getSymbolicName() + '/' + path);
     IUAElement[] children = extension.getChildren();
     ContentExtension[] result = new ContentExtension[children.length];
     System.arraycopy(children, 0, result, 0, children.length);
     return result;
   } else {
     throw new FileNotFoundException();
   }
 }
 public static void activateBundlesFromFile(BundleContext context, String bundleStartupFileName)
     throws IOException, BundleException {
   Map<String, Version> bundleMap =
       readBundleActivationFile(context.getBundle(), bundleStartupFileName);
   Map<String, Bundle> startupBundleMap = new HashMap<String, Bundle>();
   for (Bundle b : context.getBundles()) {
     String symbolicName = b.getSymbolicName();
     if (bundleMap.containsKey(symbolicName)) {
       Version version = b.getVersion();
       Version reqVersion = bundleMap.get(symbolicName);
       if (version.getMajor() == reqVersion.getMajor()
           && version.getMinor() >= reqVersion.getMinor()) {
         if (startupBundleMap.containsKey(symbolicName)) {
           Bundle previousBundle = startupBundleMap.get(symbolicName);
           if (version.compareTo(previousBundle.getVersion()) <= 0) {
             break;
           }
         }
         startupBundleMap.put(symbolicName, b);
       }
     }
   }
   for (Bundle startupBundle : startupBundleMap.values()) {
     logger.log(Level.INFO, "Starting bundle: " + startupBundle);
     startupBundle.start();
   }
 }
Beispiel #29
0
  @SuppressWarnings("deprecation")
  public void testAllResolved() {
    assertNotNull("Expected a Bundle Context", context);
    StringBuilder sb = new StringBuilder();

    for (Bundle b : context.getBundles()) {
      if (b.getState() == Bundle.INSTALLED
          && b.getHeaders().get(aQute.bnd.osgi.Constants.FRAGMENT_HOST) == null) {
        try {
          b.start();
        } catch (BundleException e) {
          sb.append(b.getBundleId())
              .append(" ")
              .append(b.getSymbolicName())
              .append(";")
              .append(b.getVersion())
              .append("\n");
          sb.append("    ").append(e.getMessage()).append("\n\n");
          System.err.println(e.getMessage());
        }
      }
    }
    Matcher matcher = IP_P.matcher(sb);
    String out =
        matcher.replaceAll(
            "\n\n         " + aQute.bnd.osgi.Constants.IMPORT_PACKAGE + ": $1;version=[$2,$3)\n");
    assertTrue("Unresolved bundles\n" + out, sb.length() == 0);
  }
Beispiel #30
0
 protected void findBundlesWithFramentsToRefresh(Set<Bundle> toRefresh) {
   for (Bundle b : toRefresh) {
     if (b.getState() != Bundle.UNINSTALLED) {
       String hostHeader = (String) b.getHeaders().get(Constants.FRAGMENT_HOST);
       if (hostHeader != null) {
         Clause[] clauses = Parser.parseHeader(hostHeader);
         if (clauses != null && clauses.length > 0) {
           Clause path = clauses[0];
           for (Bundle hostBundle : bundleContext.getBundles()) {
             if (hostBundle.getSymbolicName().equals(path.getName())) {
               String ver = path.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE);
               if (ver != null) {
                 VersionRange v = VersionRange.parseVersionRange(ver);
                 if (v.contains(hostBundle.getVersion())) {
                   toRefresh.add(hostBundle);
                 }
               } else {
                 toRefresh.add(hostBundle);
               }
             }
           }
         }
       }
     }
   }
 }