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.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;
    }//ww w  .  ja v  a  2s.com
    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.apache.hadoop.hive.ql.metadata.JarUtils.java

private static void createJar(File dir, File jarFile) throws IOException {
    Preconditions.checkNotNull(dir, "dir");
    Preconditions.checkNotNull(jarFile, "jarFile");
    File jarDir = jarFile.getParentFile();
    if (!jarDir.exists()) {
        if (!jarDir.mkdirs()) {
            throw new IOException(MessageFormat.format("could not create dir [{0}]", jarDir));
        }//from  www .j  ava  2  s. c o  m
    }
    JarOutputStream zos = new JarOutputStream(new FileOutputStream(jarFile));
    jarDir(dir, StringUtils.EMPTY, zos);
}

From source file:com.glaf.core.util.ZipUtils.java

public static void makeZip(File dir, File zipFile) throws IOException, FileNotFoundException {
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(zipFile));
    String as[] = dir.list();// w ww. ja v a  2 s  .c  o m
    if (as != null) {
        for (int i = 0; i < as.length; i++)
            recurseFiles(jos, new File(dir, as[i]), "");
    }
    jos.close();
}

From source file:com.taobao.android.builder.tools.asm.ClazzBasicHandler.java

public void execute() throws IOException {

    logger.info("[ClazzReplacer] rewriteJar from " + jar.getAbsolutePath() + " to " + outJar.getAbsolutePath());

    JarFile jarFile = new JarFile(jar);

    JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));

    Enumeration<JarEntry> jarFileEntries = jarFile.entries();

    while (jarFileEntries.hasMoreElements()) {

        JarEntry ze = jarFileEntries.nextElement();

        String pathName = ze.getName();

        logger.info(jar.getAbsolutePath() + "->" + pathName);

        if (!pathName.endsWith(".class")) {
            justCopy(jarFile, jos, ze, pathName);
            continue;
        }/*from   w  ww .j a  v a  2  s.  c om*/

        handleClazz(jarFile, jos, ze, pathName);

    }

    jarFile.close();
    //        IOUtils.closeQuietly(fileOutputStream);
    IOUtils.closeQuietly(jos);
}

From source file:org.eclipse.wb.tests.designer.TestUtils.java

/**
 * @return the path to the temporary "jar" file with single entry.
 * /*from  ww w .j a v a2 s.co m*/
 * @param entryName
 *          the name of entry, for example <code>"myFolder/subFolder/file.txt"</code>.
 * @param content
 *          the {@link String} content of entry.
 */
public static String createTemporaryJar(String entryName, String content) throws Exception {
    File tempFile = File.createTempFile("wbpTests", ".jar");
    tempFile.deleteOnExit();
    // create "jar" with single entry
    {
        JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(tempFile));
        jarOutputStream.putNextEntry(new ZipEntry(entryName));
        jarOutputStream.write(content.getBytes());
        jarOutputStream.closeEntry();
        jarOutputStream.close();
    }
    // return path to "jar"
    return tempFile.getAbsolutePath();
}

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

/**
 * Recorre el war para escribir los archivos web.xml, la api de dspace y los jar de lucene
 *
 * @throws IOException// w  w  w  . ja  v a 2  s . c o  m
 * @throws TransformerException
 */
