Example usage for java.util.jar JarOutputStream write

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

Introduction

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

Prototype

public synchronized void write(byte[] b, int off, int len) throws IOException 

Source Link

Document

Writes an array of bytes to the current ZIP entry data.

Usage

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

/**
 *
 *///from   w  w  w  . j  a v a  2s.  c o  m
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());
}

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   ww  w  .  j  a v  a2s .  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:com.amalto.core.jobox.watch.JoboxListener.java

public void contextChanged(String jobFile, String context) {
    File entity = new File(jobFile);
    String sourcePath = jobFile;/*from w w w  .ja va2 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:rapture.kernel.JarApiImplTest.java

private void add(File source, JarOutputStream target) throws IOException {
    BufferedInputStream in = null;
    try {/* www  .  j  a v  a 2s  .com*/
        if (source.isDirectory()) {
            String name = source.getPath().replace("\\", "/");
            if (!name.isEmpty()) {
                if (!name.endsWith("/")) {
                    name += "/";
                }
                JarEntry entry = new JarEntry(name);
                entry.setTime(source.lastModified());
                target.putNextEntry(entry);
                target.closeEntry();
            }
            for (File nestedFile : source.listFiles()) {
                add(nestedFile, target);
            }
            return;
        }

        JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        in = new BufferedInputStream(new FileInputStream(source));

        byte[] buffer = new byte[1024];
        while (true) {
            int count = in.read(buffer);
            if (count == -1) {
                break;
            }
            target.write(buffer, 0, count);
        }
        target.closeEntry();
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

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 a  2 s  . 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();

}

From source file:net.cliseau.composer.javacor.MissingToolException.java

/**
 * Create a JAR file for startup of the unit.
 *
 * The created JAR file contains all the specified archive files and contains a
 * manifest which in particular determines the class path for the JAR file.
 * All files in startupArchiveFileNames are deleted during the execution of
 * this method.//w  ww  . ja va2s.  c  o  m
 *
 * @param fileName Name of the file to write the result to.
 * @param startupArchiveFileNames Names of files to include in the JAR file.
 * @param startupDependencies Names of classpath entries to include in the JAR file classpath.
 * @exception IOException Thrown if file operations fail, such as creating the JAR file or reading from the input file(s).
 */
private void createJAR(final String fileName, final Collection<String> startupArchiveFileNames,
        final Collection<String> startupDependencies) throws IOException, InvalidConfigurationException {
    // Code inspired by:
    //   http://www.java2s.com/Code/Java/File-Input-Output/CreateJarfile.htm
    //   http://www.massapi.com/class/java/util/jar/Manifest.java.html

    // construct manifest with appropriate "Class-path" property
    Manifest starterManifest = new Manifest();
    Attributes starterAttributes = starterManifest.getMainAttributes();
    // Remark for those who read this code to learn something:
    // If one forgets to set the MANIFEST_VERSION attribute, then
    // silently *nothing* (except for a line break) will be written
    // to the JAR file manifest!
    starterAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    starterAttributes.put(Attributes.Name.MAIN_CLASS, getStartupName());
    starterAttributes.put(Attributes.Name.CLASS_PATH,
            StringUtils.join(startupDependencies, manifestClassPathSeparator));

    // create output JAR file
    FileOutputStream fos = new FileOutputStream(fileName);
    JarOutputStream jos = new JarOutputStream(fos, starterManifest);

    // add the entries for the starter archive's files
    for (String archFileName : startupArchiveFileNames) {
        File startupArchiveFile = new File(archFileName);
        JarEntry startupEntry = new JarEntry(startupArchiveFile.getName());
        startupEntry.setTime(startupArchiveFile.lastModified());
        jos.putNextEntry(startupEntry);

        // copy the content of the starter archive's file
        // TODO: if we used Apache Commons IO 2.1, then the following
        //       code block could be simplified as:
        //       FileUtils.copyFile(startupArchiveFile, jos);
        FileInputStream fis = new FileInputStream(startupArchiveFile);
        byte buffer[] = new byte[1024 /*bytes*/];
        while (true) {
            int nRead = fis.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            jos.write(buffer, 0, nRead);
        }
        fis.close();
        // end of FileUtils.copyFile() substitution code
        jos.closeEntry();

        startupArchiveFile.delete(); // cleanup the disk a bit
    }

    jos.close();
    fos.close();
}

From source file:JarUtils.java

/**
 * Create a jar file from a particular directory.
 * /*from  w ww .j a  v a 2 s .c  o m*/
 * @param root in the root directory
 * @param directory in the directory we are adding
 * @param jarStream the jar stream to be added to
 * @throws IOException on IOException
 */
protected void createJarFromDirectory(File root, File directory, JarOutputStream jarStream) throws IOException {
    byte[] buffer = new byte[40960];
    int bytesRead;

    File[] filesToAdd = directory.listFiles();

    for (int i = 0; i < filesToAdd.length; i++) {
        File fileToAdd = filesToAdd[i];

        if (fileToAdd.isDirectory()) {
            createJarFromDirectory(root, fileToAdd, jarStream);
        } else {
            FileInputStream addFile = new FileInputStream(fileToAdd);
            try {
                // Create a jar entry and add it to the temp jar.
                String entryName = fileToAdd.getPath().substring(root.getPath().length() + 1);

                // If we leave these entries as '\'s, then the resulting zip file won't be
                // expandable on Unix operating systems like OSX, because it is possible to 
                // have filenames with \s in them - so it's impossible to determine that this 
                // is actually a directory.
                entryName = entryName.replace('\\', '/');
                JarEntry entry = new JarEntry(entryName);
                jarStream.putNextEntry(entry);

                // Read the file and write it to the jar.
                while ((bytesRead = addFile.read(buffer)) != -1) {
                    jarStream.write(buffer, 0, bytesRead);
                }
                jarStream.closeEntry();
            } finally {
                addFile.close();
            }
        }
    }
}

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 {/*  ww w . ja  va 2s. 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.dspace.installer_edm.InstallerCrosswalk.java

/**
 * Abre el jar para escribir el nuevo archivo class compilado, elresto de archivos los copia tal cual
 *
 * @throws IOException/*from   w  w w  . j  a  v  a2  s  . com*/
 */
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:com.paniclauncher.workers.InstanceInstaller.java

public void deleteMetaInf() {
    File inputFile = getMinecraftJar();
    File outputTmpFile = new File(App.settings.getTempDir(), pack.getSafeName() + "-minecraft.jar");
    try {//from  w w w.  j a  va  2  s  .c  o m
        JarInputStream input = new JarInputStream(new FileInputStream(inputFile));
        JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile));
        JarEntry entry;

        while ((entry = input.getNextJarEntry()) != null) {
            if (entry.getName().contains("META-INF")) {
                continue;
            }
            output.putNextEntry(entry);
            byte buffer[] = new byte[1024];
            int amo;
            while ((amo = input.read(buffer, 0, 1024)) != -1) {
                output.write(buffer, 0, amo);
            }
            output.closeEntry();
        }

        input.close();
        output.close();

        inputFile.delete();
        outputTmpFile.renameTo(inputFile);
    } catch (IOException e) {
        App.settings.getConsole().logStackTrace(e);
    }
}