Example usage for java.util.zip ZipOutputStream setLevel

List of usage examples for java.util.zip ZipOutputStream setLevel

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream setLevel.

Prototype

public void setLevel(int level) 

Source Link

Document

Sets the compression level for subsequent entries which are DEFLATED.

Usage

From source file:org.apache.oozie.tools.OozieDBExportCLI.java

private static void queryAllDBTables(String filename) throws StoreException, IOException {

    EntityManager manager = null;/*from  w  ww .ja va2 s. co m*/
    ZipOutputStream zos = null;
    File file = null;
    try {
        file = new File(filename);
        zos = new ZipOutputStream(new FileOutputStream(file));
        zos.setLevel(1);
        manager = Services.get().get(JPAService.class).getEntityManager();
        manager.setFlushMode(FlushModeType.COMMIT);

        int infoSize = exportTableToJSON(manager.createNativeQuery(GET_DB_VERSION), zos, OOZIEDB_SYS_INFO_JSON);
        System.out.println(infoSize + " rows exported from OOZIE_SYS");

        int wfjSize = exportTableToJSON(manager.createQuery(GET_WORKFLOW_JOBS), zos, OOZIEDB_WF_JSON);
        System.out.println(wfjSize + " rows exported from WF_JOBS");

        int wfaSize = exportTableToJSON(manager.createQuery(GET_WORKFLOW_ACTIONS), zos, OOZIEDB_AC_JSON);
        System.out.println(wfaSize + " rows exported from WF_ACTIONS");

        int cojSize = exportTableToJSON(manager.createQuery(GET_COORD_JOBS), zos, OOZIEDB_CJ_JSON);
        System.out.println(cojSize + " rows exported from COORD_JOBS");

        int coaSize = exportTableToJSON(manager.createQuery(GET_COORD_ACTIONS), zos, OOZIEDB_CA_JSON);
        System.out.println(coaSize + " rows exported from COORD_ACTIONS");

        int bnjSize = exportTableToJSON(manager.createQuery(GET_BUNDLE_JOBS), zos, OOZIEDB_BNJ_JSON);
        System.out.println(bnjSize + " rows exported from BUNDLE_JOBS");

        int bnaSize = exportTableToJSON(manager.createQuery(GET_BUNDLE_ACIONS), zos, OOZIEDB_BNA_JSON);
        System.out.println(bnaSize + " rows exported from BUNDLE_ACTIONS");

        int slaRegSize = exportTableToJSON(manager.createQuery(GET_SLA_REGISTRATIONS), zos,
                OOZIEDB_SLAREG_JSON);
        System.out.println(slaRegSize + " rows exported from SLA_REGISTRATION");

        int ssSize = exportTableToJSON(manager.createQuery(GET_SLA_SUMMARYS), zos, OOZIEDB_SLASUM_JSON);
        System.out.println(ssSize + " rows exported from SLA_SUMMARY");

    } catch (Exception e) {
        System.err.println("Error during dump creation: " + e.getMessage());
        System.err.println();
        e.printStackTrace(System.err);
        System.err.println();
        if (file != null) {
            file.delete();
        }
        System.exit(1);
    } finally {
        IOUtils.closeSafely(zos);
        if (manager != null) {
            manager.close();
        }
    }
}

From source file:de.fu_berlin.inf.dpp.core.zip.FileZipper.java

private static void internalZipFiles(List<FileWrapper> files, File archive, boolean compress,
        boolean includeDirectories, long totalSize, ZipListener listener)
        throws IOException, OperationCanceledException {

    byte[] buffer = new byte[BUFFER_SIZE];

    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(archive), BUFFER_SIZE);

    ZipOutputStream zipStream = new ZipOutputStream(outputStream);

    zipStream.setLevel(compress ? Deflater.DEFAULT_COMPRESSION : Deflater.NO_COMPRESSION);

    boolean cleanup = true;
    boolean isCanceled = false;

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();/* ww w .  j  ava  2s.  c om*/

    long totalRead = 0L;

    try {
        for (FileWrapper file : files) {
            String entryName = includeDirectories ? file.getPath() : file.getName();

            if (listener != null) {
                isCanceled = listener.update(file.getPath());
            }

            log.trace("compressing file: " + entryName);

            zipStream.putNextEntry(new ZipEntry(entryName));

            InputStream in = null;

            try {
                int read = 0;
                in = file.getInputStream();
                while (-1 != (read = in.read(buffer))) {

                    if (isCanceled) {
                        throw new OperationCanceledException(
                                "compressing of file '" + entryName + "' was canceled");
                    }

                    zipStream.write(buffer, 0, read);

                    totalRead += read;

                    if (listener != null) {
                        listener.update(totalRead, totalSize);
                    }

                }
            } finally {
                IOUtils.closeQuietly(in);
            }
            zipStream.closeEntry();
        }
        cleanup = false;
    } finally {
        IOUtils.closeQuietly(zipStream);
        if (cleanup && archive != null && archive.exists() && !archive.delete()) {
            log.warn("could not delete archive file: " + archive);
        }
    }

    stopWatch.stop();

    log.debug(String.format("created archive %s I/O: [%s]", archive.getAbsolutePath(),
            CoreUtils.throughput(archive.length(), stopWatch.getTime())));

}