private void writeNewJar() throws IOException, TransformerException {
    final int BUFFER_SIZE = 1024;
    // directorio de trabajo
    File jarDir = new File(this.eDMExportWarJarFile.getName()).getParentFile();
    // archivo temporal del nuevo war
    File newJarFile = File.createTempFile("EDMExport", ".jar", jarDir);
    newJarFile.deleteOnExit();
    // flujo de escritura para el nuevo war
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    try {
        // recorrer los archivos del war
        Enumeration<JarEntry> entries = eDMExportWarJarFile.entries();
        // libreras de lucene
        Pattern luceneLibPattern = Pattern.compile("^WEB-INF/lib/(lucene-.+?)-\\d+.+\\.jar$");
        boolean newApiCopied = false;
        if (dspaceApi == null)
            newApiCopied = true;
        boolean replace = false;
        // recorrer
        while (entries.hasMoreElements()) {
            replace = false;
            installerEDMDisplay.showProgress('.');
            JarEntry entry = entries.nextElement();
            InputStream intputStream = null;
            // todos menos web.xml
            if (!entry.getName().equals("WEB-INF/web.xml")) {
                // api de dspace, se muestra la actual y la de dspace para pedir si se copia
                if (!newApiCopied && entry.getName().matches("^WEB-INF/lib/dspace-api-\\d+.+\\.jar$")) {
                    String response = null;
                    do {
                        installerEDMDisplay.showLn();
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace.question",
                                new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                        dspaceApi.getAbsolutePath() });
                        response = br.readLine();
                        if (response == null)
                            continue;
                        response = response.trim();
                        if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                            replace = true;
                            break;
                        } else if (response.equalsIgnoreCase("n")) {
                            break;
                        }
                    } while (true);
                    // se reemplaza por la de dspace
                    if (replace) {
                        JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + dspaceApi.getName());
                        newJarEntry.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(newJarEntry);
                        intputStream = new FileInputStream(dspaceApi);
                        newApiCopied = true;
                        if (debug) {
                            installerEDMDisplay.showLn();
                            installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                    new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                            dspaceApi.getAbsolutePath() });
                            installerEDMDisplay.showLn();
                        }
                    }
                } else {
                    // libreras de lucene
                    Matcher luceneLibMatcher = luceneLibPattern.matcher(entry.getName());
                    if (luceneLibMatcher.find()) {
                        String prefixLuceneLib = luceneLibMatcher.group(1);
                        File luceneLibFile = null;
                        String patternFile = prefixLuceneLib + "-\\d+.+\\.jar";
                        for (File file : luceneLibs) {
                            if (file.getName().matches(patternFile)) {
                                luceneLibFile = file;
                                break;
                            }
                        }
                        if (luceneLibFile != null) {
                            String response = null;
                            do {
                                installerEDMDisplay.showLn();
                                installerEDMDisplay.showQuestion(currentStepGlobal,
                                        "writeNewJar.replace.question",
                                        new String[] { entry.getName(),
                                                "WEB-INF/lib/" + luceneLibFile.getName(),
                                                luceneLibFile.getAbsolutePath() });
                                response = br.readLine();
                                if (response == null)
                                    continue;
                                response = response.trim();
                                if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                                    replace = true;
                                    break;
                                } else if (response.equalsIgnoreCase("n")) {
                                    break;
                                }
                            } while (true);
                            // se reemplaza por la de dspace
                            if (replace) {
                                JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + luceneLibFile.getName());
                                newJarEntry.setCompressedSize(-1);
                                jarOutputStream.putNextEntry(newJarEntry);
                                intputStream = new FileInputStream(luceneLibFile);
                                if (debug) {
                                    installerEDMDisplay.showLn();
                                    installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                            new String[] { entry.getName(),
                                                    "WEB-INF/lib/" + luceneLibFile.getName(),
                                                    luceneLibFile.getAbsolutePath() });
                                    installerEDMDisplay.showLn();
                                }
                            }
                        }
                        // si no era la api de dspace o las libreras de lucene se copia tal cual
                    } else if (!replace) {
                        JarEntry entryOld = new JarEntry(entry);
                        entryOld.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(entryOld);
                        intputStream = eDMExportWarJarFile.getInputStream(entry);
                    }
                }
                if (intputStream == null) {
                    if (debug)
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.notIS",
                                new String[] { entry.getName() });
                    continue;
                }
                // se lee el archivo y se copia al flujo de escritura del war
                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();
        // se aade web.xml al war
        addNewWebXml(jarOutputStream);
        // cerramos el archivo jar y borramos el war
        eDMExportWarJarFile.close();
        eDMExportWarWorkFile.delete();
        // sustituimos el viejo por el temporal
        try {
            /*if (newJarFile.renameTo(eDMExportWarWorkFile) && eDMExportWarWorkFile.setExecutable(true, true)) {
            eDMExportWarWorkFile = new File(myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
            } else {
            throw new IOException();
            }*/
            if (jarOutputStream != null)
                jarOutputStream.close();
            FileUtils.moveFile(newJarFile, eDMExportWarWorkFile);
            //newJarFile.renameTo(eDMExportWarWorkFile);
            eDMExportWarWorkFile.setExecutable(true, true);
            eDMExportWarWorkFile = new File(
                    myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
        } catch (Exception io) {
            io.printStackTrace();
            throw new IOException();
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

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

public static void makeJar(File directory, File jar, String mainClass, PropertyChangeListener listener,
        Hashtable<String, String> manifestAttributes) {
    JarOutputStream jarOutput = null;
    try {//from  w w  w .ja  v a 2s. co m
        jarOutput = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jar)));
        addDirectoryToJar(directory, jarOutput, null, listener);
        StringBuffer sbuf = new StringBuffer();
        sbuf.append("Manifest-Version: 1.0\n");
        sbuf.append("Built-By: Colombbus\n");
        if (mainClass != null)
            sbuf.append("Main-Class: " + mainClass + "\n");
        if (manifestAttributes != null) {
            for (Enumeration<String> keys = manifestAttributes.keys(); keys.hasMoreElements();) {
                String name = keys.nextElement();
                sbuf.append(name + ": " + manifestAttributes.get(name) + "\n");
            }
        }
        InputStream is = new ByteArrayInputStream(sbuf.toString().getBytes("UTF-8"));

        JarEntry manifestEntry = new JarEntry("META-INF/MANIFEST.MF");
        jarOutput.putNextEntry(manifestEntry);

        byte buffer[] = new byte[2048];
        while (true) {
            int n = is.read(buffer);
            if (n <= 0)
                break;
            jarOutput.write(buffer, 0, n);
        }
        is.close();
        jarOutput.close();
    } catch (Exception e) {
        LOG.error("Error while creating JAR file '" + jar.getAbsolutePath() + "'", e);
    } finally {
        try {
            if (jarOutput != null)
                jarOutput.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.hortonworks.streamline.streams.runtime.splitjoin.SplitJoinTest.java

private JarInputStream createJarInputStream(String... classNames) throws Exception {

    final File tempFile = Files.createTempFile(UUID.randomUUID().toString(), ".jar").toFile();
    tempFile.deleteOnExit();//w  ww. jav a  2 s  .c o  m

    try (JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(tempFile))) {
        for (String className : classNames) {
            final String classFileName = className.replace(".", "/") + ".class";
            try (InputStream classInputStream = this.getClass().getResourceAsStream("/" + classFileName)) {
                jarOutputStream.putNextEntry(new JarEntry(classFileName));
                IOUtils.copy(classInputStream, jarOutputStream);
            }
        }
    }

    return new JarInputStream(new FileInputStream(tempFile));
}

From source file:com.glaf.core.util.ZipUtils.java

public static byte[] toZipBytes(Map<String, byte[]> zipMap) {
    byte[] bytes = null;
    InputStream inputStream = null;
    BufferedInputStream bis = null;
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    JarOutputStream jos = null;//from ww w  .j  av  a  2s.co m
    try {
        baos = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(baos);
        jos = new JarOutputStream(bos);
        if (zipMap != null) {
            Set<Entry<String, byte[]>> entrySet = zipMap.entrySet();
            for (Entry<String, byte[]> entry : entrySet) {
                String name = entry.getKey();
                byte[] x_bytes = entry.getValue();
                inputStream = new ByteArrayInputStream(x_bytes);
                if (name != null && inputStream != null) {
                    bis = new BufferedInputStream(inputStream);
                    JarEntry jarEntry = new JarEntry(name);
                    jos.putNextEntry(jarEntry);
                    while ((len = bis.read(buf)) >= 0) {
                        jos.write(buf, 0, len);
                    }
                    IOUtils.closeStream(bis);
                    jos.closeEntry();
                }
                IOUtils.closeStream(inputStream);
            }
        }
        jos.flush();
        jos.close();

        bytes = baos.toByteArray();
        IOUtils.closeStream(baos);
        IOUtils.closeStream(bos);
        return bytes;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(inputStream);
        IOUtils.closeStream(baos);
        IOUtils.closeStream(bos);
    }
}

From source file:com.taobao.android.builder.tools.multidex.mutli.JarRefactor.java

private Collection<File> generateFirstDexJar(List<String> mainDexList, Collection<File> files)
        throws IOException {

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);/*from  ww  w . j a v  a  2  s.  co  m*/
        } else {
            jarList.add(file);
        }
    }

    File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(),
            "fastmultidex/" + appVariantContext.getVariantName());
    FileUtils.deleteDirectory(dir);
    dir.mkdirs();

    if (!folderList.isEmpty()) {
        File mergedJar = new File(dir, "jarmerging/combined.jar");
        mergedJar.getParentFile().mkdirs();
        mergedJar.delete();
        mergedJar.createNewFile();
        JarMerger jarMerger = new JarMerger(mergedJar.toPath());
        for (File folder : folderList) {
            jarMerger.addDirectory(folder.toPath());
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

    List<File> result = new ArrayList<>();
    File maindexJar = new File(dir, DexMerger.FASTMAINDEX_JAR + ".jar");

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));

    //First order
    Collections.sort(jarList, new NameComparator());

    for (File jar : jarList) {
        File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar");

        result.add(outJar);
        JarFile jarFile = new JarFile(jar);
        JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));
        Enumeration<JarEntry> jarFileEntries = jarFile.entries();

        List<String> pathList = new ArrayList<>();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
                pathList.add(pathName);
            }
        }

        if (!pathList.isEmpty()) {
            jarFileEntries = jarFile.entries();
            while (jarFileEntries.hasMoreElements()) {
                JarEntry ze = jarFileEntries.nextElement();
                String pathName = ze.getName();
                if (!pathList.contains(pathName)) {
                    copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
                }
            }
        }

        jarFile.close();
        IOUtils.closeQuietly(jos);

        if (pathList.isEmpty()) {
            FileUtils.copyFile(jar, outJar);
        }
        if (!appVariantContext.getAtlasExtension().getTBuildConfig().isFastProguard() && files.size() == 1) {
            JarUtils.splitMainJar(result, outJar, 1, MAX_CLASSES);
        }
    }

    IOUtils.closeQuietly(mainJarOuputStream);

    Collections.sort(result, new NameComparator());

    result.add(0, maindexJar);

    return result;
}