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() 

Source Link

Document

Constructs a new, empty Manifest.

Usage

From source file:org.cloudifysource.dsl.internal.packaging.Packager.java

private static void createManifestFile(final File destPuFolder) throws IOException {
    final File manifestFolder = new File(destPuFolder, "META-INF");
    final File manifestFile = new File(manifestFolder, "MANIFEST.MF");

    final Manifest manifest = new Manifest();

    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().putValue("Class-Path",
            "lib/platform/cloudify/dsl.jar lib/platform/usm/usm.jar "
                    // added support for @grab annotation in groovy file - requires ivy and groovy in same classloader
                    + "tools/groovy/embeddable/groovy-all-1.8.6.jar tools/groovy/lib/ivy-2.2.0.jar ");

    OutputStream out = null;/*  w w  w .  j a  va 2  s. c o  m*/

    try {
        out = new BufferedOutputStream(new FileOutputStream(manifestFile));
        manifest.write(out);

    } finally {
        if (out != null) {

            try {
                out.close();
            } catch (final IOException e) {
                logger.log(Level.SEVERE, "Failed to close file: " + manifestFile, e);
            }

        }
    }

}

From source file:rubah.tools.UpdateClassGenerator.java

public void generateConversionJar(File outJar) throws IOException {

    FileOutputStream fos = new FileOutputStream(outJar);
    JarOutputStream jos = new JarOutputStream(fos, new Manifest());

    this.generateConversionClasses(jos, this.v0, this.preffixes.get(this.v1.getNamespace()));
    this.generateConversionClasses(jos, this.v1, "");

    jos.close();/*from  w  ww  .  java 2 s. c  om*/
    fos.close();
}

From source file:com.hellblazer.process.JavaProcessTest.java

protected void copyTestJarFile() throws Exception {
    String classFileName = HelloWorld.class.getCanonicalName().replace('.', '/') + ".class";
    URL classFile = getClass().getResource("/" + classFileName);
    assertNotNull(classFile);// w ww. jav a 2s  . c o m

    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.putValue("Manifest-Version", "1.0");
    attributes.putValue("Main-Class", HelloWorld.class.getCanonicalName());

    FileOutputStream fos = new FileOutputStream(new File(testDir, TEST_JAR));
    JarOutputStream jar = new JarOutputStream(fos, manifest);
    JarEntry entry = new JarEntry(classFileName);
    jar.putNextEntry(entry);
    InputStream in = classFile.openStream();
    byte[] buffer = new byte[1024];
    for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
        jar.write(buffer, 0, read);
    }
    in.close();
    jar.closeEntry();
    jar.close();
}

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

private Manifest createManifestWithExampleSection(Map<String, String> attributes) {
    Manifest manifest = new Manifest();
    Attributes attrs = new Attributes();
    for (Map.Entry<String, String> stringStringEntry : attributes.entrySet()) {
        attrs.put(new Attributes.Name(stringStringEntry.getKey()), stringStringEntry.getValue());
    }// www .  j a  v  a2 s.  c  o  m
    manifest.getEntries().put("example", attrs);
    return manifest;
}

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

