Example usage for java.util.jar JarOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry ze) throws IOException 

Source Link

Document

Begins writing a new JAR file entry and positions the stream to the start of the entry data.

Usage

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

/**
 * Code from forum board for creating a Jar.
 * //from  w w w  .  j a v a2s  . com
 * @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();

}

From source file:org.hyperic.hq.plugin.websphere.WebsphereProductPlugin.java

private File runtimeJarHack(File file) throws Exception {
    String tmp = System.getProperty("java.io.tmpdir"); //agent/tmp
    File newJar = new File(tmp, file.getName());
    if (newJar.exists()) {
        return newJar;
    }/*from   w  w  w .  ja  va  2 s . c  o m*/
    log.debug("Creating " + newJar);
    JarFile jar = new JarFile(file);
    JarOutputStream os = new JarOutputStream(new FileOutputStream(newJar));
    byte[] buffer = new byte[1024];
    try {
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            int n;
            JarEntry entry = e.nextElement();

            if (entry.getName().startsWith("org/apache/commons/logging/")) {
                continue;
            }
            InputStream entryStream = jar.getInputStream(entry);

            os.putNextEntry(entry);
            while ((n = entryStream.read(buffer)) != -1) {
                os.write(buffer, 0, n);
            }
            entryStream.close();
        }
    } finally {
        jar.close();
        os.close();
    }
    return newJar;
}

From source file:org.dspace.installer_edm.InstallerCrosswalk.java

/**
 * Abre el jar para escribir el nuevo archivo class compilado, elresto de archivos los copia tal cual
 *
 * @throws IOException/* w w w .  j  a v a 2 s  .co m*/
 */
