java.util.jar.Attributes Java Examples

The following examples show how to use java.util.jar.Attributes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractProjectCommander.java    From Jpom with MIT License 6 votes vote down vote up
private static String checkJar(File jarFile) {
    try (JarFile jarFile1 = new JarFile(jarFile)) {
        Manifest manifest = jarFile1.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        String mainClass = attributes.getValue(Attributes.Name.MAIN_CLASS);
        if (mainClass == null) {
            return jarFile.getAbsolutePath() + "中没有找到对应的MainClass属性";
        }
        JarClassLoader jarClassLoader = JarClassLoader.load(jarFile);
        try {
            jarClassLoader.loadClass(mainClass);
        } catch (ClassNotFoundException notFound) {
            return jarFile.getAbsolutePath() + "中没有找到对应的MainClass:" + mainClass;
        }
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("解析jar", e);
        return jarFile.getAbsolutePath() + " 解析错误:" + e.getMessage();
    }
    return null;
}
 
Example #2
Source File: URLClassPath.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
URL[] getClassPath() throws IOException {
    if (index != null) {
        return null;
    }

    if (metaIndex != null) {
        return null;
    }

    ensureOpen();
    parseExtensionsDependencies();

    if (SharedSecrets.javaUtilJarAccess().jarFileHasClassPathAttribute(jar)) { // Only get manifest when necessary
        Manifest man = jar.getManifest();
        if (man != null) {
            Attributes attr = man.getMainAttributes();
            if (attr != null) {
                String value = attr.getValue(Name.CLASS_PATH);
                if (value != null) {
                    return parseClassPath(csu, value);
                }
            }
        }
    }
    return null;
}
 
Example #3
Source File: Options.java    From opsu with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns whether the XDG flag in the manifest (if any) is set to "true".
 * @return true if XDG directories are enabled, false otherwise
 */
private static boolean checkXDGFlag() {
	JarFile jarFile = Utils.getJarFile();
	if (jarFile == null)
		return false;
	try {
		Manifest manifest = jarFile.getManifest();
		if (manifest == null)
			return false;
		Attributes attributes = manifest.getMainAttributes();
		String value = attributes.getValue("Use-XDG");
		return (value != null && value.equalsIgnoreCase("true"));
	} catch (IOException e) {
		return false;
	}
}
 
Example #4
Source File: ManifestUtil.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
private static Map<String, String> load(InputStream stream) {
    Map<String, String> props = Maps.newConcurrentMap();

    try {
        Manifest manifest = new Manifest(stream);
        Attributes attributes = manifest.getMainAttributes();

        for (Object key : attributes.keySet()) {
            String value = attributes.getValue((Attributes.Name) key);
            props.put(key.toString(), value);
        }
    } catch (Throwable t) {
        logger.error("#load(): failed", t);
    } finally {
        try {
            stream.close();
        } catch (IOException e) {
            // ignored
        }
    }

    return props;
}
 
Example #5
Source File: URLClassPath.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
URL[] getClassPath() throws IOException {
    if (index != null) {
        return null;
    }

    if (metaIndex != null) {
        return null;
    }

    ensureOpen();
    parseExtensionsDependencies();

    if (SharedSecrets.javaUtilJarAccess().jarFileHasClassPathAttribute(jar)) { // Only get manifest when necessary
        Manifest man = jar.getManifest();
        if (man != null) {
            Attributes attr = man.getMainAttributes();
            if (attr != null) {
                String value = attr.getValue(Name.CLASS_PATH);
                if (value != null) {
                    return parseClassPath(csu, value);
                }
            }
        }
    }
    return null;
}
 
Example #6
Source File: BigJar.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
Manifest createMainClass(File javaFile) throws IOException {
    javaFile.delete();
    List<String> content = new ArrayList<>();
    content.add("public class " + baseName(javaFile) + "{");
    content.add("public static void main(String... args) {");
    content.add("System.out.println(\"Hello World\\n\");");
    content.add("System.exit(0);");
    content.add("}");
    content.add("}");
    createFile(javaFile, content);
    compile(javaFile.getName());
    Manifest manifest = new Manifest();
    manifest.clear();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, baseName(javaFile));
    System.out.println(manifest.getMainAttributes().keySet());
    System.out.println(manifest.getMainAttributes().values());
    return manifest;
}
 
