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) throws IOException 

Source Link

Document

Creates a new JarOutputStream with no manifest.

Usage

From source file:org.sourcepit.common.maven.testing.ArtifactRepositoryFacade.java

private static File createStubJar(File dir) throws IOException {
    final File jarFile = File.createTempFile("stub", ".jar", dir);

    JarOutputStream jarOut = null;
    try {/* w w  w  .j a v a  2 s .  c om*/
        jarOut = new JarOutputStream(new FileOutputStream(jarFile));

        final JarEntry mfEntry = new JarEntry(JarFile.MANIFEST_NAME);
        jarOut.putNextEntry(mfEntry);

        final Manifest mf = new Manifest();
        mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1");
        mf.write(jarOut);

        jarOut.closeEntry();
    } finally {
        IOUtils.closeQuietly(jarOut);
    }

    return jarFile;
}

From source file:org.apache.hadoop.hbase.mapreduce.hadoopbackport.TestJarFinder.java

@Test
public void testNoManifest() throws Exception {
    File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
            TestJarFinder.class.getName() + "-testNoManifest");
    delete(dir);//from  w  ww . j  a  va 2  s  . c o m
    dir.mkdirs();
    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();
}

From source file:com.izforge.izpack.installer.unpacker.Pack200FileUnpackerTest.java

/**
 * Creates a new source file.//from w w w . ja v  a2s .  c  o  m
 *
 * @param baseDir the base directory
 * @return the source file
 * @throws IOException for any I/O error
 */
@Override
protected File createSourceFile(File baseDir) throws IOException {
    File source = super.createSourceFile(baseDir);

    this.sourceFile = new File(baseDir, "source.jar");
    JarOutputStream srcJar = new JarOutputStream(new FileOutputStream(this.sourceFile));
    FileInputStream stream = new FileInputStream(source);
    try {
        IoHelper.copyStreamToJar(stream, srcJar, source.getName(), source.lastModified());
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(srcJar);
    }

    return this.sourceFile;
}

From source file:com.izforge.izpack.compiler.packager.impl.AbstractPackagerTest.java

/**
 * Verifies that the pack size is calculated correctly.
 *
 * @param expectedSize     the expected pack size
 * @param expectedFileSize the expected total file size
 * @param size             the pack size. May be {@code 0}
 * @param files            the pack files
 * @throws Exception for any error/*from w  w  w  . j av  a2s.  co  m*/
 */
private void checkSize(long expectedSize, long expectedFileSize, long size, File... files) throws Exception {
    File jar = File.createTempFile("installer", ".jar");

    JarOutputStream output = new JarOutputStream(new FileOutputStream(jar));
    PackagerBase packager = createPackager(output, mergeManager);

    PackInfo packInfo = new PackInfo("Core", "Core", null, true, false, null, true, size);
    long fileSize = 0;
    for (File file : files) {
        packInfo.addFile(file.getParentFile(), file, "$INSTALL_PATH/" + file.getName(), null,
                OverrideType.OVERRIDE_TRUE, null, Blockable.BLOCKABLE_NONE, null, null, null);
        fileSize += file.length();
    }
    packager.addPack(packInfo);
    packager.createInstaller();

    InputStream jarEntry = getJarEntry("resources/packs.info", jar);

    ObjectInputStream packStream = new ObjectInputStream(jarEntry);
    List<PackInfo> packsInfo = (List<PackInfo>) packStream.readObject();
    assertEquals(1, packsInfo.size());
    Pack pack = packsInfo.get(0).getPack();
    assertEquals(expectedSize, pack.getSize());
    assertEquals(expectedFileSize, fileSize);

    IOUtils.closeQuietly(jarEntry);
    IOUtils.closeQuietly(packStream);
    assertTrue(jar.delete());
}

From source file:JarUtils.java

