Java 类java.util.jar.Manifest 实例源码

项目:GazePlay    文件:GazePlayLauncher.java   
private static String findVersionInfo(String applicationName) throws IOException {
    Enumeration<URL> resources = Thread.currentThread().getContextClassLoader()
            .getResources("META-INF/MANIFEST.MF");
    while (resources.hasMoreElements()) {
        URL manifestUrl = resources.nextElement();
        Manifest manifest = new Manifest(manifestUrl.openStream());
        Attributes mainAttributes = manifest.getMainAttributes();
        String implementationTitle = mainAttributes.getValue("Implementation-Title");
        if (implementationTitle != null && implementationTitle.equals(applicationName)) {
            String implementationVersion = mainAttributes.getValue("Implementation-Version");
            String buildTime = mainAttributes.getValue("Build-Time");
            return implementationVersion + " (" + buildTime + ")";
        }
    }
    return "Current Version";
}
项目:Reer    文件:DefaultManifest.java   
static void writeTo(org.gradle.api.java.archives.Manifest manifest, OutputStream outputStream, String contentCharset) {
    try {
        Manifest javaManifest = generateJavaManifest(manifest.getEffectiveManifest());
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        javaManifest.write(buffer);
        byte[] manifestBytes;
        if (DEFAULT_CONTENT_CHARSET.equals(contentCharset)) {
            manifestBytes = buffer.toByteArray();
        } else {
            // Convert the UTF-8 manifest bytes to the requested content charset
            manifestBytes = buffer.toString(DEFAULT_CONTENT_CHARSET).getBytes(contentCharset);
        }
        outputStream.write(manifestBytes);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:Reer    文件:DefaultManifest.java   
@Override
public org.gradle.api.java.archives.Manifest writeTo(Object path) {
    File manifestFile = fileResolver.resolve(path);
    try {
        File parentFile = manifestFile.getParentFile();
        if (parentFile != null) {
            FileUtils.forceMkdir(parentFile);
        }
        IoActions.withResource(new FileOutputStream(manifestFile), new Action<FileOutputStream>() {
            @Override
            public void execute(FileOutputStream fileOutputStream) {
                writeTo(fileOutputStream);
            }
        });
        return this;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:Reer    文件:DefaultManifest.java   
private void read(Object manifestPath) {
    File manifestFile = fileResolver.resolve(manifestPath);
    try {
        byte[] manifestBytes = FileUtils.readFileToByteArray(manifestFile);
        manifestBytes = prepareManifestBytesForInteroperability(manifestBytes);
        // Eventually convert manifest content to UTF-8 before handing it to java.util.jar.Manifest
        if (!DEFAULT_CONTENT_CHARSET.equals(contentCharset)) {
            manifestBytes = new String(manifestBytes, contentCharset).getBytes(DEFAULT_CONTENT_CHARSET);
        }
        // Effectively read the manifest
        Manifest javaManifest = new Manifest(new ByteArrayInputStream(manifestBytes));
        addJavaManifestToAttributes(javaManifest);
        addJavaManifestToSections(javaManifest);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:incubator-netbeans    文件:ParseManifest.java   
@Override
public void execute() throws BuildException {
    if (manifest == null) {
        throw new BuildException("Must specify parameter 'manifest'.");
    }
    if (property == null) {
        throw new BuildException("Must specify parameter 'property'.");
    }
    if (attribute == null) {
        throw new BuildException("Must specify parameter 'attribute'.");
    }
    try {
        try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(manifest))) {
            Manifest mf = new Manifest(is);
            String attr = mf.getMainAttributes().getValue(attribute);
            if (attr == null)
                return;
            getProject().setProperty(property, attr);
        }
    } catch (Exception x) {
        throw new BuildException("Reading manifest " + manifest + ": " + x, x, getLocation());
    }
}
项目:incubator-netbeans    文件:ModuleDependencies.java   
private static void addDependencies (TreeSet<Dependency> addTo, java.util.jar.Manifest man, Dependency.Type dependencyType, String attrName) throws BuildException {
    String value = man.getMainAttributes ().getValue (attrName);
    if (value == null) {
        return;
    }

    StringTokenizer tok = new StringTokenizer (value, ",");
    while (tok.hasMoreElements ()) {
        String nextDep = tok.nextToken ();
        StringTokenizer dep = new StringTokenizer (nextDep, "=>", true);
        if (dep.countTokens () == 1) {
            addTo.add (new Dependency (dep.nextToken ().trim (), dependencyType, false, null));
            continue;
        }

        if (dep.countTokens () == 3) {
            String name = dep.nextToken ().trim ();
            String equal = dep.nextToken ().trim ();
            String comp = dep.nextToken ().trim ();
            addTo.add (new Dependency (name, dependencyType, equal.equals ("="), comp));
            continue;
        }

        throw new BuildException ("Cannot parse dependency: " + value);
    }
}
项目:neoscada    文件:Starter.java   
private Bundle readFromManifest ( final String location, final Manifest m ) throws IOException
{
    final Object sn = m.getMainAttributes ().getValue ( Constants.BUNDLE_SYMBOLICNAME );
    if ( ! ( sn instanceof String ) )
    {
        return null;
    }

    final Object version = m.getMainAttributes ().getValue ( Constants.BUNDLE_VERSION );
    if ( ! ( version instanceof String ) )
    {
        return null;
    }

    String symName = (String)sn;
    symName = symName.split ( ";", 2 )[0];

    return new Bundle ( symName, new Version ( (String)version ), location );
}
项目:openjdk-jdk10    文件:DefineClass.java   
private static void loadInstrumentationAgent(String myName, byte[] buf) throws Exception {
    // Create agent jar file on the fly
    Manifest m = new Manifest();
    m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    m.getMainAttributes().put(new Attributes.Name("Agent-Class"), myName);
    m.getMainAttributes().put(new Attributes.Name("Can-Redefine-Classes"), "true");
    File jarFile = File.createTempFile("agent", ".jar");
    jarFile.deleteOnExit();
    JarOutputStream jar = new JarOutputStream(new FileOutputStream(jarFile), m);
    jar.putNextEntry(new JarEntry(myName.replace('.', '/') + ".class"));
    jar.write(buf);
    jar.close();
    String pid = Long.toString(ProcessTools.getProcessId());
    System.out.println("Our pid is = " + pid);
    VirtualMachine vm = VirtualMachine.attach(pid);
    vm.loadAgent(jarFile.getAbsolutePath());
}
项目:lazycat    文件:WebappClassLoaderBase.java   
/**
 * Returns true if the specified package name is sealed according to the
 * given manifest.
 */
protected boolean isPackageSealed(String name, Manifest man) {

    String path = name.replace('.', '/') + '/';
    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);

}
项目:incubator-netbeans    文件:PackageAttrsCache.java   
final String[] findImpl(URL src, Manifest man, String path) {
    String key = src.toExternalForm();
    if (key.startsWith("jar:file:")) { // NOI18N
        key = key.substring(9);
    }
    if (!key.endsWith("!/")) { // NOI18N
        key += "!/"; // NOI18N
    }
    key += path;
    String[] arr;
    if (cache instanceof ConcurrentHashMap) {
        arr = extractFromManifest(man, path);
        if (isEmpty(arr)) {
            arr = EMPTY;
        } else {
            cache.put(key, arr);
        }
    } else {
        arr = cache.get(key);
        if (arr == null) {
            arr = EMPTY;
        }
    }
    return arr;
}
项目:jdk8u-jdk    文件:Main.java   
private boolean updateManifest(Manifest m, ZipOutputStream zos)
    throws IOException
{
    addVersion(m);
    addCreatedBy(m);
    if (ename != null) {
        addMainClass(m, ename);
    }
    ZipEntry e = new ZipEntry(MANIFEST_NAME);
    e.setTime(System.currentTimeMillis());
    if (flag0) {
        crc32Manifest(e, m);
    }
    zos.putNextEntry(e);
    m.write(zos);
    if (vflag) {
        output(getMsg("out.update.manifest"));
    }
    return true;
}
项目:incubator-netbeans    文件:RemoveWritablesTest.java   
private File createModuleJar(String manifest) throws IOException {
    // XXX use TestFileUtils.writeZipFile
    File jarFile = new File( getWorkDir(), "mymodule.jar" );

    JarOutputStream os = new JarOutputStream(new FileOutputStream(jarFile), new Manifest(
        new ByteArrayInputStream(manifest.getBytes())
    ));
    JarEntry entry = new JarEntry("foo/mf-layer.xml");
    os.putNextEntry( entry );

    File l3 = new File(new File(new File(getDataDir(), "layers"), "data"), "layer3.xml");
    InputStream is = new FileInputStream(l3);
    FileUtil.copy( is, os );
    is.close();
    os.close();

    return jarFile;
}
项目:atlas    文件:FastBuild.java   
@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;
}
项目:mobile-store    文件:ZipSigner.java   
/**
 * Copy all the files in a manifest from input to output.  We set
 * the modification times in the output to a fixed time, so as to
 * reduce variation in the output file and make incremental OTAs
 * more efficient.
 */
private void copyFiles(Manifest manifest, Map<String,ZioEntry> input, ZipOutput output, long timestamp)
    throws IOException 
{
    Map<String, Attributes> entries = manifest.getEntries();
    List<String> names = new ArrayList<String>(entries.keySet());
    Collections.sort(names);
    int i = 1;
    for (String name : names) {
        if (canceled) break;
        progressHelper.progress(ProgressEvent.PRORITY_NORMAL, resourceAdapter.getString(ResourceAdapter.Item.COPYING_ZIP_ENTRY, i, names.size()));
        i += 1;
        ZioEntry inEntry = input.get(name);
        inEntry.setTime(timestamp);
        output.write(inEntry);

    }
}
项目:openjdk-jdk10    文件:AutomaticModulesTest.java   
/**
 * 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());
}
项目:fatjar    文件:Main.java   
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException,
                                      InvocationTargetException, IllegalAccessException {
    URL url = FatJarClassLoaderUtils.getLocatoin(Main.class);
    File fatJarFile = new File(url.getFile());
    JarFile jar = new JarFile(fatJarFile);
    Manifest manifest = jar.getManifest();
    Attributes attributes = manifest.getMainAttributes();
    String startClass = attributes.getValue(START_CLASS_KEY);
    if (startClass == null || startClass.length() == 0) {
        throw new IllegalArgumentException(START_CLASS_KEY + " is missing");
    }
    ClassLoader classLoader = Main.class.getClassLoader();
    FatJarClassLoader fatJarClassLoader = new FatJarClassLoader(jar, url, classLoader.getParent(), classLoader,
                                                                false, true);
    ClassLoader classLoader1 = FatJarClassLoaderUtils.injectFatJarClassLoader(classLoader, fatJarClassLoader);
    Class<?> mainClazz = Class.forName(startClass, true, classLoader1);
    Method invokeMethod = mainClazz.getMethod("main", String[].class);
    invokeMethod.invoke(null, (Object) args);
}
项目:incubator-netbeans    文件:ModuleFactoryAlienTest.java   
@Override
public Module create(
    File jar, Object history,
    boolean reloadable, boolean autoload, boolean eager,
    ModuleManager mgr, Events ev
) throws IOException {
    try {
        Module m = super.create(jar, history, reloadable, autoload, eager, mgr, ev);
        registerBundle(m);
        return m;
    } catch (InvalidException ex) {
        Manifest mani = ex.getManifest();
        if (mani != null) {
            String name = mani.getMainAttributes().getValue("AlienName"); // NOI18N
            if (name == null) {
                throw ex;
            }
            return new AlienModule(mani, jar, mgr, ev, history, reloadable, autoload, eager);
        }
        throw ex;
    }
}
项目:walle    文件:WalleCommandLine.java   
private static String getVersion() {
    try {
        final Enumeration resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
        while (resEnum.hasMoreElements()) {
            try {
                final URL url = (URL) resEnum.nextElement();
                final InputStream is = url.openStream();
                if (is != null) {
                    final Manifest manifest = new Manifest(is);
                    final Attributes mainAttribs = manifest.getMainAttributes();
                    final String version = mainAttribs.getValue("Walle-Version");
                    if (version != null) {
                        return version;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return null;
}
项目:imagingbook-common    文件:Info.java   
/**
 * Reads version information from the MANIFEST.MF file of the JAR file from
 * which this class was loaded. 
 * 
 * @return A string with the version information. 
 * The string "UNKNOWN" is returned if the class was not loaded from a JAR file or if 
 * the version information could not be determined.
 */
public static String getVersionInfo() {
    Manifest mf = FileUtils.getJarManifest(Info.class);
    if (mf == null) {
        return "UNKNOWN";
    }
    //IJ.log("listing attributes");
    Attributes attr = mf.getMainAttributes();
    String version = null;
    String buildDate = null;
    try {
        version = attr.getValue("Implementation-Version");
        buildDate = attr.getValue("Build-Date");
    } catch (IllegalArgumentException e) { }
    return version + " (" + buildDate + ")";
}
项目:elasticsearch_my    文件:JarHellTests.java   
public void testRequiredJDKVersionTooOld() throws Exception {
    Path dir = createTempDir();
    List<Integer> current = JavaVersion.current().getVersion();
    List<Integer> target = new ArrayList<>(current.size());
    for (int i = 0; i < current.size(); i++) {
        target.add(current.get(i) + 1);
    }
    JavaVersion targetVersion = JavaVersion.parse(Strings.collectionToDelimitedString(target, "."));


    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
    attributes.put(new Attributes.Name("X-Compile-Target-JDK"), targetVersion.toString());
    URL[] jars = {makeJar(dir, "foo.jar", manifest, "Foo.class")};
    try {
        JarHell.checkJarHell(jars);
        fail("did not get expected exception");
    } catch (IllegalStateException e) {
        assertTrue(e.getMessage().contains("requires Java " + targetVersion.toString()));
        assertTrue(e.getMessage().contains("your system: " + JavaVersion.current().toString()));
    }
}
项目:FJ-VDMJ    文件:VDMJC.java   
private static String getVersion()
{
    try
    {
        String path = VDMJC.class.getName().replaceAll("\\.", "/");
        URL url = VDMJC.class.getResource("/" + path + ".class");
        JarURLConnection conn = (JarURLConnection)url.openConnection();
        JarFile jar = conn.getJarFile();
        Manifest mf = jar.getManifest();
        String version = (String)mf.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_VERSION);
        return version;
    }
    catch (Exception e)
    {
        return null;
    }
}
项目:JRediClients    文件:Version.java   
public static void logVersion() {
    try {
        Enumeration<URL> resources = Version.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
        while (resources.hasMoreElements()) {
                Manifest manifest = new Manifest(resources.nextElement().openStream());
                Attributes attrs = manifest.getMainAttributes();
                if (attrs == null) {
                    continue;
                }
                String name = attrs.getValue("Bundle-Name");
                if (name != null && name.equals("Redisson")) {
                    log.info("Redisson " + attrs.getValue("Bundle-Version"));
                    break;
                }
        }
    } catch (Exception E) {
        // skip it
    }
}
项目:reflect    文件:Scanner.java   
private void scanJarManifest(File file, Manifest manifest, ClassLoader loader)
    throws Exception {
  if (manifest == null) {
    return;
  }

  String classPath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
  if (Strings.isNullOrEmpty(classPath)) {
    return;
  }

  for (String path : CLASS_PATH_ATTRIBUTE_SPLITTER.split(classPath)) {
    URL url = new URL(file.toURI().toURL(), path);
    scan(url, loader);
  }
}
项目:openjdk-jdk10    文件:ExecJarWithAgent.java   
/**
 * 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);
}
项目:incubator-netbeans    文件:SingleModulePropertiesTest.java   
public void testAvailablePublicPackages() throws Exception {
    Map<String,String> contents = new HashMap<String,String>();
    contents.put("lib/pkg/Clazz3.class", "");
    contents.put("lib/pkg2/Clazz4.class", "");
    contents.put("1.0/oldlib/Clazz5.class", ""); // #72669
    File jar = new File(getWorkDir(), "some.jar");
    createJar(jar, contents, new Manifest());
    SuiteProject sweet = generateSuite("sweet");
    File moduleDir = new File(getWorkDir(), "module");
    NbModuleProjectGenerator.createSuiteLibraryModule(
            moduleDir, "module", "Module", "module/Bundle.properties",
            sweet.getProjectDirectoryFile(), null, new File[] {jar});
    NbModuleProject p = (NbModuleProject) ProjectManager.getDefault().findProject(FileUtil.toFileObject(moduleDir));
    FileObject srcDir = p.getProjectDirectory().getFileObject("src");
    FileUtil.createData(srcDir, "pkg1/Clazz1.java");
    FileUtil.createData(srcDir, "pkg1/Clazz2.java");
    FileUtil.createData(srcDir, "pkg2/CVS/#1.20#Clazz1.java");
    FileUtil.createData(srcDir, "pkg2/Clazz1.java");
    FileUtil.createData(srcDir, "pkg2/deeper/Clazz1.java");
    FileUtil.createData(srcDir, "pkg2/deeper/and/deeper/Clazz1.java");
    FileUtil.createData(srcDir, ".broken/Clazz.java"); // #72669
    assertEquals(Arrays.asList("lib.pkg", "lib.pkg2", "pkg1", "pkg2", "pkg2.deeper", "pkg2.deeper.and.deeper"),
            new ArrayList<String>(SingleModuleProperties.getInstance(p).getAvailablePublicPackages()));
}
项目:openjdk-jdk10    文件:BigJar.java   
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;
}
项目:incubator-netbeans    文件:LayerHandle.java   
/**
 * Find the XML layer file for this project, if it exists.
 * @return the layer, or null
 */
public FileObject getLayerFile() {
    if (layerXML != null) {
        return layerXML;
    }
    NbModuleProvider module = project.getLookup().lookup(NbModuleProvider.class);
    if (module == null) { // #126939: other project type
        return null;
    }
    Manifest mf = Util.getManifest(module.getManifestFile());
    if (mf == null) {
        return null;
    }
    String path = ManifestManager.getInstance(mf, false).getLayer();
    if (path == null) {
        return null;
    }
    return Util.getResource(project, path);
}
项目:javaide    文件:URLClassPath.java   
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;
}
项目:incubator-netbeans    文件:MakeJNLPTest.java   
protected final File generateJar (String prefix, String[] content, Manifest manifest, Properties props) throws IOException {
    File f = createNewJarFile (prefix);

    if (props != null) {
        manifest.getMainAttributes().putValue("OpenIDE-Module-Localizing-Bundle", "some/fake/prop/name/Bundle.properties");
    }

    try (JarOutputStream os = new JarOutputStream (new FileOutputStream (f), manifest)) {
        if (props != null) {
            os.putNextEntry(new JarEntry("some/fake/prop/name/Bundle.properties"));
            props.store(os, "# properties for the module");
            os.closeEntry();
        }


        for (int i = 0; i < content.length; i++) {
            os.putNextEntry(new JarEntry (content[i]));
            os.closeEntry();
        }
        os.closeEntry ();
    }

    return f;
}
项目:Vanilla-Injection    文件:JarClassLoader.java   
/**
 * @param jarFile
 *            Never null.
 * @param simpleName
 *            Used for logging. Never null.
 * @param jarFileParent
 *            Used to make simpleName for logging. Null for top level JAR.
 * @param fileDeleteOnExit
 *            Used only to delete temporary file on exit.
 *            Could be null if not required to delete on exit (top level JAR)
 * @throws JarClassLoaderException
 */