Example #7
Source File: URLClassPath.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
URL[] getClassPath() throws IOException {
    if (index != null) {
        return null;
    }

    if (metaIndex != null) {
        return null;
    }

    ensureOpen();
    parseExtensionsDependencies();

    if (SharedSecrets.javaUtilJarAccess().jarFileHasClassPathAttribute(jar)) { // Only get manifest when necessary
        Manifest man = jar.getManifest();
        if (man != null) {
            Attributes attr = man.getMainAttributes();
            if (attr != null) {
                String value = attr.getValue(Name.CLASS_PATH);
                if (value != null) {
                    return parseClassPath(csu, value);
                }
            }
        }
    }
    return null;
}
 
Example #8
Source File: BundleMakerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testInstallBundle() throws Exception {
    Map<String, String> manifest = ImmutableMap.of(
            Attributes.Name.MANIFEST_VERSION.toString(), "1.2.3", 
            Constants.BUNDLE_VERSION, "4.5.6",
            Constants.BUNDLE_SYMBOLICNAME, "myname");
    generatedJar = bundleMaker.copyAddingManifest(emptyJar, manifest);
    
    Bundle bundle = bundleMaker.installBundle(generatedJar, false);
    assertEquals(bundle.getSymbolicName(), "myname");
    assertEquals(bundle.getVersion(), new Version("4.5.6"));
    
    // Confirm it really is installed in the management context's OSGi framework
    Bundle bundle2 = Osgis.bundleFinder(mgmt.getOsgiManager().get().getFramework())
            .symbolicName("myname")
            .version("4.5.6")
            .findUnique()
            .get();
    assertEquals(bundle2, bundle);
}
 
Example #9
Source File: JoclVersionAction.java    From constellation with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(final ActionEvent e) {
    final com.jogamp.opencl.JoclVersion jv = com.jogamp.opencl.JoclVersion.getInstance();
    final Set<?> names = jv.getAttributeNames();
    final ArrayList<String> lines = new ArrayList<>();
    for (final Object name : names) {
        lines.add(String.format("%s: %s\n", name, jv.getAttribute((Attributes.Name) name)));
    }

    Collections.sort(lines);

    final StringBuilder sb = new StringBuilder();
    sb.append("JOCL Attributes\n");
    for (final String line : lines) {
        sb.append(line);
    }

    final InfoTextPanel itp = new InfoTextPanel(sb.toString());
    final NotifyDescriptor.Message msg = new NotifyDescriptor.Message(itp);
    msg.setTitle(Bundle.CTL_JoclVersionAction());
    DialogDisplayer.getDefault().notify(msg);
}
 
Example #10
Source File: AndroidResourceOutputs.java    From bazel with Apache License 2.0 6 votes vote down vote up
private byte[] manifestContent(@Nullable String targetLabel, @Nullable String injectingRuleKind)
    throws IOException {
  Manifest manifest = new Manifest();
  Attributes attributes = manifest.getMainAttributes();
  attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
  Attributes.Name createdBy = new Attributes.Name("Created-By");
  if (attributes.getValue(createdBy) == null) {
    attributes.put(createdBy, "bazel");
  }
  if (targetLabel != null) {
    // Enable add_deps support. add_deps expects this attribute in the jar manifest.
    attributes.putValue("Target-Label", targetLabel);
  }
  if (injectingRuleKind != null) {
    // add_deps support for aspects. Usually null.
    attributes.putValue("Injecting-Rule-Kind", injectingRuleKind);
  }
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  manifest.write(out);
  return out.toByteArray();
}
 
Example #11
Source File: PackageDefinitionStrategyTypeSimpleTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonSealedIsCompatibleToSealed() throws Exception {
    File file = File.createTempFile(FOO, BAR);
    try {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(Attributes.Name.SEALED, Boolean.TRUE.toString());
        URL url = new ByteBuddy().subclass(Object.class).name("foo.Bar").make().toJar(file, manifest).toURI().toURL();
        ClassLoader classLoader = new URLClassLoader(new URL[]{url}, null);
        Package definedPackage = classLoader.loadClass("foo.Bar").getPackage();
        assertThat(new PackageDefinitionStrategy.Definition.Simple(FOO, BAR, QUX, BAZ, FOO + BAR, QUX + BAZ, null)
                .isCompatibleTo(definedPackage), is(false));
    } finally {
        file.deleteOnExit();
    }
}
 