public void initializeRuntimeMetadata(AbstractNeo4jRuntimeInstaller installer, IPath path) {
    File dirFile = path.toFile();
    File manifestFile = path.append(META_INF).append(MANIFEST_MF).toFile();
    FileOutputStream outputStream = null;
    try {//from   w ww .j  a v a2 s . c  o  m
        FileUtils.forceMkdir(manifestFile.getParentFile());
        outputStream = new FileOutputStream(manifestFile);
        Manifest manifest = new Manifest();
        Attributes atts = manifest.getMainAttributes();
        atts.put(Attributes.Name.MANIFEST_VERSION, "1.0");
        atts.putValue(BUNDLE_MANIFEST_VERSION, "2");
        atts.putValue(BUNDLE_NAME, installer.getName());
        atts.putValue(BUNDLE_SYMBOLIC_NAME, installer.getId());
        atts.putValue(BUNDLE_VERSION, installer.getVersion());
        atts.putValue(BUNDLE_CLASS_PATH, buildJarFilesList(dirFile));
        atts.putValue(EXPORT_PACKAGE, buildPackagesList(dirFile));
        manifest.write(outputStream);
        load();
    } catch (Exception e) {
        Logger.log(Logger.SEVERITY_ERROR, e);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:org.apache.sysml.utils.lite.BuildLite.java

/**
 * Build a lite jar based on the consolidated class names.
 * //from  w  w w .  j  a v  a2  s  .co  m
 * @param consolidateClassPathNames
 *            the consolidated class names
 * @throws IOException
 *             if an IOException occurs
 */
private static void createJarFromConsolidatedClassPathNames(Set<String> consolidateClassPathNames)
        throws IOException {
    System.out.println("\nCreating " + liteJarLocation + " file");
    ClassLoader cl = BuildLite.class.getClassLoader();

    Manifest mf = new Manifest();
    Attributes attr = mf.getMainAttributes();
    attr.putValue("" + Attributes.Name.MANIFEST_VERSION, "1.0");

    File file = new File(liteJarLocation);
    try (FileOutputStream fos = new FileOutputStream(file);
            JarOutputStream jos = new JarOutputStream(fos, mf)) {
        int numFilesWritten = 0;
        for (String classPathName : consolidateClassPathNames) {
            writeMessage(classPathName, ++numFilesWritten);
            InputStream is = cl.getResourceAsStream(classPathName);
            byte[] bytes = IOUtils.toByteArray(is);

            JarEntry je = new JarEntry(classPathName);
            jos.putNextEntry(je);
            jos.write(bytes);
        }

        writeIdentifierFileToLiteJar(jos, ++numFilesWritten);
        writeAdditionalResourcesToJar(jos, numFilesWritten);
    }

}

From source file:org.wso2.carbon.server.util.Utils.java

/**
 * Create an OSGi bundle out of a JAR file
 *
 * @param jarFile         The jarfile to be bundled
 * @param targetDir       The directory into which the created OSGi bundle needs to be placed into.
 * @param mf              The bundle manifest file
 * @param extensionPrefix Prefix, if any, for the bundle
 * @throws java.io.IOException If an error occurs while reading the jar or creating the bundle
 *//*from ww w.  j a  v  a  2 s. c om*/
public static void createBundle(File jarFile, File targetDir, Manifest mf, String extensionPrefix)
        throws IOException {
    if (mf == null) {
        mf = new Manifest();
    }
    String exportedPackages = Utils.parseJar(jarFile);

    String fileName = jarFile.getName();
    fileName = fileName.replaceAll("-", "_");
    if (fileName.endsWith(".jar")) {
        fileName = fileName.substring(0, fileName.length() - 4);
    }
    String symbolicName = extensionPrefix + fileName;
    String pluginName = extensionPrefix + fileName + "_1.0.0.jar";
    File extensionBundle = new File(targetDir, pluginName);

    Attributes attribs = mf.getMainAttributes();
    attribs.putValue(LauncherConstants.MANIFEST_VERSION, "1.0");
    attribs.putValue(LauncherConstants.BUNDLE_MANIFEST_VERSION, "2");
    attribs.putValue(LauncherConstants.BUNDLE_NAME, fileName);
    attribs.putValue(LauncherConstants.BUNDLE_SYMBOLIC_NAME, symbolicName);
    attribs.putValue(LauncherConstants.BUNDLE_VERSION, "1.0.0");
    attribs.putValue(LauncherConstants.EXPORT_PACKAGE, exportedPackages);
    attribs.putValue(LauncherConstants.BUNDLE_CLASSPATH, ".," + jarFile.getName());

    Utils.createBundle(jarFile, extensionBundle, mf);
}

From source file:com.threerings.media.tile.bundle.tools.TileSetBundler.java

/**
 * Create a tileset bundle jar file./*from ww  w.j  a v a  2  s.c o  m*/
 *
 * @param target the tileset bundle file that will be created.
 * @param bundle contains the tilesets we'd like to save out to the bundle.
 * @param improv the image provider.
 * @param imageBase the base directory for getting images for non-ObjectTileSet tilesets.
 * @param keepOriginalPngs bundle up the original PNGs as PNGs instead of converting to the
 * FastImageIO raw format
 */
public static boolean createBundleJar(File target, TileSetBundle bundle, ImageProvider improv, String imageBase,
        boolean keepOriginalPngs, boolean uncompressed) throws IOException {
    // now we have to create the actual bundle file
    FileOutputStream fout = new FileOutputStream(target);
    Manifest manifest = new Manifest();
    JarOutputStream jar = new JarOutputStream(fout, manifest);
    jar.setLevel(uncompressed ? Deflater.NO_COMPRESSION : Deflater.BEST_COMPRESSION);

    try {
        // write all of the image files to the bundle, converting the
        // tilesets to trimmed tilesets in the process
        Iterator<Integer> iditer = bundle.enumerateTileSetIds();

        // Store off the updated TileSets in a separate Map so we can wait to change the
        // bundle till we're done iterating.
        HashIntMap<TileSet> toUpdate = new HashIntMap<TileSet>();
        while (iditer.hasNext()) {
            int tileSetId = iditer.next().intValue();
            TileSet set = bundle.getTileSet(tileSetId);
            String imagePath = set.getImagePath();

            // sanity checks
            if (imagePath == null) {
                log.warning("Tileset contains no image path " + "[set=" + set + "]. It ain't gonna work.");
                continue;
            }

            // if this is an object tileset, trim it
            if (!keepOriginalPngs && (set instanceof ObjectTileSet)) {
                // set the tileset up with an image provider; we
                // need to do this so that we can trim it!
                set.setImageProvider(improv);

                // we're going to trim it, so adjust the path
                imagePath = adjustImagePath(imagePath);
                jar.putNextEntry(new JarEntry(imagePath));

                try {
                    // create a trimmed object tileset, which will
                    // write the trimmed tileset image to the jar
                    // output stream
                    TrimmedObjectTileSet tset = TrimmedObjectTileSet.trimObjectTileSet((ObjectTileSet) set,
                            jar);
                    tset.setImagePath(imagePath);
                    // replace the original set with the trimmed
                    // tileset in the tileset bundle
                    toUpdate.put(tileSetId, tset);

                } catch (Exception e) {
                    e.printStackTrace(System.err);

                    String msg = "Error adding tileset to bundle " + imagePath + ", " + set.getName() + ": "
                            + e;
                    throw (IOException) new IOException(msg).initCause(e);
                }

            } else {
                // read the image file and convert it to our custom
                // format in the bundle
                File ifile = new File(imageBase, imagePath);
                try {
                    BufferedImage image = ImageIO.read(ifile);
                    if (!keepOriginalPngs && FastImageIO.canWrite(image)) {
                        imagePath = adjustImagePath(imagePath);
                        jar.putNextEntry(new JarEntry(imagePath));
                        set.setImagePath(imagePath);
                        FastImageIO.write(image, jar);
                    } else {
                        jar.putNextEntry(new JarEntry(imagePath));
                        FileInputStream imgin = new FileInputStream(ifile);
                        StreamUtil.copy(imgin, jar);
                    }
                } catch (Exception e) {
                    String msg = "Failure bundling image " + ifile + ": " + e;
                    throw (IOException) new IOException(msg).initCause(e);
                }
            }
        }
        bundle.putAll(toUpdate);

        // now write a serialized representation of the tileset bundle
        // object to the bundle jar file
        JarEntry entry = new JarEntry(BundleUtil.METADATA_PATH);
        jar.putNextEntry(entry);
        ObjectOutputStream oout = new ObjectOutputStream(jar);
        oout.writeObject(bundle);
        oout.flush();

        // finally close up the jar file and call ourself done
        jar.close();

        return true;

    } catch (Exception e) {
        // remove the incomplete jar file and rethrow the exception
        jar.close();
        if (!target.delete()) {
            log.warning("Failed to close botched bundle '" + target + "'.");
        }
        String errmsg = "Failed to create bundle " + target + ": " + e;
        throw (IOException) new IOException(errmsg).initCause(e);
    }
}

From source file:org.apache.hadoop.hbase.TestClassFinder.java

/**
 * Makes a jar out of some class files. Unfortunately it's very tedious.
 * @param filesInJar Files created via compileTestClass.
 * @return path to the resulting jar file.
 *//*from  w  w  w  . j a  v  a 2s.co  m*/
private static String packageAndLoadJar(FileAndPath... filesInJar) throws Exception {
    // First, write the bogus jar file.
    String path = basePath + "jar" + jarCounter.incrementAndGet() + ".jar";
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    FileOutputStream fos = new FileOutputStream(path);
    JarOutputStream jarOutputStream = new JarOutputStream(fos, manifest);
    // Directory entries for all packages have to be added explicitly for
    // resources to be findable via ClassLoader. Directory entries must end
    // with "/"; the initial one is expected to, also.
    Set<String> pathsInJar = new HashSet<String>();
    for (FileAndPath fileAndPath : filesInJar) {
        String pathToAdd = fileAndPath.path;
        while (pathsInJar.add(pathToAdd)) {
            int ix = pathToAdd.lastIndexOf('/', pathToAdd.length() - 2);
            if (ix < 0) {
                break;
            }
            pathToAdd = pathToAdd.substring(0, ix);
        }
    }
    for (String pathInJar : pathsInJar) {
        jarOutputStream.putNextEntry(new JarEntry(pathInJar));
        jarOutputStream.closeEntry();
    }
    for (FileAndPath fileAndPath : filesInJar) {
        File file = fileAndPath.file;
        jarOutputStream.putNextEntry(new JarEntry(fileAndPath.path + file.getName()));
        byte[] allBytes = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(allBytes);
        fis.close();
        jarOutputStream.write(allBytes);
        jarOutputStream.closeEntry();
    }
    jarOutputStream.close();
    fos.close();

    // Add the file to classpath.
    File jarFile = new File(path);
    assertTrue(jarFile.exists());
    URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
    method.setAccessible(true);
    method.invoke(urlClassLoader, new Object[] { jarFile.toURI().toURL() });
    return jarFile.getAbsolutePath();
}

From source file:co.cask.cdap.internal.app.services.http.AppFabricTestBase.java

protected HttpResponse addAppArtifact(Id.Artifact artifactId, Class<?> cls) throws Exception {

    Location appJar = AppJarHelper.createDeploymentJar(locationFactory, cls, new Manifest());

    try (InputStream artifactInputStream = appJar.getInputStream()) {
        return addArtifact(artifactId, artifactInputStream, null);
    } finally {//from w w  w  . j a va 2s .  co m
        appJar.delete();
    }
}