JarFileInfo(JarFile jarFile, String simpleName, JarFileInfo jarFileParent,
            ProtectionDomain pd, File fileDeleteOnExit)
{
    this.simpleName = (jarFileParent == null ? "" : jarFileParent.simpleName + "!") + simpleName;
    this.jarFile = jarFile;
    this.pd = pd;
    this.fileDeleteOnExit = fileDeleteOnExit;
    try {
        this.mf = jarFile.getManifest(); // 'null' if META-INF directory is missing
    } catch (IOException e) {
        // Ignore and create blank manifest
    }
    if (this.mf == null) {
        this.mf = new Manifest();
    }
}
项目:Reer    文件:DefaultManifest.java   
private static void addMainAttributesToJavaManifest(org.gradle.api.java.archives.Manifest gradleManifest, Manifest javaManifest) {
    for (Map.Entry<String, Object> entry : gradleManifest.getAttributes().entrySet()) {
        String mainAttributeName = entry.getKey();
        String mainAttributeValue = entry.getValue().toString();
        javaManifest.getMainAttributes().putValue(mainAttributeName, mainAttributeValue);
    }
}
项目:hadoop-oss    文件:TestJarFinder.java   
@Test
public void testExistingManifest() throws Exception {
  File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
                      TestJarFinder.class.getName() + "-testExistingManifest");
  delete(dir);
  dir.mkdirs();

  File metaInfDir = new File(dir, "META-INF");
  metaInfDir.mkdirs();
  File manifestFile = new File(metaInfDir, "MANIFEST.MF");
  Manifest manifest = new Manifest();
  OutputStream os = new FileOutputStream(manifestFile);
  manifest.write(os);
  os.close();

  File propsFile = new File(dir, "props.properties");
  Writer writer = new FileWriter(propsFile);
  new Properties().store(writer, "");
  writer.close();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  JarOutputStream zos = new JarOutputStream(baos);
  JarFinder.jarDir(dir, "", zos);
  JarInputStream jis =
    new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
  Assert.assertNotNull(jis.getManifest());
  jis.close();
}
项目:OpenJSharp    文件:Main.java   
/**
 * Generates the transitive closure of the Class-Path attribute for
 * the specified jar file.
 */