Example #12
Source File: ExecJarWithAgent.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test that java -jar fails when the executable JAR has the
 * Launcher-Agent-Class attribute and the class does not define an
 * agentmain method.
 */
public void testNoAgentMain() throws Exception {
    // manifest for the executable JAR
    Manifest man = new Manifest();
    Attributes attrs = man.getMainAttributes();
    attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
    attrs.put(Attributes.Name.MAIN_CLASS, "Main");

    // the main class does not define the agentmain method
    attrs.put(new Attributes.Name("Launcher-Agent-Class"), "Main");

    Path app = Paths.get("app.jar");
    Path dir = Paths.get(System.getProperty("test.classes"));

    JarUtils.createJarFile(app, man, dir, Paths.get("Main.class"));

    // java -jar app.jar
    int exitCode = exec(app).shouldContain("NoSuchMethodException").getExitValue();
    assertNotEquals(exitCode, 0);
}
 
Example #13
Source File: FastBuild.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Override
protected Manifest getMeta() {
    Manifest manifest = new Manifest();
    Attributes main = manifest.getMainAttributes();
    main.putValue("Manifest-Version", "1.0");
    main.putValue("Created-By", "1.0 (ApkPatch)");
    main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString());
    main.putValue("Patch-Name", name);
    main.putValue(name + "-Patch-Classes", Formater.dotStringList(classes));
    main.putValue(name + "-Prepare-Classes", Formater.dotStringList(prepareClasses));
    main.putValue(name + "-Used-Methods", Formater.dotStringList(usedMethods));
    main.putValue(name + "-Modified-Classes", Formater.dotStringList(modifiedClasses));
    main.putValue(name + "-Used-Classes", Formater.dotStringList(usedClasses));
    main.putValue(name + "-add-classes", Formater.dotStringList(addClasses));
    return manifest;
}
 
Example #14
Source File: BuildNumberMojoTest.java    From buildnumber-maven-plugin with MIT License 6 votes vote down vote up
@Test
public void Mojo1668Test()
    throws Exception
{
    Assume.assumeTrue( isSvn18() );

    File projDir = resources.getBasedir( "MOJO-1668" );

    MavenExecution mavenExec = maven.forProject( projDir );
    MavenExecutionResult result = mavenExec.execute( "clean" );
    result.assertErrorFreeLog();
    File testDir = result.getBasedir();
    FileUtils.copyDirectoryStructure( new File( testDir, "dotSvnDir" ), new File( testDir, ".svn" ) );
    result = mavenExec.execute( "clean", "verify" );

    File artifact = new File( testDir, "target/buildnumber-maven-plugin-MOJO-1668-1.0-SNAPSHOT.jar" );
    JarFile jarFile = new JarFile( artifact );
    Attributes manifest = jarFile.getManifest().getMainAttributes();
    jarFile.close();
    String buildDate = manifest.getValue( "Build-Date" );
    Assert.assertTrue( buildDate.length() > 0 );
}
 
Example #15
Source File: BuildNumberMojoTest.java    From buildnumber-maven-plugin with MIT License 6 votes vote down vote up
@Test
public void mBuildNum83Test()
    throws Exception
{
    File projDir = resources.getBasedir( "MBUILDNUM-83" );

    MavenExecution mavenExec = maven.forProject( projDir );
    MavenExecutionResult result = mavenExec.execute( "clean", "verify" );
    result.assertErrorFreeLog();

    File testDir = result.getBasedir();
    File artifact = new File( testDir, "target/buildnumber-maven-plugin-basic-it-svnjava-1.0-SNAPSHOT.jar" );
    JarFile jarFile = new JarFile( artifact );
    Attributes manifest = jarFile.getManifest().getMainAttributes();
    jarFile.close();
    String scmRev = manifest.getValue( "SCM-Revision" );
    Assert.assertEquals( "booom", scmRev ); // ??? biim?
}
 
