示例#1
0
 /** @tests java.util.jar.Attributes#clear() */
 public void test_clear() {
   a.clear();
   assertNull("a) All entries should be null after clear", a.get("1"));
   assertNull("b) All entries should be null after clear", a.get("2"));
   assertNull("c) All entries should be null after clear", a.get("3"));
   assertNull("d) All entries should be null after clear", a.get("4"));
   assertTrue("Should not contain any keys", !a.containsKey("1"));
 }
示例#2
0
 /**
  * Returns the manifest value for the specified key.
  *
  * @param key key
  * @return value or {@code null}
  */
 public static Object get(final String key) {
   if (MAP != null) {
     for (final Object o : MAP.keySet()) {
       if (key.equals(o.toString())) return MAP.get(o);
     }
   }
   return null;
 }
 public ManifestAppletDefImpl(String descriptorName, ManifestModel manifest, String appletName) {
   super(descriptorName, manifest);
   this.appletName = appletName;
   Attributes mainAttributes = manifest.getMainAttributes();
   String extensionListValue =
       (mainAttributes.containsKey(Name.EXTENSION_LIST)
           ? String.valueOf(mainAttributes.get(Name.EXTENSION_LIST)) + " " + appletName
           : appletName);
   manifest.getMainAttributes().put(Name.EXTENSION_LIST, extensionListValue);
 }
  public static void updateManifest(
      @NotNull final VirtualFile file,
      final @Nullable String mainClass,
      final @Nullable List<String> classpath,
      final boolean replaceValues) {
    final Manifest manifest = readManifest(file);
    final Attributes mainAttributes = manifest.getMainAttributes();

    if (mainClass != null) {
      mainAttributes.put(Attributes.Name.MAIN_CLASS, mainClass);
    } else if (replaceValues) {
      mainAttributes.remove(Attributes.Name.MAIN_CLASS);
    }

    if (classpath != null && !classpath.isEmpty()) {
      List<String> updatedClasspath;
      if (replaceValues) {
        updatedClasspath = classpath;
      } else {
        updatedClasspath = new ArrayList<String>();
        final String oldClasspath = (String) mainAttributes.get(Attributes.Name.CLASS_PATH);
        if (!StringUtil.isEmpty(oldClasspath)) {
          updatedClasspath.addAll(StringUtil.split(oldClasspath, " "));
        }
        for (String path : classpath) {
          if (!updatedClasspath.contains(path)) {
            updatedClasspath.add(path);
          }
        }
      }
      mainAttributes.put(Attributes.Name.CLASS_PATH, StringUtil.join(updatedClasspath, " "));
    } else if (replaceValues) {
      mainAttributes.remove(Attributes.Name.CLASS_PATH);
    }

    ManifestBuilder.setVersionAttribute(mainAttributes);

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              @Override
              public void run() {
                try {
                  final OutputStream outputStream = file.getOutputStream(ManifestFileUtil.class);
                  try {
                    manifest.write(outputStream);
                  } finally {
                    outputStream.close();
                  }
                } catch (IOException e) {
                  LOG.info(e);
                }
              }
            });
  }
示例#5
0
 private boolean isAmbiguousMainClass(Manifest m) {
   if (ename != null) {
     Attributes global = m.getMainAttributes();
     if ((global.get(Attributes.Name.MAIN_CLASS) != null)) {
       error(getMsg("error.bad.eflag"));
       usageError();
       return true;
     }
   }
   return false;
 }
示例#6
0
  /** @tests java.util.jar.Attributes.put(java.lang.Object, java.lang.Object) */
  public void test_putLjava_lang_ObjectLjava_lang_Object_Null() {

    Attributes attribute = new Attributes();

    assertFalse(attribute.containsKey(null));
    assertFalse(attribute.containsValue(null));
    attribute.put(null, null);
    attribute.put(null, null);
    assertEquals(1, attribute.size());
    assertTrue(attribute.containsKey(null));
    assertTrue(attribute.containsValue(null));
    assertNull(attribute.get(null));

    String value = "It's null";
    attribute.put(null, value);
    assertEquals(1, attribute.size());
    assertEquals(value, attribute.get(null));

    Attributes.Name name = new Attributes.Name("null");
    attribute.put(name, null);
    assertEquals(2, attribute.size());
    assertNull(attribute.get(name));
  }
