Example usage for java.util.jar Manifest Manifest

List of usage examples for java.util.jar Manifest Manifest

Introduction

In this page you can find the example usage for java.util.jar Manifest Manifest.

Prototype

public Manifest(Manifest man) 

Source Link

Document

Constructs a new Manifest that is a copy of the specified Manifest.

Usage

From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginOSGiManifestTest.java

private void addHeaderToManifest(String header, String value) throws IOException {
    FileInputStream manifestInputStream = new FileInputStream(manifestFile);
    Manifest manifest = new Manifest(manifestInputStream);
    Attributes entries = manifest.getMainAttributes();
    entries.put(new Attributes.Name(header), value);

    FileOutputStream manifestOutputStream = new FileOutputStream(manifestFile, false);
    manifest.write(manifestOutputStream);
    manifestOutputStream.close();/*  w  w  w  .ja  v a  2  s.  c o m*/
    manifestInputStream.close();
}

From source file:edu.stanford.epad.common.plugins.impl.ClassFinderTestUtils.java

/**
 * //from w w  w.  j  a  v  a2s.c om
 * @param clazz Class
 * @return String
 */
public static String readJarManifestForClass(Class<?> clazz) {
    StringBuilder sb = new StringBuilder();
    InputStream manifestInputStream = null;

    try {

        String className = clazz.getSimpleName() + ".class";
        String classPath = clazz.getResource(className).toString();
        if (!classPath.startsWith("jar")) {
            // Class not from JAR
            return "Class " + className + " not from jar file.";
        }

        String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
        manifestInputStream = new URL(manifestPath).openStream();
        Manifest manifest = new Manifest(manifestInputStream);
        Attributes attr = manifest.getMainAttributes();
        // String value = attr.getValue("Manifest-Version");

        Set<Object> keys = attr.keySet();
        for (Object currKey : keys) {
            String currValue = attr.getValue(currKey.toString());
            if (currValue != null) {
                sb.append(currKey.toString()).append(" : ").append(currValue).append("\n");
            } else {
                sb.append(currKey.toString()).append(": Didn't have a value");
            }
        }
    } catch (Exception e) {
        logger.warning("Failed to read manifest for " + clazz.getSimpleName(), e);
    } finally {
        IOUtils.closeQuietly(manifestInputStream);
    }
    return sb.toString();
}

From source file:ca.uhn.fhir.rest.server.RestfulServer.java

public RestulfulServerConfiguration createConfiguration() {
    RestulfulServerConfiguration result = new RestulfulServerConfiguration();
    result.setResourceBindings(getResourceBindings());
    result.setServerBindings(getServerBindings());
    result.setImplementationDescription(getImplementationDescription());
    result.setServerVersion(getServerVersion());
    result.setServerName(getServerName());
    result.setFhirContext(getFhirContext());
    result.setServerAddressStrategy(myServerAddressStrategy);
    InputStream inputStream = null;
    try {//from   www .  j  a  v  a 2  s  .c  o m
        inputStream = getClass().getResourceAsStream("/META-INF/MANIFEST.MF");
        if (inputStream != null) {
            Manifest manifest = new Manifest(inputStream);
            result.setConformanceDate(manifest.getMainAttributes().getValue("Build-Time"));
        }
    } catch (IOException e) {
        // fall through
    } finally {
        if (inputStream != null) {
            IOUtils.closeQuietly(inputStream);
        }
    }
    return result;
}

From source file:org.gradle.api.java.archives.internal.DefaultManifest.java

private void read(Object manifestPath) {
    File manifestFile = fileResolver.resolve(manifestPath);
    try {//from  ww w  . j  a  va2  s . c o m
        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);
    }
}

From source file:com.github.sampov2.OneJarMojo.java