Example #16
Source File: Utils.java    From Scripts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves BAR's implementation date
 *
 * @return the implementation date or an empty strong if date could not be
 *         retrieved.
 */
private static String buildDate() {
	// http://stackoverflow.com/questions/1272648/
	if (BUILD_DATE == null) {
		final Class<Utils> clazz = Utils.class;
		final String className = clazz.getSimpleName() + ".class";
		final String classPath = clazz.getResource(className).toString();
		final String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1)
				+ "/META-INF/MANIFEST.MF";
		try {
			final Manifest manifest = new Manifest(new URL(manifestPath).openStream());
			final Attributes attr = manifest.getMainAttributes();
			BUILD_DATE = attr.getValue("Implementation-Date");
			BUILD_DATE = BUILD_DATE.substring(0, BUILD_DATE.lastIndexOf("T"));
		} catch (final Exception ignored) {
			BUILD_DATE = "";
		}
	}
	return BUILD_DATE;
}
 
Example #17
Source File: ManifestParser.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
private static void parseRequirement(BundleInfo bundleInfo, Attributes mainAttributes,
        String headerName, String type, String versionAttr) throws ParseException {
    ManifestHeaderValue elements = new ManifestHeaderValue(mainAttributes.getValue(headerName));
    for (ManifestHeaderElement element : elements.getElements()) {
        String resolution = element.getDirectives().get(ATTR_RESOLUTION);
        String attVersion = element.getAttributes().get(versionAttr);
        VersionRange version = null;
        try {
            version = versionRangeOf(attVersion);
        } catch (ParseException e) {
            throw new ParseException("The " + headerName + " has an incorrect version: "
                    + attVersion + " (" + e.getMessage() + ")", 0);
        }

        for (String name : element.getValues()) {
            bundleInfo.addRequirement(new BundleRequirement(type, name, version, resolution));
        }
    }
}
 
Example #18
Source File: IllegalAccessTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Specify Add-Exports in JAR file manifest
 */
public void testWithAddExportsInManifest() throws Exception {
    Manifest man = new Manifest();
    Attributes attrs = man.getMainAttributes();
    attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    attrs.put(Attributes.Name.MAIN_CLASS, "TryAccess");
    attrs.put(new Attributes.Name("Add-Exports"), "java.base/sun.security.x509");
    Path jarfile = Paths.get("x.jar");
    Path classes = Paths.get(TEST_CLASSES);
    JarUtils.createJarFile(jarfile, man, classes, Paths.get("TryAccess.class"));

    run(jarfile, "reflectPublicMemberNonExportedPackage", successNoWarning());

    run(jarfile, "setAccessibleNonPublicMemberExportedPackage", successWithWarning());

    // attempt two illegal accesses, one allowed by Add-Exports
    run(jarfile, "reflectPublicMemberNonExportedPackage,"
            + "setAccessibleNonPublicMemberExportedPackage",
        successWithWarning());
}
 
Example #19
Source File: Metadata.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
    * Public main method, used solely for allowing customers to
    * print version and other metadata information from the enclosing
    * JAR file's manifest. This information is printed to stdout;
    * errors are printed to stderr.
    * 
    * @since 2011.1
    * @param args not used.
    */
public static void main(String[] args) {
	try {
		Manifest manifest = getManifest();
		Attributes attr = manifest.getMainAttributes();
		System.out.println(attr.getValue(Name.IMPLEMENTATION_TITLE));
		StringBuilder version = new StringBuilder(
				attr.getValue(Name.IMPLEMENTATION_VERSION));
		String changelist = attr.getValue("Build-Changelist");
		if (changelist != null) {
			version.append('/').append(changelist);
		}
		String type = attr.getValue("Build-Type");
		if (type != null) {
			version.append('/').append(type);
		}
		System.out.println(version);
	} catch (Exception exception) {
		System.err.println(exception.getLocalizedMessage());
	}
}
 
Example #20
Source File: MergePatch.java    From atlas with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
protected Manifest getMeta() {
    Manifest retManifest = new Manifest();
    Attributes main = retManifest.getMainAttributes();
    main.putValue("Manifest-Version", "1.0");
    main.putValue("Created-By", "1.0 (ApkPatch)");
    main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString());
    main.putValue("Patch-Name", name);

    try {
        fillManifest(main);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return retManifest;
}
 