From source file:org.roda_project.commons_ip.utils.ZIPUtils.java

public static void zip(Map<String, ZipEntryInfo> files, OutputStream out, SIP sip, boolean createSipIdFolder,
        boolean isCompressed) throws IOException, InterruptedException, IPException {
    ZipOutputStream zos = new ZipOutputStream(out);
    if (isCompressed) {
        zos.setLevel(Deflater.DEFAULT_COMPRESSION);
    } else {//from  w w w .j  a  v  a  2  s.co  m
        zos.setLevel(Deflater.NO_COMPRESSION);
    }

    Set<String> nonMetsChecksumAlgorithms = new TreeSet<>();
    nonMetsChecksumAlgorithms.add(IPConstants.CHECKSUM_ALGORITHM);
    Set<String> metsChecksumAlgorithms = new TreeSet<>();
    metsChecksumAlgorithms.addAll(nonMetsChecksumAlgorithms);
    metsChecksumAlgorithms.addAll(sip.getExtraChecksumAlgorithms());

    int i = 0;
    for (ZipEntryInfo file : files.values()) {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        file.prepareEntryforZipping();

        LOGGER.debug("Zipping file {}", file.getFilePath());
        ZipEntry entry;
        if (createSipIdFolder) {
            entry = new ZipEntry(sip.getId() + "/" + file.getName());
        } else {
            entry = new ZipEntry(file.getName());
        }

        zos.putNextEntry(entry);
        InputStream inputStream = Files.newInputStream(file.getFilePath());

        try {
            Map<String, String> checksums;
            if (file instanceof METSZipEntryInfo) {
                checksums = calculateChecksums(Optional.of(zos), inputStream, metsChecksumAlgorithms);
                METSZipEntryInfo metsEntry = (METSZipEntryInfo) file;
                metsEntry.setChecksums(checksums);
                metsEntry.setSize(metsEntry.getFilePath().toFile().length());
            } else {
                checksums = calculateChecksums(Optional.of(zos), inputStream, nonMetsChecksumAlgorithms);
            }

            LOGGER.debug("Done zipping file");
            String checksum = checksums.get(IPConstants.CHECKSUM_ALGORITHM);
            String checksumType = IPConstants.CHECKSUM_ALGORITHM;
            file.setChecksum(checksum);
            file.setChecksumAlgorithm(checksumType);
            if (file instanceof METSFileTypeZipEntryInfo) {
                METSFileTypeZipEntryInfo f = (METSFileTypeZipEntryInfo) file;
                f.getMetsFileType().setCHECKSUM(checksum);
                f.getMetsFileType().setCHECKSUMTYPE(checksumType);
            } else if (file instanceof METSMdRefZipEntryInfo) {
                METSMdRefZipEntryInfo f = (METSMdRefZipEntryInfo) file;
                f.getMetsMdRef().setCHECKSUM(checksum);
                f.getMetsMdRef().setCHECKSUMTYPE(checksumType);
            }
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Error while zipping files", e);
        }
        zos.closeEntry();
        inputStream.close();
        i++;

        sip.notifySipBuildPackagingCurrentStatus(i);
    }

    zos.close();
    out.close();
}

From source file:rega.genotype.ui.util.GenotypeLib.java