private Manifest prepareManifest() throws IOException {
    // Copy the template's boot-manifest.mf file
    ZipInputStream zipIS = openOnejarTemplateArchive();
    Manifest manifest = new Manifest(getFileBytes(zipIS, "boot-manifest.mf"));
    IOUtils.closeQuietly(zipIS);//  w  w  w . j ava 2  s.co m

    Attributes mainAttributes = manifest.getMainAttributes();
    // first add the custom specified entries
    addExplicitManifestEntries(mainAttributes);

    // If the client has specified an implementationVersion argument, add it also
    // (It's required and defaulted, so this always executes...)
    //
    // TODO: The format of this manifest entry is not "hard and fast".  Some specs call for "implementationVersion",
    // some for "implemenation-version", and others use various capitalizations of these two.  It's likely that a
    // better solution then this "brute-force" bit here is to allow clients to configure these entries from the
    // Maven POM.
    setRequired(mainAttributes, new AttributeEntry(MF_REQUIRED_IMPL_VERSION, implementationVersion),
            MF_REQUIRED_IMPL_VERSION);

    // If the client has specified a splashScreen argument, add the proper entry to the manifest
    setOptional(splashScreen, mainAttributes, new AttributeEntry(MF_OPTION_SPLASH_SCREEN_IMAGE, splashScreen),
            MF_OPTION_SPLASH_SCREEN_IMAGE);

    // If the client has specified a mainClass argument, add the proper entry to the manifest
    // to be backwards compatible, add mainclass as simple option when not already set in manifestEntries
    setOptional(mainClass, mainAttributes, new AttributeEntry(MF_OPTION_MAIN_CLASS, mainClass),
            MF_OPTION_MAIN_CLASS);

    return manifest;
}

From source file:jenkins.security.ClassFilterImpl.java

private boolean isLocationWhitelisted(String _loc) {
    return codeSourceCache.computeIfAbsent(_loc, loc -> {
        if (loc.equals(JENKINS_LOC)) {
            LOGGER.log(Level.FINE, "{0} seems to be the location of Jenkins core, OK", loc);
            return true;
        }//w w  w. ja va  2s. c om
        if (loc.equals(REMOTING_LOC)) {
            LOGGER.log(Level.FINE, "{0} seems to be the location of Remoting, OK", loc);
            return true;
        }
        if (loc.matches("file:/.+[.]jar")) {
            try (JarFile jf = new JarFile(new File(new URI(loc)), false)) {
                Manifest mf = jf.getManifest();
                if (mf != null) {
                    if (isPluginManifest(mf)) {
                        LOGGER.log(Level.FINE, "{0} seems to be a Jenkins plugin, OK", loc);
                        return true;
                    } else {
                        LOGGER.log(Level.FINE, "{0} does not look like a Jenkins plugin", loc);
                    }
                } else {
                    LOGGER.log(Level.FINE, "ignoring {0} with no manifest", loc);
                }
            } catch (Exception x) {
                LOGGER.log(Level.WARNING, "problem checking " + loc, x);
            }
        }
        Matcher m = CLASSES_JAR.matcher(loc);
        if (m.matches()) {
            // Cf. ClassicPluginStrategy.createClassJarFromWebInfClasses: handle legacy plugin format with unpacked WEB-INF/classes/
            try {
                File manifestFile = new File(new URI(m.group(1) + "META-INF/MANIFEST.MF"));
                if (manifestFile.isFile()) {
                    try (InputStream is = new FileInputStream(manifestFile)) {
                        if (isPluginManifest(new Manifest(is))) {
                            LOGGER.log(Level.FINE, "{0} looks like a Jenkins plugin based on {1}, OK",
                                    new Object[] { loc, manifestFile });
                            return true;
                        } else {
                            LOGGER.log(Level.FINE, "{0} does not look like a Jenkins plugin", manifestFile);
                        }
                    }
                } else {
                    LOGGER.log(Level.FINE, "{0} has no matching {1}", new Object[] { loc, manifestFile });
                }
            } catch (Exception x) {
                LOGGER.log(Level.WARNING, "problem checking " + loc, x);
            }
        }
        if (loc.endsWith("/target/classes/") || loc.matches(".+/build/classes/[^/]+/main/")) {
            LOGGER.log(Level.FINE, "{0} seems to be current plugin classes, OK", loc);
            return true;
        }
        if (Main.isUnitTest) {
            if (loc.endsWith("/target/test-classes/") || loc.endsWith("-tests.jar")
                    || loc.matches(".+/build/classes/[^/]+/test/")) {
                LOGGER.log(Level.FINE, "{0} seems to be test classes, OK", loc);
                return true;
            }
            if (loc.matches(".+/jenkins-test-harness-.+[.]jar")) {
                LOGGER.log(Level.FINE, "{0} seems to be jenkins-test-harness, OK", loc);
                return true;
            }
        }
        LOGGER.log(Level.FINE, "{0} is not recognized; rejecting", loc);
        return false;
    });
}

From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4JRuntimesManager.java

