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:org.wso2.carbon.integration.common.utils.FileManager.java

public static void copyJarFile(File sourceFile, String destinationDirectory) throws IOException {
    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 = null;
    try {/*from w ww.  ja  v a 2s . c o m*/
        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);
            }
            inputStream.close();
            jarOutputStream.flush();
            jarOutputStream.closeEntry();
        }
    } finally {
        if (jarOutputStream != null) {
            try {
                jarOutputStream.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }
}

From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java

private static void addEntry(JarOutputStream jas, String name, byte[] content) throws Exception {
    JarEntry entry = new JarEntry(name);
    jas.putNextEntry(entry);
    if (content != null) {
        jas.write(content);//from  ww  w.  j av a2 s  .com
    }
    jas.closeEntry();
}

From source file:org.colombbus.tangara.FileUtils.java

private static void addFileToJar(File fileToAdd, JarOutputStream output, String prefix) throws IOException {
    BufferedInputStream input = null;
    JarEntry entry = null;/* ww  w.j a v a2  s .c  o  m*/
    try {
        if (prefix != null)
            entry = new JarEntry(prefix + "/" + fileToAdd.getName());
        else
            entry = new JarEntry(fileToAdd.getName());
        output.putNextEntry(entry);
        input = new BufferedInputStream(new FileInputStream(fileToAdd));
        byte buffer[] = new byte[2048];
        while (true) {
            int n = input.read(buffer);
            if (n <= 0)
                break;
            output.write(buffer, 0, n);
        }
        input.close();
    } catch (IOException e) {
        LOG.error("Error trying to add file '" + fileToAdd.getAbsolutePath() + "' to jar", e);
        if (input != null) {
            try {
                input.close();
            } catch (IOException e2) {
            }
        }
        throw e;
    }
}

From source file:org.mule.util.JarUtils.java

public static void createJarFileEntries(File jarFile, LinkedHashMap entries) throws Exception {
    JarOutputStream jarStream = null;
    FileOutputStream fileStream = null;

    if (jarFile != null) {
        logger.debug("Creating jar file " + jarFile.getAbsolutePath());

        try {/*from w w  w  .  j  ava  2  s .  c  o m*/
            fileStream = new FileOutputStream(jarFile);
            jarStream = new JarOutputStream(fileStream);

            if (entries != null && !entries.isEmpty()) {
                Iterator iter = entries.keySet().iterator();
                while (iter.hasNext()) {
                    String jarFilePath = (String) iter.next();
                    Object content = entries.get(jarFilePath);

                    JarEntry entry = new JarEntry(jarFilePath);
                    jarStream.putNextEntry(entry);

                    logger.debug("Adding jar entry " + jarFilePath + " to " + jarFile.getAbsolutePath());

                    if (content instanceof String) {
                        writeJarEntry(jarStream, ((String) content).getBytes());
                    } else if (content instanceof byte[]) {
                        writeJarEntry(jarStream, (byte[]) content);
                    } else if (content instanceof File) {
                        writeJarEntry(jarStream, (File) content);
                    }
                }
            }

            jarStream.flush();
            fileStream.getFD().sync();
        } finally {
            if (jarStream != null) {
                try {
                    jarStream.close();
                } catch (Exception jarNotClosed) {
                    logger.debug(jarNotClosed);
                }
            }
            if (fileStream != null) {
                try {
                    fileStream.close();
                } catch (Exception fileNotClosed) {
                    logger.debug(fileNotClosed);
                }
            }
        }
    }
}

From source file:ai.h2o.servicebuilder.Util.java

/**
 * Create jar archive out of files list. Names in archive have paths starting from relativeToDir
 *
 * @param tobeJared     list of files/*from   w  w  w .j  av  a  2  s .  c om*/
 * @param relativeToDir starting directory for paths
 * @return jar as byte array
 * @throws IOException
 */
public static byte[] createJarArchiveByteArray(File[] tobeJared, String relativeToDir) throws IOException {
    int BUFFER_SIZE = 10240;
    byte buffer[] = new byte[BUFFER_SIZE];
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    JarOutputStream out = new JarOutputStream(stream, new Manifest());

    for (File t : tobeJared) {
        if (t == null || !t.exists() || t.isDirectory()) {
            if (t != null && !t.isDirectory())
                logger.error("Can't add to jar {}", t);
            continue;
        }
        // Create jar entry
        String filename = t.getPath().replace(relativeToDir, "").replace("\\", "/");
        //      if (filename.endsWith("MANIFEST.MF")) { // skip to avoid duplicates
        //        continue;
        //      }
        JarEntry jarAdd = new JarEntry(filename);
        jarAdd.setTime(t.lastModified());
        out.putNextEntry(jarAdd);

        // Write file to archive
        FileInputStream in = new FileInputStream(t);
        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();
    return stream.toByteArray();
}

From source file:org.roda.core.util.ZipUtility.java

/**
 * Creates ZIP file with the files inside directory <code>contentsDir</code> .
 * //from  w  w w.  jav  a 2 s  . c o  m
 * @param newZipFile
 *          the ZIP file to create
 * @param contentsDir
 *          the directory containing the files to compress.
 * @return the created ZIP file.
 * @throws IOException
 *           if something goes wrong with creation of the ZIP file or the
 *           reading of the files to compress.
 */
public static File createZIPFile(File newZipFile, File contentsDir) throws IOException {

    List<File> contentAbsoluteFiles = FileUtility.listFilesRecursively(contentsDir);

    FileOutputStream zipStream = new FileOutputStream(newZipFile);
    JarOutputStream jarOutputStream = new JarOutputStream(new BufferedOutputStream(zipStream));

    // Create a buffer for reading the files
    byte[] buffer = new byte[BUFFER_SIZE];

    Iterator<File> iterator = contentAbsoluteFiles.iterator();
    while (iterator.hasNext()) {
        File absoluteFile = iterator.next();
        String relativeFile = getFilePathRelativeTo(absoluteFile, contentsDir);

        FileInputStream inputStream = new FileInputStream(absoluteFile);
        BufferedInputStream in = new BufferedInputStream(inputStream);

        // Add ZIP entry to output stream.
        jarOutputStream.putNextEntry(new JarEntry(relativeFile));

        LOGGER.trace("Adding {}", relativeFile);

        int length;
        while ((length = in.read(buffer)) > 0) {
            jarOutputStream.write(buffer, 0, length);
        }

        // Complete the entry
        jarOutputStream.closeEntry();
        in.close();
        inputStream.close();
    }

    // Complete the ZIP file
    jarOutputStream.close();
    zipStream.close();

    return newZipFile;
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

private static void replaceInJar(File sourceJar, String origFile, File replacementFile) throws IOException {
    String srcJarAbsPath = sourceJar.getAbsolutePath();
    String srcJarSuffix = srcJarAbsPath.substring(srcJarAbsPath.lastIndexOf(File.separator) + 1);
    String srcJarName = srcJarSuffix.split(".jar")[0];

    String destJarName = srcJarName + "-managix";
    String destJarSuffix = destJarName + ".jar";
    File destJar = new File(sourceJar.getParentFile().getAbsolutePath() + File.separator + destJarSuffix);
    //  File destJar = new File(sourceJar.getAbsolutePath() + ".modified");
    JarFile sourceJarFile = new JarFile(sourceJar);
    Enumeration<JarEntry> entries = sourceJarFile.entries();
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(destJar));
    byte[] buffer = new byte[2048];
    int read;/*  w  ww . j a  v  a2 s .com*/
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String name = entry.getName();
        if (name.equals(origFile)) {
            continue;
        }
        InputStream jarIs = sourceJarFile.getInputStream(entry);
        jos.putNextEntry(entry);
        while ((read = jarIs.read(buffer)) != -1) {
            jos.write(buffer, 0, read);
        }
        jarIs.close();
    }
    sourceJarFile.close();
    JarEntry entry = new JarEntry(origFile);
    jos.putNextEntry(entry);
    FileInputStream fis = new FileInputStream(replacementFile);
    while ((read = fis.read(buffer)) != -1) {
        jos.write(buffer, 0, read);
    }
    fis.close();
    jos.close();
    sourceJar.delete();
    destJar.renameTo(sourceJar);
    destJar.setExecutable(true);
}

From source file:JarMaker.java

/**
 * Combine several jar files and some given files into one jar file.
 * @param outJar The output jar file's filename.
 * @param inJarsList The jar files to be combined
 * @param filter A filter that exclude some entries of input jars. User
 *        should implement the EntryFilter interface.
 * @param inFileList The files to be added into the jar file.
 * @param prefixs The prefixs of files to be added into the jar file.
 *        inFileList and prefixs should be paired.
 * @throws FileNotFoundException// ww w . ja  v a 2 s.  co m
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static void combineJars(String outJar, String[] inJarsList, EntryFilter filter, String[] inFileList,
        String[] prefixs) throws FileNotFoundException, IOException {

    JarOutputStream jout = new JarOutputStream(new FileOutputStream(outJar));
    ArrayList entryList = new ArrayList();
    for (int i = 0; i < inJarsList.length; i++) {
        BufferedInputStream bufferedinputstream = new BufferedInputStream(new FileInputStream(inJarsList[i]));
        ZipInputStream zipinputstream = new ZipInputStream(bufferedinputstream);
        byte abyte0[] = new byte[1024 * 4];
        for (ZipEntry zipentry = zipinputstream.getNextEntry(); zipentry != null; zipentry = zipinputstream
                .getNextEntry()) {
            if (filter.accept(zipentry)) {
                if (!entryList.contains(zipentry.getName())) {
                    jout.putNextEntry(zipentry);
                    if (!zipentry.isDirectory()) {
                        int j;
                        try {
                            while ((j = zipinputstream.read(abyte0, 0, abyte0.length)) != -1)
                                jout.write(abyte0, 0, j);
                        } catch (IOException ie) {
                            throw ie;
                        }
                    }
                    entryList.add(zipentry.getName());
                }
            }
        }
        zipinputstream.close();
        bufferedinputstream.close();
    }
    for (int i = 0; i < inFileList.length; i++) {
        add(jout, new File(inFileList[i]), prefixs[i]);
    }
    jout.close();
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static void writeManifest(byte[] manifest, JarOutputStream jos) throws IOException {

    // Manifest file entry
    JarEntry mfJarEntry = new JarEntry(MANIFEST_LOCATION);
    jos.putNextEntry(mfJarEntry);

    // Write content
    ByteArrayInputStream bais = null;

    try {/*from  www.  j  ava  2 s . c o  m*/
        bais = new ByteArrayInputStream(manifest);

        byte[] buffer = new byte[2048];
        int read = -1;

        while ((read = bais.read(buffer)) != -1) {
            jos.write(buffer, 0, read);
        }

        jos.closeEntry();
    } finally {
        IOUtils.closeQuietly(bais);
    }
}

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

/**
 * Write an identifier file to the lite jar that can be used to identify
 * that the lite jar is being used.// ww  w. j a v a  2s. com
 * 
 * @param jos
 *            output stream to the jar being written
 * @param numFilesWritten
 *            the number of files written to the jar so far
 * @throws IOException
 *             if an IOException occurs
 */
private static void writeIdentifierFileToLiteJar(JarOutputStream jos, int numFilesWritten) throws IOException {
    writeMessage(LITE_JAR_IDENTIFIER_FILE, numFilesWritten);
    JarEntry je = new JarEntry(LITE_JAR_IDENTIFIER_FILE);
    jos.putNextEntry(je);
    String created = "Created " + (new Date());
    String userName = System.getProperty("user.name");
    if (userName != null) {
        created = created + " by " + userName;
    }
    jos.write(created.getBytes());
}