public static void zip(File dir, OutputStream os) {
    byte[] buffer = new byte[1024 * 1024];

    try {// w  w w .ja va 2s.  co  m

        ZipOutputStream out = new ZipOutputStream(os);

        out.setLevel(Deflater.DEFAULT_COMPRESSION);

        for (File f : dir.listFiles()) {
            FileInputStream in = new FileInputStream(f);

            //new entry, relative path
            out.putNextEntry(
                    new ZipEntry(f.getAbsolutePath().replace(dir.getAbsolutePath() + File.separatorChar, "")));

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

            out.closeEntry();
            in.close();
        }
        out.close();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.sakaiproject.search.util.FileUtils.java

/**
 * pack a segment into the zip/*from   ww  w .j  a  v  a2s . com*/
 * @param compress 
 * 
 * @param addsi
 * @return
 * @throws IOException
 */
public static void pack(File source, final String basePath, final String replacePath, OutputStream output,
        boolean compress) throws IOException {
    log.debug("Packing " + source + " repacing " + basePath + " with " + replacePath);
    final ZipOutputStream zout = new ZipOutputStream(output);
    if (compress) {
        zout.setLevel(ZipOutputStream.DEFLATED);
    } else {
        zout.setLevel(ZipOutputStream.STORED);
    }
    final byte[] buffer = new byte[1024 * 100];
    try {
        recurse(source, new RecurseAction() {

            public void doFile(File file) throws IOException {
                if (!file.isDirectory()) {
                    log.debug("               Add " + file.getPath());
                    addSingleFile(basePath, replacePath, file, zout, buffer);
                } else {
                    log.debug("              Ignore " + file.getPath());
                }
            }

            public void doBeforeFile(File f) {
            }

            public void doAfterFile(File f) {
            }

        });
    } finally {
        zout.flush();
        try {
            zout.close();
        } catch (Exception e) {
            log.warn("Exception closing output zip", e);
        }
    }
}

From source file:com.edgenius.core.util.ZipFileUtil.java

/**
 * Creates a ZIP file and places it in the current working directory. The zip file is compressed
 * at the default compression level of the Deflater.
 * /*from  ww  w . j av a 2 s.  c  o m*/
 * @param listToZip. Key is file or directory, value is parent directory which will remove from given file/directory because 
 * compression only save relative directory.  For example, c:\geniuswiki\data\repository\somefile, if value is c:\geniuswiki, then only 
 * \data\repository\somefile will be saved.  It is very important, the value must be canonical path, ie, c:\my document\geniuswiki, 
 * CANNOT like this "c:\my doc~1\" 
 * 
 * 
 */
public static void createZipFile(String zipFileName, Map<File, String> listToZip, boolean withEmptyDir)
        throws ZipFileUtilException {
    ZipOutputStream zop = null;
    try {
        zop = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
        zop.setMethod(ZipOutputStream.DEFLATED);
        zop.setLevel(Deflater.DEFAULT_COMPRESSION);

        for (Entry<File, String> entry : listToZip.entrySet()) {
            File file = entry.getKey();
            if (!file.exists()) {
                log.warn("Unable to find file " + file + " to zip");
                continue;
            }
            if (file.isDirectory()) {
                Collection<File> list = FileUtils.listFiles(file, null, true);
                for (File src : list) {
                    addEntry(zop, src, createRelativeDir(src.getCanonicalPath(), entry.getValue()));
                }
                if (withEmptyDir) {
                    final List<File> emptyDirs = new ArrayList<File>();
                    if (file.list().length == 0) {
                        emptyDirs.add(file);
                    } else {
                        //I just don't know how quickly to find out all empty sub directories recursively. so use below hack:
                        FileUtils.listFiles(file, FileFilterUtils.falseFileFilter(), new IOFileFilter() {
                            //JDK1.6 @Override
                            public boolean accept(File f) {
                                if (!f.isDirectory())
                                    return false;

                                int size = f.listFiles().length;
                                if (size == 0) {
                                    emptyDirs.add(f);
                                }
                                return true;
                            }

                            //JDK1.6 @Override
                            public boolean accept(File arg0, String arg1) {
                                return true;
                            }
                        });
                    }
                    for (File src : emptyDirs) {
                        addEntry(zop, null, createRelativeDir(src.getCanonicalPath(), entry.getValue()));
                    }
                }
            } else {
                addEntry(zop, file, createRelativeDir(file.getCanonicalPath(), entry.getValue()));
            }

        }
    } catch (IOException e1) {
        throw new ZipFileUtilException(
                "An error has occurred while trying to zip the files. Error message is: ", e1);
    } finally {
        try {
            if (zop != null)
                zop.close();
        } catch (Exception e) {
        }
    }

}

From source file:org.openmicroscopy.shoola.util.file.IOUtil.java

/**
 * Makes the zip.//from   www.  j  av a  2s  .  c  o m
 * 
 * @param zipName The name of the zip.
 * @param compress Pass <code>true</code> to compress,
 * <code>false</code> otherwise.
 */
public static File zipDirectory(File zip, boolean compress) throws Exception {
    if (zip == null)
        throw new IllegalArgumentException("No name specified.");
    if (!zip.isDirectory() || !zip.exists())
        throw new IllegalArgumentException("Not a valid directory.");
    //Check if the name already has the extension
    String extension = FilenameUtils.getExtension(zip.getName());
    String name = zip.getName();
    if (StringUtils.isEmpty(extension) || !ZIP_EXTENSION.equals("." + extension)) {
        name += ZIP_EXTENSION;
    }
    File file = new File(zip.getParentFile(), name);
    ZipOutputStream out = null;
    try {
        out = new ZipOutputStream(new FileOutputStream(file));
        if (!compress)
            out.setLevel(ZipOutputStream.STORED);
        zipDir(zip, out, null);
    } catch (Exception e) {
        throw new Exception("Cannot create the zip.", e);
    } finally {
        if (out != null)
            out.close();
    }
    return file;
}

From source file:com.l2jfree.sql.L2DataSource.java

protected static final boolean writeBackup(String databaseName, InputStream in) throws IOException {
    FileUtils.forceMkdir(new File("backup/database"));

    final Date time = new Date();

    final L2TextBuilder tb = new L2TextBuilder();
    tb.append("backup/database/DatabaseBackup_");
    tb.append(new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()));
    tb.append("_uptime-").append(L2Config.getShortUptime());
    tb.append(".zip");

    final File backupFile = new File(tb.moveToString());

    int written = 0;
    ZipOutputStream out = null;
    try {//from w  w w . j  a v  a  2s . co m
        out = new ZipOutputStream(new FileOutputStream(backupFile));
        out.setMethod(ZipOutputStream.DEFLATED);
        out.setLevel(Deflater.BEST_COMPRESSION);
        out.setComment("L2jFree Schema Backup Utility\r\n\r\nBackup date: "
                + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS z").format(new Date()));
        out.putNextEntry(new ZipEntry(databaseName + ".sql"));

        byte[] buf = new byte[4096];
        for (int read; (read = in.read(buf)) != -1;) {
            out.write(buf, 0, read);

            written += read;
        }
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }

    if (written == 0) {
        backupFile.delete();
        return false;
    }

    _log.info("DatabaseBackupManager: Database `" + databaseName + "` backed up successfully in "
            + (System.currentTimeMillis() - time.getTime()) / 1000 + " s.");
    return true;
}

From source file:org.apache.jetspeed.portlets.site.PortalSiteManagerUtil.java

private static boolean zipObject(String sourcePath, String target) {
    FileOutputStream fos = null;//  w w w .j a  v  a2  s  .  c om
    ZipOutputStream cpZipOutputStream = null;

    try {
        File cpFile = new File(sourcePath);
        if (!cpFile.isDirectory()) {
            return false;
        }
        fos = new FileOutputStream(target);
        cpZipOutputStream = new ZipOutputStream(fos);
        cpZipOutputStream.setLevel(9);
        zipFiles(cpFile, sourcePath, cpZipOutputStream);
        cpZipOutputStream.finish();
    } catch (Exception e) {
        logger.error("Unexpected exception during writing to zip output stream.", e);
        return false;
    } finally {
        if (cpZipOutputStream != null) {
            try {
                cpZipOutputStream.close();
            } catch (Exception ce) {
            }
        }

        if (fos != null) {
            try {
                fos.close();
            } catch (Exception ce) {
            }
        }
    }
    return true;
}

From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java

/**
 * saves a sound package with all meta information and audio files to a ZIP
 * file and creates the security tokens.
 *
 * @param packageFile the zip file, where the soundpackage should be stored
 * @param soundPackage the sound package info
 * @throws com.dreikraft.infactory.sound.SoundPackageException encapsulates
 * all low level (IO) exceptions/*from  w  ww.j  ava2s.  co m*/
 */
public static void exportSoundPackage(final File packageFile, final SoundPackage soundPackage)
        throws SoundPackageException {

    if (packageFile == null) {
        throw new SoundPackageException(new IllegalArgumentException("null package file"));
    }

    if (packageFile.delete()) {
        log.info("successfully deleted file: " + packageFile.getAbsolutePath());
    }

    ZipOutputStream out = null;
    InputStream in = null;
    try {
        out = new ZipOutputStream(new FileOutputStream(packageFile));
        out.setLevel(9);

        // write package info
        writePackageInfoZipEntry(soundPackage, out);

        // create path entries
        ZipEntry soundDir = new ZipEntry(SOUNDS_PATH_PREFIX + SL);
        out.putNextEntry(soundDir);
        out.flush();
        out.closeEntry();

        // write files
        for (Sound sound : soundPackage.getSounds()) {
            File axboFile = new File(sound.getAxboFile().getPath());
            in = new FileInputStream(axboFile);
            writeZipEntry(SOUNDS_PATH_PREFIX + SL + axboFile.getName(), out, in);
            in.close();
        }
    } catch (FileNotFoundException ex) {
        throw new SoundPackageException(ex);
    } catch (IOException ex) {
        throw new SoundPackageException(ex);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ex) {
                log.error("failed to close ZipOutputStream", ex);
            }
        }
        try {
            if (in != null)
                in.close();
        } catch (IOException ex) {
            log.error("failed to close FileInputStream", ex);
        }
    }
}