public INeo4jRuntime getRuntimeFromLocation(IPath path) {
    INeo4jRuntime runtime = null;/* ww w  .j  a  v a  2s  .  c o m*/
    File manifestMF = path.append(META_INF).append(MANIFEST_MF).toFile();
    if (manifestMF.exists()) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(manifestMF);
            Manifest manifest = new Manifest(stream);
            String id = manifest.getMainAttributes().getValue(BUNDLE_SYMBOLIC_NAME);
            String version = manifest.getMainAttributes().getValue(BUNDLE_VERSION);
            runtime = new Neo4jRuntime(version, id, path);
        } catch (Exception e) {
            Logger.log(Logger.SEVERITY_ERROR, e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }
    return runtime;
}

From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java

private static Pair<Artifact, byte[]> extractPacked(JarFile jar, ModList modlist, File... modDirs)
        throws IOException {
    Attributes attrs;//from   ww w .j  a v a2 s.  c o m
    if (jar.getManifest() == null)
        return null;

    JarEntry manifest_entry = jar.getJarEntry(JarFile.MANIFEST_NAME);
    if (manifest_entry == null)
        manifest_entry = jar.stream()
                .filter(e -> JarFile.MANIFEST_NAME.equals(e.getName().toUpperCase(Locale.ENGLISH))).findFirst()
                .get(); //We know that getManifest returned non-null so we know there is *some* entry that matches the manifest file. So we dont need to empty check.

    attrs = jar.getManifest().getMainAttributes();

    String modSide = attrs.getValue(LibraryManager.MODSIDE);
    if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide))
        return null;

    if (attrs.containsKey(MODCONTAINSDEPS)) {
        for (String dep : attrs.getValue(MODCONTAINSDEPS).split(" ")) {
            if (!dep.endsWith(".jar")) {
                FMLLog.log.error("Contained Dep is not a jar file: {}", dep);
                throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep);
            }

            if (jar.getJarEntry(dep) == null && jar.getJarEntry("META-INF/libraries/" + dep) != null)
                dep = "META-INF/libraries/" + dep;

            JarEntry depEntry = jar.getJarEntry(dep);
            if (depEntry == null) {
                FMLLog.log.error("Contained Dep is not in the jar: {}", dep);
                throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep);
            }

            String depEndName = new File(dep).getName(); // extract last part of name
            if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) {
                FMLLog.log.error("Skipping dep at request: {}", dep);
                continue;
            }

            Attributes meta = null;
            byte[] data = null;
            byte[] manifest_data = null;

            JarEntry metaEntry = jar.getJarEntry(dep + ".meta");
            if (metaEntry != null) {
                manifest_data = readAll(jar.getInputStream(metaEntry));
                meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
            } else {
                data = readAll(jar.getInputStream(depEntry));
                try (ZipInputStream zi = new ZipInputStream(new ByteArrayInputStream(data))) //We use zip input stream directly, as the current Oracle implementation of JarInputStream only works when the manifest is the First/Second entry in the jar...
                {
                    ZipEntry ze = null;
                    while ((ze = zi.getNextEntry()) != null) {
                        if (ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) {
                            manifest_data = readAll(zi);
                            meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
                            break;
                        }
                    }
                }
            }

            if (meta == null || !meta.containsKey(MAVEN_ARTIFACT)) //Ugh I really don't want to do backwards compatibility here, I want to force modders to provide information... TODO: Remove in 1.13?
            {
                boolean found = false;
                for (File dir : modDirs) {
                    File target = new File(dir, depEndName);
                    if (target.exists()) {
                        FMLLog.log.debug("Found existing ContainDep extracted to {}, skipping extraction",
                                target.getCanonicalPath());
                        found = true;
                    }
                }
                if (!found) {
                    File target = new File(modDirs[0], depEndName);
                    FMLLog.log.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(),
                            target.getCanonicalPath());
                    try {
                        Files.createParentDirs(target);
                        try (FileOutputStream out = new FileOutputStream(target);
                                InputStream in = data == null ? jar.getInputStream(depEntry)
                                        : new ByteArrayInputStream(data)) {
                            ByteStreams.copy(in, out);
                        }
                        FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(),
                                target.getCanonicalPath());
                        extractPacked(target, modlist, modDirs);
                    } catch (IOException e) {
                        FMLLog.log.error("An error occurred extracting dependency", e);
                    }
                }
            } else {
                try {
                    Artifact artifact = readArtifact(modlist.getRepository(), meta);
                    File target = artifact.getFile();
                    if (target.exists()) {
                        FMLLog.log.debug(
                                "Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction",
                                dep, artifact.toString(), target.getCanonicalPath(), jar.getName());
                        if (!ENABLE_AUTO_MOD_MOVEMENT) {
                            Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down.
                            if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
                            {
                                modlist.add(artifact);
                            }
                        }
                    } else {
                        FMLLog.log.debug("Extracting ContainedDep {}({}) from {} to {}", dep,
                                artifact.toString(), jar.getName(), target.getCanonicalPath());
                        Files.createParentDirs(target);
                        try (FileOutputStream out = new FileOutputStream(target);
                                InputStream in = data == null ? jar.getInputStream(depEntry)
                                        : new ByteArrayInputStream(data)) {
                            ByteStreams.copy(in, out);
                        }
                        FMLLog.log.debug("Extracted ContainedDep {}({}) from {} to {}", dep,
                                artifact.toString(), jar.getName(), target.getCanonicalPath());

                        if (artifact.isSnapshot()) {
                            SnapshotJson json = SnapshotJson.create(artifact.getSnapshotMeta());
                            json.add(new SnapshotJson.Entry(artifact.getTimestamp(), meta.getValue(MD5)));
                            json.write(artifact.getSnapshotMeta());
                        }

                        if (!DISABLE_EXTERNAL_MANIFEST) {
                            File meta_target = new File(target.getAbsolutePath() + ".meta");
                            Files.write(manifest_data, meta_target);
                        }
                        Pair<?, ?> child = extractPacked(target, modlist, modDirs);
                        if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
                        {
                            modlist.add(artifact);
                        }
                    }
                } catch (NumberFormatException nfe) {
                    FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage(
                            "An error occurred extracting dependency. Invalid Timestamp: {}",
                            meta.getValue(TIMESTAMP)), nfe);
                } catch (IOException e) {
                    FMLLog.log.error("An error occurred extracting dependency", e);
                }
            }
        }
    }

    if (attrs.containsKey(MAVEN_ARTIFACT)) {
        Artifact artifact = readArtifact(modlist.getRepository(), attrs);
        modlist.add(artifact);
        return Pair.of(artifact, readAll(jar.getInputStream(manifest_entry)));
    }
    return null;
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