List<String> getJarPath(String jar) throws IOException {
    List<String> files = new ArrayList<String>();
    files.add(jar);
    jarPaths.add(jar);

    // take out the current path
    String path = jar.substring(0, Math.max(0, jar.lastIndexOf('/') + 1));

    // class path attribute will give us jar file name with
    // '/' as separators, so we need to change them to the
    // appropriate one before we open the jar file.
    JarFile rf = new JarFile(jar.replace('/', File.separatorChar));

    if (rf != null) {
        Manifest man = rf.getManifest();
        if (man != null) {
            Attributes attr = man.getMainAttributes();
            if (attr != null) {
                String value = attr.getValue(Attributes.Name.CLASS_PATH);
                if (value != null) {
                    StringTokenizer st = new StringTokenizer(value);
                    while (st.hasMoreTokens()) {
                        String ajar = st.nextToken();
                        if (!ajar.endsWith("/")) {  // it is a jar file
                            ajar = path.concat(ajar);
                            /* check on cyclic dependency */
                            if (! jarPaths.contains(ajar)) {
                                files.addAll(getJarPath(ajar));
                            }
                        }
                    }
                }
            }
        }
    }
    rf.close();
    return files;
}
项目:OpenJSharp    文件:ExtCheck.java   
URL[] getClassPath() throws IOException {
    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;
}
项目:OpenJSharp    文件:Main.java   
private void addCreatedBy(Manifest m) {
    Attributes global = m.getMainAttributes();
    if (global.getValue(new Attributes.Name("Created-By")) == null) {
        String javaVendor = System.getProperty("java.vendor");
        String jdkVersion = System.getProperty("java.version");
        global.put(new Attributes.Name("Created-By"), jdkVersion + " (" +
                    javaVendor + ")");
    }
}
项目:jdk8u-jdk    文件:Main.java   
/**
 * Generates the transitive closure of the Class-Path attribute for
 * the specified jar file.
 */