/**
 * <P>This function will create a Jar archive containing the src
 * file/directory.  The archive will be written to the specified
 * OutputStream.  Directories are processed recursively, applying the
 * specified filter if it exists./*from   w  w  w  .j  a v  a  2  s .co m*/
 *
 * @param out The output stream to which the generated Jar archive is
 *        written.
 * @param src The file or directory to jar up.  Directories will be
 *        processed recursively.
 * @param filter The filter to use while processing directories.  Only
 *        those files matching will be included in the jar archive.  If
 *        null, then all files are included.
 * @param prefix The name of an arbitrary directory that will precede all
 *        entries in the jar archive.  If null, then no prefix will be
 *        used.
 * @param man The manifest to use for the Jar archive.  If null, then no
 *        manifest will be included.
 * @throws IOException 
 */
public static void jar(OutputStream out, File[] src, FileFilter filter, String prefix, Manifest man)
        throws IOException {

    for (int i = 0; i < src.length; i++) {
        if (!src[i].exists()) {
            throw new FileNotFoundException(src.toString());
        }
    }

    JarOutputStream jout;
    if (man == null) {
        jout = new JarOutputStream(out);
    } else {
        jout = new JarOutputStream(out, man);
    }
    if (prefix != null && prefix.length() > 0 && !prefix.equals("/")) {
        // strip leading '/'
        if (prefix.charAt(0) == '/') {
            prefix = prefix.substring(1);
        }
        // ensure trailing '/'
        if (prefix.charAt(prefix.length() - 1) != '/') {
            prefix = prefix + "/";
        }
    } else {
        prefix = "";
    }
    JarInfo info = new JarInfo(jout, filter);
    for (int i = 0; i < src.length; i++) {
        jar(src[i], prefix, info);
    }
    jout.close();
}

From source file:org.apache.maven.plugins.shade.resource.ServiceResourceTransformerTest.java

@Test
public void concatenation() throws Exception {
    SimpleRelocator relocator = new SimpleRelocator("org.foo", "borg.foo", null, null);
    List<Relocator> relocators = Lists.<Relocator>newArrayList(relocator);

    String content = "org.foo.Service\n";
    byte[] contentBytes = content.getBytes("UTF-8");
    InputStream contentStream = new ByteArrayInputStream(contentBytes);
    String contentResource = "META-INF/services/org.something.another";

    ServicesResourceTransformer xformer = new ServicesResourceTransformer();
    xformer.processResource(contentResource, contentStream, relocators);
    contentStream.close();/*from  www.ja v a  2  s.  c o  m*/

    content = "org.blah.Service\n";
    contentBytes = content.getBytes("UTF-8");
    contentStream = new ByteArrayInputStream(contentBytes);
    contentResource = "META-INF/services/org.something.another";

    xformer.processResource(contentResource, contentStream, relocators);
    contentStream.close();

    File tempJar = File.createTempFile("shade.", ".jar");
    tempJar.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(tempJar);
    JarOutputStream jos = new JarOutputStream(fos);
    try {
        xformer.modifyOutputStream(jos, false);
        jos.close();
        jos = null;
        JarFile jarFile = new JarFile(tempJar);
        JarEntry jarEntry = jarFile.getJarEntry(contentResource);
        assertNotNull(jarEntry);
        InputStream entryStream = jarFile.getInputStream(jarEntry);
        try {
            String xformedContent = IOUtils.toString(entryStream, "utf-8");
            // must be two lines, with our two classes.
            String[] classes = xformedContent.split("\r?\n");
            boolean h1 = false;
            boolean h2 = false;
            for (String name : classes) {
                if ("org.blah.Service".equals(name)) {
                    h1 = true;
                } else if ("borg.foo.Service".equals(name)) {
                    h2 = true;
                }
            }
            assertTrue(h1 && h2);
        } finally {
            IOUtils.closeQuietly(entryStream);
            jarFile.close();
        }
    } finally {
        if (jos != null) {
            IOUtils.closeQuietly(jos);
        }
        tempJar.delete();
    }
}

From source file:org.wso2.esb.integration.common.utils.common.FileManager.java