@Test
public void shouldMergeManifestsIfAsked() throws IOException {
    Manifest fromJar = createManifestWithExampleSection(ImmutableMap.of("Not-Seen", "ever"));
    Manifest fromUser = createManifestWithExampleSection(ImmutableMap.of("cake", "cheese"));

    Manifest seenManifest = jarDirectoryAndReadManifest(fromJar, fromUser, true);

    Manifest expectedManifest = new Manifest(fromJar);
    Attributes attrs = new Attributes();
    attrs.putValue("Not-Seen", "ever");
    attrs.putValue("cake", "cheese");
    expectedManifest.getEntries().put("example", attrs);
    assertEquals(expectedManifest.getEntries(), seenManifest.getEntries());
}

From source file:com.buglabs.bug.ws.program.ProgramServlet.java

/**
 * Code from forum board for creating a Jar.
 * /* w  ww.  j ava 2s.  c  o  m*/
 * @param archiveFile
 * @param tobeJared
 * @param rootDir
 * @throws IOException
 */
protected void createJarArchive(File archiveFile, File[] tobeJared, File rootDir) throws IOException {

    byte buffer[] = new byte[BUFFER_SIZE];
    // Open archive file
    FileOutputStream stream = new FileOutputStream(archiveFile);
    JarOutputStream out = new JarOutputStream(stream, new Manifest(new FileInputStream(
            rootDir.getAbsolutePath() + File.separator + "META-INF" + File.separator + MANIFEST_FILENAME)));

    for (int i = 0; i < tobeJared.length; i++) {
        if (tobeJared[i] == null || !tobeJared[i].exists() || tobeJared[i].isDirectory())
            continue; // Just in case...

        String relPath = getRelPath(rootDir.getAbsolutePath(), tobeJared[i].getAbsolutePath());

        // Add archive entry
        JarEntry jarAdd = new JarEntry(relPath);
        jarAdd.setTime(tobeJared[i].lastModified());
        out.putNextEntry(jarAdd);
        // Write file to archive
        FileInputStream in = new FileInputStream(tobeJared[i]);
        while (true) {
            int nRead = in.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            out.write(buffer, 0, nRead);
        }
        in.close();
    }

    out.close();
    stream.close();

}