Example #21
Source File: AutomaticModulesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test that a JAR file with a Main-Class attribute that is not in the module
 */
public void testMissingMainClassPackage() throws IOException {
    Manifest man = new Manifest();
    Attributes attrs = man.getMainAttributes();
    attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
    attrs.put(Attributes.Name.MAIN_CLASS, "p.Main");

    Path dir = Files.createTempDirectory(USER_DIR, "mods");
    createDummyJarFile(dir.resolve("m.jar"), man);

    // Main-Class should be ignored because package p is not in module
    Optional<ModuleReference> omref = ModuleFinder.of(dir).find("m");
    assertTrue(omref.isPresent());
    ModuleDescriptor descriptor = omref.get().descriptor();
    assertFalse(descriptor.mainClass().isPresent());
}
 
Example #22
Source File: BundleMakerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreate() throws Exception {
    Map<String, String> manifest = ImmutableMap.of(
        Attributes.Name.MANIFEST_VERSION.toString(), "1.2.3", 
        Constants.BUNDLE_VERSION, "4.5.6",
        Constants.BUNDLE_SYMBOLICNAME, "myname");
    
    generatedJar = bundleMaker.createTempBundle("test", manifest,
        ImmutableMap.of(new ZipEntry("myfile.txt"), new ByteArrayInputStream("mytext".getBytes())));
    assertJarContents(generatedJar, ImmutableMap.of("myfile.txt", "mytext"), true);
    
    @SuppressWarnings("deprecation")
    Bundle bundle = bundleMaker.installBundle(generatedJar, false);
    assertEquals(bundle.getSymbolicName(), "myname");
    assertEquals(bundle.getVersion(), new Version("4.5.6"));
}
 
Example #23
Source File: Writer.java    From yGuard with MIT License 5 votes vote down vote up
private void addDigests( String entryName ) {

      Attributes oldEntryAttributes = this.manifest.getAttributes( entryName );
      Attributes newEntryAttributes = new Attributes( digests.length + 1 );

      if ( null != oldEntryAttributes ) {
        Set<Object> keys = oldEntryAttributes.keySet();
        for ( Object key : keys ) {
          if ( ( (Attributes.Name) key ).toString().indexOf( "Digest" ) == -1 ) {
            newEntryAttributes.put( key, oldEntryAttributes.get( key ) );
          }
        }
      }

      StringBuffer digestsList = new StringBuffer();
      for (int i = 0; i < digests.length; i++) {
        MessageDigest digest = digests[i];

        if (null != digest) {

          String digestKey = digest.getAlgorithm() + "-Digest";
          digestsList.append(digest.getAlgorithm());
          if (i < digests.length - 1){
            digestsList.append(", ");
          }

          String digestVal = Util.toBase64(digest.digest());

          newEntryAttributes.putValue(digestKey, digestVal);
        }
      }

      newEntryAttributes.putValue("Digest-Algorithms", digestsList.toString());

      this.manifest.getEntries().put( entryName, newEntryAttributes );
    }
 
Example #24
Source File: NarBundleExtractor.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private BundleIdentifier getBundleCoordinate(final Attributes attributes) {
    try {
        final String groupId = attributes.getValue(NarManifestEntry.NAR_GROUP.getManifestName());
        final String artifactId = attributes.getValue(NarManifestEntry.NAR_ID.getManifestName());
        final String version = attributes.getValue(NarManifestEntry.NAR_VERSION.getManifestName());

        return new BundleIdentifier(groupId, artifactId, version);
    } catch (Exception e) {
        throw new BundleException("Unable to obtain bundle coordinate due to: " + e.getMessage(), e);
    }
}
 
Example #25
Source File: URLClassLoader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private boolean isSealed(String name, Manifest man) {
    String path = name.replace('.', '/').concat("/");
    Attributes attr = man.getAttributes(path);
    String sealed = null;
    if (attr != null) {
        sealed = attr.getValue(Name.SEALED);
    }
    if (sealed == null) {
        if ((attr = man.getMainAttributes()) != null) {
            sealed = attr.getValue(Name.SEALED);
        }
    }
    return "true".equalsIgnoreCase(sealed);
}
 