示例#7
0
 /** @tests java.util.jar.Attributes#putAll(java.util.Map) */
 public void test_putAllLjava_util_Map() {
   Attributes b = new Attributes();
   b.putValue("3", "san");
   b.putValue("4", "shi");
   b.putValue("5", "go");
   b.putValue("6", "roku");
   a.putAll(b);
   assertEquals("Should not have been replaced", "one", a.getValue("1"));
   assertEquals("Should have been replaced", "san", a.getValue("3"));
   assertEquals("Should have been added", "go", a.getValue("5"));
   Attributes atts = new Attributes();
   assertNull("Assert 0: ", atts.put(Attributes.Name.CLASS_PATH, "tools.jar"));
   assertNull("Assert 1: ", atts.put(Attributes.Name.MANIFEST_VERSION, "1"));
   Attributes atts2 = new Attributes();
   atts2.putAll(atts);
   assertEquals("Assert 2:", "tools.jar", atts2.get(Attributes.Name.CLASS_PATH));
   assertEquals("Assert 3: ", "1", atts2.get(Attributes.Name.MANIFEST_VERSION));
   try {
     atts.putAll(Collections.EMPTY_MAP);
     fail("Assert 4: no class cast from attrib parameter");
   } catch (ClassCastException e) {
     // Expected
   }
 }
 private static String getVersionFromManifest(File artifact) throws IOException {
   String versionNumber = null;
   try (JarFile jar = new JarFile(artifact)) {
     Manifest manifest = jar.getManifest();
     Attributes attributes = manifest.getMainAttributes();
     if (attributes != null) {
       for (Object o : attributes.keySet()) {
         Attributes.Name key = (Attributes.Name) o;
         String keyword = key.toString();
         if (keyword.equals("Implementation-Version") || keyword.equals("Bundle-Version")) {
           versionNumber = (String) attributes.get(key);
           break;
         }
       }
     }
   }
   return versionNumber;
 }
 public void addExportedPackage(
     final IJavaProject pluginProject, final String... exportedPackages) {
   try {
     IProject _project = pluginProject.getProject();
     final IFile manifestFile = _project.getFile("META-INF/MANIFEST.MF");
     final InputStream manifestContent = manifestFile.getContents();
     Manifest _xtrycatchfinallyexpression = null;
     try {
       _xtrycatchfinallyexpression = new Manifest(manifestContent);
     } finally {
       manifestContent.close();
     }
     final Manifest manifest = _xtrycatchfinallyexpression;
     final Attributes attrs = manifest.getMainAttributes();
     boolean _containsKey = attrs.containsKey("Export-Package");
     if (_containsKey) {
       Object _get = attrs.get("Export-Package");
       String _plus = (_get + ",");
       String _join =
           IterableExtensions.join(((Iterable<?>) Conversions.doWrapArray(exportedPackages)), ",");
       String _plus_1 = (_plus + _join);
       attrs.putValue("Export-Package", _plus_1);
     } else {
       String _join_1 =
           IterableExtensions.join(((Iterable<?>) Conversions.doWrapArray(exportedPackages)), ",");
       attrs.putValue("Export-Package", _join_1);
     }
     final ByteArrayOutputStream out = new ByteArrayOutputStream();
     manifest.write(out);
     byte[] _byteArray = out.toByteArray();
     final ByteArrayInputStream in = new ByteArrayInputStream(_byteArray);
     BufferedInputStream _bufferedInputStream = new BufferedInputStream(in);
     manifestFile.setContents(_bufferedInputStream, true, true, null);
   } catch (Throwable _e) {
     throw Exceptions.sneakyThrow(_e);
   }
 }