List<String> getJarPath(String jar) throws IOException {
    List<String> files = new ArrayList<String>();
    files.add(jar);
    jarPaths.add(jar);

    // take out the current path
    String path = jar.substring(0, Math.max(0, jar.lastIndexOf('/') + 1));

    // class path attribute will give us jar file name with
    // '/' as separators, so we need to change them to the
    // appropriate one before we open the jar file.
    JarFile rf = new JarFile(jar.replace('/', File.separatorChar));

    if (rf != null) {
        Manifest man = rf.getManifest();
        if (man != null) {
            Attributes attr = man.getMainAttributes();
            if (attr != null) {
                String value = attr.getValue(Attributes.Name.CLASS_PATH);
                if (value != null) {
                    StringTokenizer st = new StringTokenizer(value);
                    while (st.hasMoreTokens()) {
                        String ajar = st.nextToken();
                        if (!ajar.endsWith("/")) {  // it is a jar file
                            ajar = path.concat(ajar);
                            /* check on cyclic dependency */
                            if (! jarPaths.contains(ajar)) {
                                files.addAll(getJarPath(ajar));
                            }
                        }
                    }
                }
            }
        }
    }
    rf.close();
    return files;
}
项目:openjdk-jdk10    文件:JarFileSystem.java   
private boolean isMultiReleaseJar() throws IOException {
    try (InputStream is = newInputStream(getBytes("/META-INF/MANIFEST.MF"))) {
        String multiRelease = new Manifest(is).getMainAttributes()
                .getValue(Attributes.Name.MULTI_RELEASE);
        return "true".equalsIgnoreCase(multiRelease);
    } catch (NoSuchFileException x) {
        return false;
    }
}
项目:EM    文件:Dependencies.java   
public boolean isOSGiBundle (Artifact artifact) {
    try (JarFile jarFile = new JarFile(artifact.getFile()))  {
        Manifest manifest = jarFile.getManifest();
        if (manifest == null) return false;
        return manifest.getMainAttributes().getValue("Bundle-SymbolicName") != null;
    } catch (IOException e) {
        logger.warn("Failed to check if " + artifact.getFile() + " is OSGi bundle!", e);
    }
    return false;
}
项目:n4js    文件:JarRsrcLoader.java   
private static ManifestInfo getManifestInfo() throws IOException {
    Enumeration<?> resEnum;
    resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
    while (resEnum.hasMoreElements()) {
        try {
            URL url = (URL) resEnum.nextElement();
            InputStream is = url.openStream();
            if (is != null) {
                ManifestInfo result = new ManifestInfo();
                Manifest manifest = new Manifest(is);
                Attributes mainAttribs = manifest.getMainAttributes();
                result.rsrcMainClass = mainAttribs.getValue(JIJConstants.REDIRECTED_MAIN_CLASS_MANIFEST_NAME);
                String rsrcCP = mainAttribs.getValue(JIJConstants.REDIRECTED_CLASS_PATH_MANIFEST_NAME);
                if (rsrcCP == null)
                    rsrcCP = JIJConstants.DEFAULT_REDIRECTED_CLASSPATH;
                result.rsrcClassPath = splitSpaces(rsrcCP);
                if ((result.rsrcMainClass != null) && !result.rsrcMainClass.trim().equals("")) //$NON-NLS-1$
                    return result;
            }
        } catch (Exception e) {
            // Silently ignore wrong manifests on classpath?
        }
    }
    System.err.println(
            "Missing attributes for JarRsrcLoader in Manifest (" + JIJConstants.REDIRECTED_MAIN_CLASS_MANIFEST_NAME //$NON-NLS-1$
                    + ", " + JIJConstants.REDIRECTED_CLASS_PATH_MANIFEST_NAME + ")"); //$NON-NLS-1$ //$NON-NLS-2$
    return null;
}
项目:guava-mock    文件:ClassPathTest.java   
public void testGetClassPathFromManifest_relativeJar() throws IOException {
  File jarFile = new File("base/some.jar");
  // with/relative/directory is the Class-Path value in the mf file.
  Manifest manifest = manifestClasspath("with/relative.jar");
  assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest))
      .containsExactly(fullpath("base/with/relative.jar"));
}