Example usage for java.util.jar JarOutputStream JarOutputStream

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

Introduction

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

Prototype

public JarOutputStream(OutputStream out, Manifest man) throws IOException 

Source Link

Document

Creates a new JarOutputStream with the specified Manifest.

Usage

From source file:org.eclipse.equinox.servletbridge.FrameworkLauncher.java

/**
 * deployExtensionBundle will generate the Servletbridge extensionbundle if it is not already present in the platform's
 * plugin directory. By default it exports "org.eclipse.equinox.servletbridge" and a versioned export of the Servlet API.
 * Additional exports can be added by using the "extendedFrameworkExports" initial-param in the ServletConfig
 *//*from   ww  w  .ja  v  a 2  s  . com*/
private void deployExtensionBundle(File plugins) {
    File extensionBundle = new File(plugins, "org.eclipse.equinox.servletbridge.extensionbundle_1.0.0.jar"); //$NON-NLS-1$
    File extensionBundleDir = new File(plugins, "org.eclipse.equinox.servletbridge.extensionbundle_1.0.0"); //$NON-NLS-1$
    if (Boolean.valueOf(config.getInitParameter(CONFIG_OVERRIDE_AND_REPLACE_EXTENSION_BUNDLE)).booleanValue()) {
        extensionBundle.delete();
        deleteDirectory(extensionBundleDir);
    } else if (extensionBundle.exists() || extensionBundleDir.isDirectory())
        return;

    Manifest mf = new Manifest();
    Attributes attribs = mf.getMainAttributes();
    attribs.putValue(MANIFEST_VERSION, "1.0"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_MANIFEST_VERSION, "2"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_NAME, "Servletbridge Extension Bundle"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_SYMBOLIC_NAME, "org.eclipse.equinox.servletbridge.extensionbundle"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_VERSION, "1.0.0"); //$NON-NLS-1$
    attribs.putValue(FRAGMENT_HOST, "system.bundle; extension:=framework"); //$NON-NLS-1$

    String servletVersion = context.getMajorVersion() + "." + context.getMinorVersion(); //$NON-NLS-1$
    String packageExports = "org.eclipse.equinox.servletbridge; version=1.0" + //$NON-NLS-1$
            ", javax.servlet; version=" + servletVersion + //$NON-NLS-1$
            ", javax.servlet.http; version=" + servletVersion + //$NON-NLS-1$
            ", javax.servlet.resources; version=" + servletVersion; //$NON-NLS-1$

    String extendedExports = config.getInitParameter(CONFIG_EXTENDED_FRAMEWORK_EXPORTS);
    if (extendedExports != null && extendedExports.trim().length() != 0)
        packageExports += ", " + extendedExports; //$NON-NLS-1$

    attribs.putValue(EXPORT_PACKAGE, packageExports);

    try {
        JarOutputStream jos = null;
        try {
            jos = new JarOutputStream(new FileOutputStream(extensionBundle), mf);
            jos.finish();
        } finally {
            if (jos != null)
                jos.close();
        }
    } catch (IOException e) {
        context.log("Error generating extension bundle", e); //$NON-NLS-1$
    }
}

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);//from  www  .j a va2 s  .  c om

    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:org.eclipse.smarthome.test.SyntheticBundleInstaller.java

private static byte[] createSyntheticBundle(Bundle bundle, String bundlePath, String bundleName,
        Set<String> extensionsToInclude) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Manifest manifest = getManifest(bundle, bundlePath);
    JarOutputStream jarOutputStream = manifest != null ? new JarOutputStream(outputStream, manifest)
            : new JarOutputStream(outputStream);

    List<String> files = collectFilesFrom(bundle, bundlePath, bundleName, extensionsToInclude);
    for (String file : files) {
        addFileToArchive(bundle, bundlePath, file, jarOutputStream);
    }/* w  w w.j  av a 2s.  c om*/
    jarOutputStream.close();
    return outputStream.toByteArray();
}

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

private Manifest jarDirectoryAndReadManifest(Manifest fromJar, Manifest fromUser, boolean mergeEntries)
        throws IOException {
    // Create a jar with a manifest we'd expect to see merged.
    Path originalJar = folder.newFile("unexpected.jar");
    JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(originalJar), fromJar);
    ignored.close();/*w  w  w .  j  a  v  a2 s. c o m*/

    // Now create the actual manifest
    Path manifestFile = folder.newFile("actual_manfiest.mf");
    try (OutputStream os = Files.newOutputStream(manifestFile)) {
        fromUser.write(os);
    }

    Path tmp = folder.newFolder();
    Path output = tmp.resolve("example.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output,
            ImmutableSortedSet.of(originalJar), /* main class */ null, manifestFile, mergeEntries,
            /* blacklist */ ImmutableSet.<String>of());
    ExecutionContext context = TestExecutionContext.newInstance();
    step.execute(context);

    // Now verify that the created manifest matches the expected one.
    try (JarInputStream jis = new JarInputStream(Files.newInputStream(output))) {
        return jis.getManifest();
    }
}

From source file:org.apache.sling.osgi.obr.Repository.java