protected void writeNewJar() throws IOException {
    // buffer para leer datos de los archivos
    final int BUFFER_SIZE = 1024;
    // directorio de trabajo
    File jarDir = new File(this.oaiApiJarJarFile.getName()).getParentFile();
    // nombre del jar
    String name = oaiApiJarWorkFile.getName();
    String extension = name.substring(name.lastIndexOf('.'));
    name = name.substring(0, name.lastIndexOf('.'));
    // archivo temporal del nuevo jar
    File newJarFile = File.createTempFile(name, extension, jarDir);
    newJarFile.deleteOnExit();
    // flujo de escritura del nuevo jar
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    // recorrer todos los archivos del jar menos el crosswalk para replicarlos
    try {
        Enumeration<JarEntry> entries = oaiApiJarJarFile.entries();
        while (entries.hasMoreElements()) {
            installerEDMDisplay.showProgress('.');
            JarEntry entry = entries.nextElement();
            if (!entry.getName().equals(edmCrossWalkClass)) {
                JarEntry entryOld = new JarEntry(entry);
                entryOld.setCompressedSize(-1);
                jarOutputStream.putNextEntry(entryOld);
                InputStream intputStream = oaiApiJarJarFile.getInputStream(entry);
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    jarOutputStream.write(data, 0, count);
                }
                intputStream.close();
            }
        }
        installerEDMDisplay.showLn();
        // aadir class compilado
        addClass2Jar(jarOutputStream);
        // cerrar jar original
        oaiApiJarJarFile.close();
        // borrar jar original
        oaiApiJarWorkFile.delete();
        // cambiar jar original por nuevo
        try {
            /*if (newJarFile.renameTo(oaiApiJarWorkFile) && oaiApiJarWorkFile.setExecutable(true, true)) {
            oaiApiJarWorkFile = new File(oaiApiJarName);
            } else {
            throw new IOException();
            }*/
            if (jarOutputStream != null)
                jarOutputStream.close();
            FileUtils.moveFile(newJarFile, oaiApiJarWorkFile);
            oaiApiJarWorkFile.setExecutable(true, true);
            oaiApiJarWorkFile = new File(oaiApiJarName);
        } catch (Exception io) {
            io.printStackTrace();
            throw new IOException();
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

From source file:org.apache.hadoop.mapreduce.v2.TestMRJobs.java

private Path makeJar(Path p, int index) throws FileNotFoundException, IOException {
    FileOutputStream fos = new FileOutputStream(new File(p.toUri().getPath()));
    JarOutputStream jos = new JarOutputStream(fos);
    ZipEntry ze = new ZipEntry("distributed.jar.inside" + index);
    jos.putNextEntry(ze);
    jos.write(("inside the jar!" + index).getBytes());
    jos.closeEntry();/*w w  w  .j a v  a 2  s  . c  om*/
    jos.close();
    localFs.setPermission(p, new FsPermission("700"));
    return p;
}

From source file:org.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java

private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) {
    try {/* ww w  . j  av a 2s  .  c om*/
        final boolean oldExists = moveJarToOld();
        if (javacresult.size() > 0) {
            final Set<String> entries = new HashSet<String>();
            final JarOutputStream jos = new JarOutputStream(
                    new BufferedOutputStream(new FileOutputStream(JARFILE)), getManifest());

            try {
                for (final String key : javacresult.keySet()) {
                    entries.add(key);
                    byte[] bytecode = javacresult.get(key);

                    // create entry for directory (required for classpath scanning)
                    if (key.contains("/")) {
                        String dir = key.substring(0, key.lastIndexOf('/') + 1);
                        if (!entries.contains(dir)) {
                            entries.add(dir);
                            jos.putNextEntry(new JarEntry(dir));
                            jos.closeEntry();
                        }
                    }

                    // call postCompile() (weaving) on compiled sources
                    for (CodeGenerator generator : generators) {
                        if (!oldExists || generator.isRecompileNecessary()) {
                            for (JavaSourceAsString src : generator.getSourceFiles()) {
                                final String name = src.getFQName();
                                if (key.startsWith(name.replaceAll("\\.", "/"))) {
                                    LOG.debug("postCompile (weaving) " + key);
                                    bytecode = generator.postCompile(key, bytecode);
                                    // Can we break here???
                                    // break outer;
                                }
                            }
                        }
                    }
                    jos.putNextEntry(new ZipEntry(key));
                    LOG.debug("writing to " + key + " to jar " + JARFILE);
                    jos.write(bytecode);
                    jos.closeEntry();
                }

                if (oldExists) {
                    final JarInputStream in = new JarInputStream(
                            new BufferedInputStream(new FileInputStream(JARFILE_OLD)));
                    final byte[] buffer = new byte[2048];
                    try {
                        int size;
                        JarEntry entry;
                        while ((entry = in.getNextJarEntry()) != null) {
                            if (!entries.contains(entry.getName())) {
                                jos.putNextEntry(entry);
                                LOG.debug("copying " + entry.getName() + " from old jar " + JARFILE_OLD);
                                while ((size = in.read(buffer, 0, buffer.length)) != -1) {
                                    jos.write(buffer, 0, size);
                                }
                                jos.closeEntry();
                            }
                            in.closeEntry();
                        }
                    } finally {
                        in.close();
                    }
                }
            } finally {
                jos.close();
            }
        }
    } catch (IOException ex) {
        throw new NuclosFatalException(ex);
    }
}

From source file:JarEntryOutputStream.java

/**
 * Writes the entry to a the jar file.  This is done by creating a
 * temporary jar file, copying the contents of the existing jar to the
 * temp jar, skipping the entry named by this.jarEntryName if it exists.
 * Then, if the stream was written to, then contents are written as a
 * new entry.  Last, a callback is made to the EnhancedJarFile to
 * swap the temp jar in for the old jar.
 *///from  ww  w  .  j a va2s  . co m
private void writeToJar() throws IOException {

    File jarDir = new File(this.jar.getName()).getParentFile();
    // create new jar
    File newJarFile = File.createTempFile("config", ".jar", jarDir);
    newJarFile.deleteOnExit();
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    try {
        Enumeration entries = this.jar.entries();

        // copy all current entries into the new jar
        while (entries.hasMoreElements()) {
            JarEntry nextEntry = (JarEntry) entries.nextElement();
            // skip the entry named jarEntryName
            if (!this.jarEntryName.equals(nextEntry.getName())) {
                // the next 3 lines of code are a work around for
                // bug 4682202 in the java.sun.com bug parade, see:
                // http://developer.java.sun.com/developer/bugParade/bugs/4682202.html
                JarEntry entryCopy = new JarEntry(nextEntry);
                entryCopy.setCompressedSize(-1);
                jarOutputStream.putNextEntry(entryCopy);

                InputStream intputStream = this.jar.getInputStream(nextEntry);
                // write the data
                for (int data = intputStream.read(); data != -1; data = intputStream.read()) {

                    jarOutputStream.write(data);
                }
            }
        }

        // write the new or modified entry to the jar
        if (size() > 0) {
            jarOutputStream.putNextEntry(new JarEntry(this.jarEntryName));
            jarOutputStream.write(super.buf, 0, size());
            jarOutputStream.closeEntry();
        }
    } finally {
        // close close everything up
        try {
            if (jarOutputStream != null) {
                jarOutputStream.close();
            }
        } catch (IOException ioe) {
            // eat it, just wanted to close stream
        }
    }

    // swap the jar
    this.jar.swapJars(newJarFile);
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java

/**
 * Change the version in jar//w w w  . j  a va  2 s  .com
 * 
 * @param newVersion
 * @param file
 * @return
 * @throws MojoExecutionException
 */
protected File changeVersion(File file, String oldVersion, String newVersion) throws MojoExecutionException {
    String fileName = file.getName();
    int pos = fileName.indexOf(oldVersion);
    fileName = fileName.substring(0, pos) + newVersion + fileName.substring(pos + oldVersion.length());

    JarInputStream jis = null;
    JarOutputStream jos;
    OutputStream out = null;
    JarFile sourceJar = null;
    try {
        // now create a temporary file and update the version
        sourceJar = new JarFile(file);
        final Manifest manifest = sourceJar.getManifest();
        manifest.getMainAttributes().putValue("Bundle-Version", newVersion);

        jis = new JarInputStream(new FileInputStream(file));
        final File destJar = new File(file.getParentFile(), fileName);
        out = new FileOutputStream(destJar);
        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()) {
                IOUtils.copy(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();
        return destJar;
    } catch (IOException ioe) {
        throw new MojoExecutionException("Unable to update version in jar file.", ioe);
    } finally {
        if (sourceJar != null) {
            try {
                sourceJar.close();
            } catch (IOException ex) {
                // close
            }
        }
        IOUtils.closeQuietly(jis);
        IOUtils.closeQuietly(out);
    }

}

From source file:com.amalto.core.jobox.watch.JoboxListener.java

public void contextChanged(String jobFile, String context) {
    File entity = new File(jobFile);
    String sourcePath = jobFile;/*from   ww  w .  j a v a  2 s . com*/
    int dotMark = jobFile.lastIndexOf("."); //$NON-NLS-1$
    int separateMark = jobFile.lastIndexOf(File.separatorChar);
    if (dotMark != -1) {
        sourcePath = System.getProperty("java.io.tmpdir") + File.separatorChar //$NON-NLS-1$
                + jobFile.substring(separateMark, dotMark);
    }
    try {
        JoboxUtil.extract(jobFile, System.getProperty("java.io.tmpdir") + File.separatorChar); //$NON-NLS-1$
    } catch (Exception e1) {
        LOGGER.error("Extraction exception occurred.", e1);
        return;
    }
    List<File> resultList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, new File(sourcePath), "classpath.jar", resultList); //$NON-NLS-1$
    if (!resultList.isEmpty()) {
        JarInputStream jarIn = null;
        JarOutputStream jarOut = null;
        try {
            JarFile jarFile = new JarFile(resultList.get(0));
            Manifest mf = jarFile.getManifest();
            jarIn = new JarInputStream(new FileInputStream(resultList.get(0)));
            Manifest newManifest = jarIn.getManifest();
            if (newManifest == null) {
                newManifest = new Manifest();
            }
            newManifest.getMainAttributes().putAll(mf.getMainAttributes());
            newManifest.getMainAttributes().putValue("activeContext", context); //$NON-NLS-1$
            jarOut = new JarOutputStream(new FileOutputStream(resultList.get(0)), newManifest);
            byte[] buf = new byte[4096];
            JarEntry entry;
            while ((entry = jarIn.getNextJarEntry()) != null) {
                if ("META-INF/MANIFEST.MF".equals(entry.getName())) { //$NON-NLS-1$
                    continue;
                }
                jarOut.putNextEntry(entry);
                int read;
                while ((read = jarIn.read(buf)) != -1) {
                    jarOut.write(buf, 0, read);
                }
                jarOut.closeEntry();
            }
        } catch (Exception e) {
            LOGGER.error("Extraction exception occurred.", e);
        } finally {
            IOUtils.closeQuietly(jarIn);
            IOUtils.closeQuietly(jarOut);
        }
        // re-zip file
        if (entity.getName().endsWith(".zip")) { //$NON-NLS-1$
            File sourceFile = new File(sourcePath);
            try {
                JoboxUtil.zip(sourceFile, jobFile);
            } catch (Exception e) {
                LOGGER.error("Zip exception occurred.", e);
            }
        }
    }
}

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

public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
        throws URISyntaxException, IOException {
    File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
    File destinationFileDirectory = new File(destinationDirectory);
    JarOutputStream jarOutputStream = null;
    InputStream inputStream = null;

    try {/*from   w  w w  .  j ava2s  .  c o m*/
        JarFile jarFile = new JarFile(sourceFile);
        String fileName = jarFile.getName();
        String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
        File destinationFile = new File(destinationFileDirectory, fileNameLastPart);
        jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            try {
                JarEntry jarEntry = entries.nextElement();
                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);
                }
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        log.warn("Fail to close jarOutStream");
                    }
                }
                if (jarOutputStream != null) {
                    try {
                        jarOutputStream.flush();
                        jarOutputStream.closeEntry();
                    } catch (IOException e) {
                        log.warn("Error while closing jar out stream");
                    }
                }
                if (jarFile != null) {
                    try {
                        jarFile.close();
                    } catch (IOException e) {
                        log.warn("Error while closing jar file");
                    }
                }
            }
        }
    } finally {
        if (jarOutputStream != null) {
            try {
                jarOutputStream.close();
            } catch (IOException e) {
                log.warn("Fail to close jarOutStream");
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.warn("Error while closing input stream");
            }
        }
    }
}

From source file:org.apache.hadoop.mapreduce.v2.TestMRJobs.java

private void createAndAddJarToJar(JarOutputStream jos, File jarFile) throws FileNotFoundException, IOException {
    FileOutputStream fos2 = new FileOutputStream(jarFile);
    JarOutputStream jos2 = new JarOutputStream(fos2);
    // Have to have at least one entry or it will complain
    ZipEntry ze = new ZipEntry("lib1.inside");
    jos2.putNextEntry(ze);
    jos2.closeEntry();/*from   www  .j av  a  2 s . c o  m*/
    jos2.close();
    ze = new ZipEntry("lib/" + jarFile.getName());
    jos.putNextEntry(ze);
    FileInputStream in = new FileInputStream(jarFile);
    byte buf[] = new byte[1024];
    int numRead;
    do {
        numRead = in.read(buf);
        if (numRead >= 0) {
            jos.write(buf, 0, numRead);
        }
    } while (numRead != -1);
    in.close();
    jos.closeEntry();
    jarFile.delete();
}