示例#10
0
  /**
   * Extract a kar from a given URI into a repository dir and resource dir and populate
   * shouldInstallFeatures and featureRepos
   *
   * @param repoDir directory to write the repository contents of the kar to
   * @param resourceDir directory to write the resource contents of the kar to
   */
  public void extract(File repoDir, File resourceDir) {
    InputStream is = null;
    JarInputStream zipIs = null;
    FeatureDetector featureDetector = new FeatureDetector();
    this.featureRepos = new ArrayList<URI>();
    this.shouldInstallFeatures = true;

    try {
      is = karUri.toURL().openStream();
      repoDir.mkdirs();

      if (!repoDir.isDirectory()) {
        throw new RuntimeException("The KAR file " + karUri + " is already installed");
      }

      LOGGER.debug("Uncompress the KAR file {} into directory {}", karUri, repoDir);
      zipIs = new JarInputStream(is);
      boolean scanForRepos = true;

      Manifest manifest = zipIs.getManifest();
      if (manifest != null) {
        Attributes attr = manifest.getMainAttributes();
        String featureStartSt =
            (String) attr.get(new Attributes.Name(MANIFEST_ATTR_KARAF_FEATURE_START));
        if ("false".equals(featureStartSt)) {
          shouldInstallFeatures = false;
        }
        String featureReposAttr =
            (String) attr.get(new Attributes.Name(MANIFEST_ATTR_KARAF_FEATURE_REPOS));
        if (featureReposAttr != null) {
          featureRepos.add(new URI(featureReposAttr));
          scanForRepos = false;
        }
      }

      ZipEntry entry = zipIs.getNextEntry();
      while (entry != null) {
        if (entry.getName().startsWith("repository")) {
          String path = entry.getName().substring("repository/".length());
          File destFile = new File(repoDir, path);
          extract(zipIs, entry, destFile);
          if (scanForRepos && featureDetector.isFeaturesRepository(destFile)) {
            Map map = new HashMap<>();
            String uri = Parser.pathToMaven(path, map);
            if (map.get("classifier") != null
                && ((String) map.get("classifier")).equalsIgnoreCase("features"))
              featureRepos.add(URI.create(uri));
            else featureRepos.add(destFile.toURI());
          }
        }

        if (entry.getName().startsWith("resource")) {
          String path = entry.getName().substring("resource/".length());
          File destFile = new File(resourceDir, path);
          extract(zipIs, entry, destFile);
        }
        entry = zipIs.getNextEntry();
      }
    } catch (Exception e) {
      throw new RuntimeException(
          "Error extracting kar file " + karUri + " into dir " + repoDir + ": " + e.getMessage(),
          e);
    } finally {
      closeStream(zipIs);
      closeStream(is);
    }
  }
示例#11
0
  /** @param certFile */
  private void verifyCertificate(String certFile) {
    // Found Digital Sig, .SF should already have been read
    String signatureFile = certFile.substring(0, certFile.lastIndexOf('.')) + ".SF";
    byte[] sfBytes = metaEntries.get(signatureFile);
    if (sfBytes == null) {
      return;
    }

    byte[] manifest = metaEntries.get(JarFile.MANIFEST_NAME);
    // Manifest entry is required for any verifications.
    if (manifest == null) {
      return;
    }

    byte[] sBlockBytes = metaEntries.get(certFile);
    try {
      Certificate[] signerCertChain =
          JarUtils.verifySignature(
              new ByteArrayInputStream(sfBytes), new ByteArrayInputStream(sBlockBytes));
      /*
       * Recursive call in loading security provider related class which
       * is in a signed JAR.
       */
      if (metaEntries == null) {
        return;
      }
      if (signerCertChain != null) {
        certificates.put(signatureFile, signerCertChain);
      }
    } catch (IOException e) {
      return;
    } catch (GeneralSecurityException e) {
      throw failedVerification(jarName, signatureFile);
    }

    // Verify manifest hash in .sf file
    Attributes attributes = new Attributes();
    HashMap<String, Attributes> entries = new HashMap<String, Attributes>();
    try {
      ManifestReader im = new ManifestReader(sfBytes, attributes);
      im.readEntries(entries, null);
    } catch (IOException e) {
      return;
    }

    // Do we actually have any signatures to look at?
    if (attributes.get(Attributes.Name.SIGNATURE_VERSION) == null) {
      return;
    }

    boolean createdBySigntool = false;
    String createdBy = attributes.getValue("Created-By");
    if (createdBy != null) {
      createdBySigntool = createdBy.indexOf("signtool") != -1;
    }

    // Use .SF to verify the mainAttributes of the manifest
    // If there is no -Digest-Manifest-Main-Attributes entry in .SF
    // file, such as those created before java 1.5, then we ignore
    // such verification.
    if (mainAttributesEnd > 0 && !createdBySigntool) {
      String digestAttribute = "-Digest-Manifest-Main-Attributes";
      if (!verify(attributes, digestAttribute, manifest, 0, mainAttributesEnd, false, true)) {
        throw failedVerification(jarName, signatureFile);
      }
    }

    // Use .SF to verify the whole manifest.
    String digestAttribute = createdBySigntool ? "-Digest" : "-Digest-Manifest";
    if (!verify(attributes, digestAttribute, manifest, 0, manifest.length, false, false)) {
      Iterator<Map.Entry<String, Attributes>> it = entries.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry<String, Attributes> entry = it.next();
        Manifest.Chunk chunk = man.getChunk(entry.getKey());
        if (chunk == null) {
          return;
        }
        if (!verify(
            entry.getValue(),
            "-Digest",
            manifest,
            chunk.start,
            chunk.end,
            createdBySigntool,
            false)) {
          throw invalidDigest(signatureFile, entry.getKey(), jarName);
        }
      }
    }
    metaEntries.put(signatureFile, null);
    signatures.put(signatureFile, entries);
  }