Example #26
Source File: BatchEnvironment.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void addJarClassPath(String jarFileName, boolean warn) {
            try {
                String jarParent = new File(jarFileName).getParent();
                JarFile jar = new JarFile(jarFileName);

                try {
                    Manifest man = jar.getManifest();
                    if (man == null) return;

                    Attributes attr = man.getMainAttributes();
                    if (attr == null) return;

                    String path = attr.getValue(Attributes.Name.CLASS_PATH);
                    if (path == null) return;

                    for (StringTokenizer st = new StringTokenizer(path);
                        st.hasMoreTokens();) {
                        String elt = st.nextToken();
                        if (jarParent != null)
                            elt = new File(jarParent, elt).getCanonicalPath();
                        addFile(elt, warn);
                    }
                } finally {
                    jar.close();
                }
            } catch (IOException e) {
//              log.error(Position.NOPOS,
//                        "error.reading.file", jarFileName,
//                        e.getLocalizedMessage());
            }
        }
 
Example #27
Source File: JarLoader.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Map<Resource.Attribute, String> getAttributes(@Nullable Attributes attributes) {
  if (attributes == null) return null;
  Map<Resource.Attribute, String> map = null;

  for (Pair<Resource.Attribute, Attributes.Name> p : PACKAGE_FIELDS) {
    String value = attributes.getValue(p.second);
    if (value != null) {
      if (map == null) map = new EnumMap<Resource.Attribute, String>(Resource.Attribute.class);
      map.put(p.first, value);
    }
  }

  return map;
}
 
Example #28
Source File: WebServerComponentTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void createJarFile(File srcFile, File jarFile) throws IOException {
   Manifest manifest = new Manifest();
   manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
   try (JarOutputStream target = new JarOutputStream(new FileOutputStream(jarFile), manifest)) {
      addFile(srcFile, target, "src/test/webapp");
   }
}
 
Example #29
Source File: ContentComparator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 *  Compares two manifest files. First check is for number of attributes,
 * next one is comparing name-value pairs.
 *
 *@param mf1, mf2 manifests to compare
 *@param ignoredEntries array of manifest entries to ignore
 *@return true if files contains the same entries/values in manifest
 */
public static boolean equalsManifest(File mf1, File mf2, String[] ignoredEntries) {
    if (ignoredEntries == null) {
        ignoredEntries = new String[]{};
    }
    try {
        Manifest m1 = new Manifest(new FileInputStream(mf1));
        Manifest m2 = new Manifest(new FileInputStream(mf2));
        Attributes a1 = m1.getMainAttributes();
        Attributes a2 = m2.getMainAttributes();
        if (a1.size() != a2.size()) {
            return false;
        }
        for (Iterator<Object> i = a1.keySet().iterator(); i.hasNext();) {
            Attributes.Name a = (Attributes.Name) i.next();
            boolean b = true;
            for (int j = 0; j < ignoredEntries.length; j++) {
                if (a.toString().equals(ignoredEntries[j])) {
                    a2.remove(a);
                    b = false;
                    break;
                }
            }
            if (b && (a1.get(a).equals(a2.get(a)))) {
                a2.remove(a);
            }
        }
        return a2.isEmpty();
    } catch (FileNotFoundException fnfe) {
        System.err.println("Exception from test - comparing manifests");
        fnfe.printStackTrace(System.err);
    } catch (IOException ioe) {
        System.err.println("Exception from test - comparing manifests");
        ioe.printStackTrace(System.err);
    }
    return false;
}
 
Example #30
Source File: JarFileSystem.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected Enumeration<String>  attributes(String name) {
    Attributes attr1 = getManifest().getAttributes(name);

    if (attr1 != null) {
        class ToString implements org.openide.util.Enumerations.Processor<Object, String> {
            public String process(Object obj, Collection<Object> ignore) {
                return obj.toString();
            }
        }

        return org.openide.util.Enumerations.convert(Collections.enumeration(attr1.keySet()), new ToString());
    } else {
        return org.openide.util.Enumerations.empty();
    }
}