public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
        throws IOException, URISyntaxException {
    File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
    File destinationFileDirectory = new File(destinationDirectory);
    JarFile jarFile = new JarFile(sourceFile);
    String fileName = jarFile.getName();
    String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
    File destinationFile = new File(destinationFileDirectory, fileNameLastPart);

    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
    Enumeration<JarEntry> entries = jarFile.entries();

    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        InputStream inputStream = jarFile.getInputStream(jarEntry);

        //jarOutputStream.putNextEntry(jarEntry);
        //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size
        jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName()));
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            jarOutputStream.write(buffer, 0, bytesRead);
        }//from  ww  w  .  j av  a 2 s .  co  m
        inputStream.close();
        jarOutputStream.flush();
        jarOutputStream.closeEntry();
    }
    jarOutputStream.close();
}

From source file:org.cloudata.core.parallel.hadoop.CloudataMapReduceUtil.java

private static Path makeJarToHDFS(FileSystem fs, Path parentPath, File file) throws IOException {
    Path path = new Path(parentPath, file.getName() + ".jar");

    JarOutputStream out = new JarOutputStream(fs.create(path));
    out.putNextEntry(new JarEntry(file.getName()));

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));

    byte[] buf = new byte[1024];

    try {/*  w  w  w  . ja va  2s . c  o m*/
        int readBytes = 0;
        while ((readBytes = in.read(buf)) > 0) {
            out.write(buf, 0, readBytes);
        }
    } finally {
        if (out != null) {
            out.close();
        }

        if (in != null) {
            in.close();
        }
    }

    return path;
}

From source file:JarUtil.java

/**
 * Adds the given file to the specified JAR file.
 * /*from   w w  w . j  a v  a  2s. c o m*/
 * @param file
 *            the file that should be added
 * @param jarFile
 *            The JAR to which the file should be added
 * @param parentDir
 *            the parent directory of the file, this is used to calculate
 *            the path witin the JAR file. When null is given, the file will
 *            be added into the root of the JAR.
 * @param compress
 *            True when the jar file should be compressed
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void addToJar(File file, File jarFile, File parentDir, boolean compress)
        throws FileNotFoundException, IOException {
    File tmpJarFile = File.createTempFile("tmp", ".jar", jarFile.getParentFile());
    JarOutputStream out = new JarOutputStream(new FileOutputStream(tmpJarFile));
    if (compress) {
        out.setLevel(ZipOutputStream.DEFLATED);
    } else {
        out.setLevel(ZipOutputStream.STORED);
    }
    // copy contents of old jar to new jar:
    JarFile inputFile = new JarFile(jarFile);
    JarInputStream in = new JarInputStream(new FileInputStream(jarFile));
    CRC32 crc = new CRC32();
    byte[] buffer = new byte[512 * 1024];
    JarEntry entry = (JarEntry) in.getNextEntry();
    while (entry != null) {
        InputStream entryIn = inputFile.getInputStream(entry);
        add(entry, entryIn, out, crc, buffer);
        entryIn.close();
        entry = (JarEntry) in.getNextEntry();
    }
    in.close();
    inputFile.close();

    int sourceDirLength;
    if (parentDir == null) {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1;
    } else {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1
                - parentDir.getAbsolutePath().length();
    }
    addFile(file, out, crc, sourceDirLength, buffer);
    out.close();

    // remove old jar file and rename temp file to old one:
    if (jarFile.delete()) {
        if (!tmpJarFile.renameTo(jarFile)) {
            throw new IOException(
                    "Unable to rename temporary JAR file to [" + jarFile.getAbsolutePath() + "].");
        }
    } else {
        throw new IOException("Unable to delete old JAR file [" + jarFile.getAbsolutePath() + "].");
    }

}

From source file:com.threerings.cast.bundle.tools.MetadataBundlerTask.java

/**
 * Creates the base output stream to which to write our bundle's files.
 *//*  w  ww  . j a va  2s  .  c o  m*/
protected OutputStream createOutputStream(File target) throws IOException {
    JarOutputStream jout = new JarOutputStream(new FileOutputStream(target));
    jout.setLevel(Deflater.BEST_COMPRESSION);
    return jout;
}