File spoolModified(InputStream ins) throws IOException {
    JarInputStream jis = new JarInputStream(ins);

    // immediately handle the manifest
    JarOutputStream jos;//  w  w  w .  ja v  a  2 s . c  om
    Manifest manifest = jis.getManifest();
    if (manifest == null) {
        throw new IOException("Missing Manifest !");
    }

    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
    if (symbolicName == null || symbolicName.length() == 0) {
        throw new IOException("Missing Symbolic Name in Manifest !");
    }

    String version = manifest.getMainAttributes().getValue("Bundle-Version");
    Version v = Version.parseVersion(version);
    if (v.getQualifier().indexOf("SNAPSHOT") >= 0) {
        String tStamp;
        synchronized (DATE_FORMAT) {
            tStamp = DATE_FORMAT.format(new Date());
        }
        version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "."
                + v.getQualifier().replaceAll("SNAPSHOT", tStamp);
        manifest.getMainAttributes().putValue("Bundle-Version", version);
    }

    File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar");
    OutputStream out = null;
    try {
        out = new FileOutputStream(bundle);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                spool(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();

    } finally {
        IOUtils.closeQuietly(out);
    }

    return bundle;
}

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

/**
 * Build a lite jar based on the consolidated class names.
 * /*  w  w w. j a v a 2 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:com.threerings.media.tile.bundle.tools.TileSetBundler.java

/**
 * Create a tileset bundle jar file./*from   ww  w .  j  av  a  2 s .  co 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 a2s. c  om
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:org.apache.sling.maven.slingstart.PreparePackageMojo.java

private File createSubsystemBaseFile(Feature feature, AtomicInteger startLevelHolder)
        throws MojoExecutionException {
    File subsystemFile = new File(getTmpDir(), feature.getName() + ".subsystem-base");
    if (subsystemFile.exists()) {
        // This subsystem has already been created
        // TODO is there a better way to avoid calling this multiple times?
        return null;
    }/*ww w . ja  v  a2s  . c  o m*/

    startLevelHolder.set(-1);

    // The runmodes information has to be the first item in the archive so that we always have it available when the
    // archive is being processed. For this reason a Jar file is used here as it's guaranteed to store the manifest
    // first.
    Manifest runModesManifest = getRunModesManifest(feature);

    getLog().info("Creating subsystem base file: " + subsystemFile.getName());
    subsystemFile.getParentFile().mkdirs();

    try (JarOutputStream os = new JarOutputStream(new FileOutputStream(subsystemFile), runModesManifest)) {
        Map<String, Integer> bsnStartOrderMap = new HashMap<>();

        for (RunMode rm : feature.getRunModes()) {
            for (ArtifactGroup ag : rm.getArtifactGroups()) {
                int startOrder = ag.getStartLevel(); // For subsystems the start level on the artifact group is used as start order.

                for (org.apache.sling.provisioning.model.Artifact a : ag) {
                    Artifact artifact = ModelUtils.getArtifact(this.project, this.mavenSession,
                            this.artifactHandlerManager, this.resolver, a.getGroupId(), a.getArtifactId(),
                            a.getVersion(), a.getType(), a.getClassifier());
                    File artifactFile = artifact.getFile();
                    String entryName = getEntryName(artifactFile, startOrder);

                    ZipEntry ze = new ZipEntry(entryName);
                    try {
                        os.putNextEntry(ze);
                        Files.copy(artifactFile.toPath(), os);
                    } finally {
                        os.closeEntry();
                    }
                }
            }
        }

        int sl = createSubsystemManifest(feature, bsnStartOrderMap, os);
        if (sl != -1)
            startLevelHolder.set(sl);
        addReadme(os);
    } catch (IOException ioe) {
        throw new MojoExecutionException("Problem creating subsystem .esa file " + subsystemFile, ioe);
    }
    return subsystemFile;
}

From source file:org.kepler.kar.KARBuilder.java

/**
 *
 *//*from  w  w w  . jav  a  2  s  .c  om*/
private void writeKARFile() throws IOException {

    JarOutputStream jos = new JarOutputStream(new FileOutputStream(_karFile), _manifest);
    Iterator<KAREntry> li = _karItems.keySet().iterator();
    while (li.hasNext()) {
        KAREntry entry = (KAREntry) li.next();
        if (isDebugging)
            log.debug("Writing " + entry.getName());
        try {
            jos.putNextEntry(entry);

            if (_karItems.get(entry) instanceof InputStream) {
                // inputstream from a bin file
                byte[] b = new byte[1024];
                InputStream is = (InputStream) _karItems.get(entry);
                int numread = is.read(b, 0, 1024);
                while (numread != -1) {
                    jos.write(b, 0, numread);
                    numread = is.read(b, 0, 1024);
                }
                is.close();
                // jos.flush();
                jos.closeEntry();
            }
        } catch (IOException ioe) {
            log.error(" Tried to write Duplicate Entry to kar " + entry.getName() + " " + entry.getLSID());
            ioe.printStackTrace();
        }
    }
    jos.flush();
    jos.close();

    log.info("done writing KAR file to " + _karFile.getAbsolutePath());
}