/**
   * test the supplementer registry by adding a supplementing bundle to it
   *
   * @throws Exception
   */
  public void testSupplementerRegistryWithSupplementer() throws Exception {
    final Hashtable headers = new Hashtable();
    headers.put("Eclipse-SupplementBundle", "test.bundle1");
    EasyMock.expect(bundle.getHeaders()).andStubReturn(headers);
    EasyMock.expect(context.getBundles()).andReturn(new Bundle[] {bundle});

    EasyMock.replay(mocks);

    registry.addBundle(bundle);
    final ManifestElement[] imports =
        ManifestElement.parseHeader("Import-Package", "org.test1,\n org.test2");
    final ManifestElement[] exports =
        ManifestElement.parseHeader("Export-Package", "org.test3,\n org.test4");
    final List<Supplementer> supplementers =
        registry.getMatchingSupplementers("test.bundle1", imports, exports);
    assertNotNull(supplementers);
    assertEquals(1, supplementers.size());
    assertEquals(bundle, supplementers.get(0).getSupplementerBundle());

    EasyMock.verify(mocks);
  }
  /**
   * test an empty supplementer registry
   *
   * @throws Exception
   */
  public void testSupplementerRegistryEmpty() throws Exception {

    EasyMock.replay(mocks);

    Supplementer[] supplementers = registry.getSupplementers(0);
    assertNotNull(supplementers);
    assertEquals(0, supplementers.length);

    supplementers = registry.getSupplementers(bundle);
    assertNotNull(supplementers);
    assertEquals(0, supplementers.length);

    EasyMock.verify(mocks);

    final ManifestElement[] imports =
        ManifestElement.parseHeader("Import-Package", "org.test1,\n org.test2");
    final ManifestElement[] exports =
        ManifestElement.parseHeader("Export-Package", "org.test3,\n org.test4");
    final List<Supplementer> possibleSupplementers =
        registry.getMatchingSupplementers("symbolicName", imports, exports);
    assertNotNull(possibleSupplementers);
    assertEquals(0, possibleSupplementers.size());
  }
 private String[] parseBundleClasspath(Bundle bundle) {
   String[] result = new String[] {"."};
   String header = (String) bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH);
   ManifestElement[] classpathEntries = null;
   try {
     classpathEntries = ManifestElement.parseHeader(Constants.BUNDLE_CLASSPATH, header);
   } catch (BundleException ex) {
     log.warn("Could not parse bundle classpath of {}", bundle.toString(), ex);
   }
   if (classpathEntries != null) {
     result = new String[classpathEntries.length];
     for (int i = 0; i < classpathEntries.length; i++) {
       result[i] = classpathEntries[i].getValue();
     }
   }
   return result;
 }
 public boolean matches(Capability capability) {
   if (capability instanceof BundleCapability) return matches((BundleCapability) capability);
   // now we must do the generic thing
   if (!namespace.equals(capability.getNamespace())) return false;
   String filterSpec = getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE);
   try {
     if (filterSpec != null
         && !FrameworkUtil.createFilter(filterSpec).matches(capability.getAttributes()))
       return false;
   } catch (InvalidSyntaxException e) {
     return false;
   }
   return hasMandatoryAttributes(
       ManifestElement.getArrayFromList(
           capability
               .getDirectives()
               .get(AbstractWiringNamespace.CAPABILITY_MANDATORY_DIRECTIVE)));
 }
  private static synchronized String getSymbolicName(String path) {
    if (fCachedLocations == null) fCachedLocations = new HashMap();

    File file = new File(path);
    if (file.exists() && !fCachedLocations.containsKey(path)) {
      try {
        Dictionary dictionary = MinimalState.loadManifest(file);
        String value = (String) dictionary.get(Constants.BUNDLE_SYMBOLICNAME);
        if (value != null) {
          ManifestElement[] elements =
              ManifestElement.parseHeader(Constants.BUNDLE_SYMBOLICNAME, value);
          String id = elements.length > 0 ? elements[0].getValue() : null;
          if (id != null) fCachedLocations.put(path, elements[0].getValue());
        }
      } catch (IOException e) {
      } catch (BundleException e) {
      }
    }
    return (String) fCachedLocations.get(path);
  }
 /**
  * Parses a bunlde's manifest into a dictionary. The bundle may be in a jar or in a directory at
  * the specified location.
  *
  * @param bundleLocation root location of the bundle
  * @return bundle manifest dictionary or <code>null</code> if none
  * @throws IOException if unable to parse
  */
 protected Map loadManifest(File bundleLocation) throws IOException {
   ZipFile jarFile = null;
   InputStream manifestStream = null;
   String extension = new Path(bundleLocation.getName()).getFileExtension();
   try {
     if (extension != null && extension.equals("jar") && bundleLocation.isFile()) { // $NON-NLS-1$
       jarFile = new ZipFile(bundleLocation, ZipFile.OPEN_READ);
       ZipEntry manifestEntry = jarFile.getEntry(JarFile.MANIFEST_NAME);
       if (manifestEntry != null) {
         manifestStream = jarFile.getInputStream(manifestEntry);
       }
     } else {
       File file = new File(bundleLocation, JarFile.MANIFEST_NAME);
       if (file.exists()) manifestStream = new FileInputStream(file);
     }
     if (manifestStream == null) {
       return null;
     }
     return ManifestElement.parseBundleManifest(manifestStream, new Hashtable(10));
   } catch (BundleException e) {
     PDEPlugin.log(e);
   } finally {
     try {
       if (manifestStream != null) {
         manifestStream.close();
       }
     } catch (IOException e) {
       PDEPlugin.log(e);
     }
     try {
       if (jarFile != null) {
         jarFile.close();
       }
     } catch (IOException e) {
       PDEPlugin.log(e);
     }
   }
   return null;
 }
 private void inspectBundle(IBundle bundle) {
   for (int i = 0; i < H_TOTAL; i++) {
     if (fSearchFor == S_FOR_TYPES && (i == H_IMP || i == H_EXP)) continue;
     IManifestHeader header = bundle.getManifestHeader(SEARCH_HEADERS[i]);
     if (header != null) {
       try {
         ManifestElement[] elements =
             ManifestElement.parseHeader(header.getName(), header.getValue());
         if (elements == null) continue;
         for (int j = 0; j < elements.length; j++) {
           String value = null;
           Matcher matcher = null;
           if (fSearchFor == S_FOR_TYPES) {
             value = elements[j].getValue();
             matcher = getMatcher(value);
           }
           if (value == null || (matcher != null && !matcher.matches())) {
             value = getProperValue(elements[j].getValue());
             matcher = getMatcher(value);
           }
           if (matcher.matches()) {
             String group = matcher.group(0);
             int[] offlen;
             offlen = getOffsetOfElement(bundle, header, group);
             fSearchRequestor.reportMatch(
                 new Match(
                     bundle.getModel().getUnderlyingResource(),
                     Match.UNIT_CHARACTER,
                     offlen[0],
                     offlen[1]));
             break; // only one package will be listed per header
           }
         }
       } catch (BundleException e) {
       }
     }
   }
 }
 private static Properties findVMProfile(Properties properties) {
   Properties result = new Properties();
   // Find the VM profile name using J2ME properties
   String j2meConfig = properties.getProperty(Constants.J2ME_MICROEDITION_CONFIGURATION);
   String j2meProfiles = properties.getProperty(Constants.J2ME_MICROEDITION_PROFILES);
   String vmProfile = null;
   String javaEdition = null;
   Version javaVersion = null;
   if (j2meConfig != null
       && j2meConfig.length() > 0
       && j2meProfiles != null
       && j2meProfiles.length() > 0) {
     // save the vmProfile based off of the config and profile
     // use the last profile; assuming that is the highest one
     String[] j2meProfileList = ManifestElement.getArrayFromList(j2meProfiles, " "); // $NON-NLS-1$
     if (j2meProfileList != null && j2meProfileList.length > 0)
       vmProfile = j2meConfig + '_' + j2meProfileList[j2meProfileList.length - 1];
   } else {
     // No J2ME properties; use J2SE properties
     // Note that the CDC spec appears not to require VM implementations to set the
     // javax.microedition properties!!  So we will try to fall back to the
     // java.specification.name property, but this is pretty ridiculous!!
     String javaSpecVersion = properties.getProperty("java.specification.version"); // $NON-NLS-1$
     // set the profile and EE based off of the java.specification.version
     // TODO We assume J2ME Foundation and J2SE here.  need to support other profiles J2EE ...
     if (javaSpecVersion != null) {
       StringTokenizer st = new StringTokenizer(javaSpecVersion, " _-"); // $NON-NLS-1$
       javaSpecVersion = st.nextToken();
       String javaSpecName = properties.getProperty("java.specification.name"); // $NON-NLS-1$
       if ("J2ME Foundation Specification".equals(javaSpecName)) // $NON-NLS-1$
       vmProfile =
             "CDC-"
                 + javaSpecVersion
                 + "_Foundation-"
                 + javaSpecVersion; //$NON-NLS-1$ //$NON-NLS-2$
       else {
         // look for JavaSE if 1.6 or greater; otherwise look for J2SE
         Version v16 = new Version("1.6"); // $NON-NLS-1$
         javaEdition = J2SE;
         try {
           javaVersion = new Version(javaSpecVersion);
           if (v16.compareTo(javaVersion) <= 0) javaEdition = JAVASE;
         } catch (IllegalArgumentException e) {
           // do nothing
         }
         vmProfile = javaEdition + javaSpecVersion;
       }
     }
   }
   URL url = null;
   // check for the java profile property for a url
   String propJavaProfile = FrameworkProperties.getProperty(Constants.OSGI_JAVA_PROFILE);
   if (propJavaProfile != null)
     try {
       // we assume a URL
       url = new URL(propJavaProfile);
     } catch (MalformedURLException e1) {
       // try using a relative path in the system bundle
       url = findInSystemBundle(propJavaProfile);
     }
   if (url == null && vmProfile != null) {
     // look for a profile in the system bundle based on the vm profile
     String javaProfile = vmProfile + PROFILE_EXT;
     url = findInSystemBundle(javaProfile);
     if (url == null) url = getNextBestProfile(javaEdition, javaVersion);
   }
   if (url == null)
     // the profile url is still null then use the osgi min profile in OSGi by default
     url = findInSystemBundle("OSGi_Minimum-1.1.profile"); // $NON-NLS-1$
   if (url != null) {
     InputStream in = null;
     try {
       in = url.openStream();
       result.load(new BufferedInputStream(in));
     } catch (IOException e) {
       // TODO consider logging ...
     } finally {
       if (in != null)
         try {
           in.close();
         } catch (IOException ee) {
           // do nothing
         }
     }
   }
   // set the profile name if it does not provide one
   if (result.getProperty(Constants.OSGI_JAVA_PROFILE_NAME) == null)
     if (vmProfile != null)
       result.put(Constants.OSGI_JAVA_PROFILE_NAME, vmProfile.replace('_', '/'));
     else
       // last resort; default to the absolute minimum profile name for the framework
       result.put(Constants.OSGI_JAVA_PROFILE_NAME, "OSGi/Minimum-1.1"); // $NON-NLS-1$
   return result;
 }
  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;
  }
 protected Map<String, String> getManifest(String manifestFile)
     throws IOException, BundleException {
   URL manifest = getBundle().getEntry("/test_files/containerTests/" + manifestFile);
   Assert.assertNotNull("Could not find manifest: " + manifestFile, manifest);
   return ManifestElement.parseBundleManifest(manifest.openStream(), null);
 }