Example usage for java.util.zip ZipOutputStream DEFLATED

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

Introduction

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

Prototype

int DEFLATED

To view the source code for java.util.zip ZipOutputStream DEFLATED.

Click Source Link

Document

Compression method for compressed (DEFLATED) entries.

Usage

From source file:it.geosolutions.mariss.wps.ppio.OutputResourcesPPIO.java

@Override
public void encode(Object value, OutputStream os) throws Exception {

    ZipOutputStream zos = null;/*from w ww .j  av a2s . co m*/
    try {
        OutputResource or = (OutputResource) value;

        zos = new ZipOutputStream(os);
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.DEFAULT_COMPRESSION);

        Iterator<File> iter = or.getDeletableResourcesIterator();
        while (iter.hasNext()) {

            File tmp = iter.next();
            if (!tmp.exists() || !tmp.canRead() || !tmp.canWrite()) {
                LOGGER.warning("Skip Deletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

            if (!tmp.delete()) {
                LOGGER.warning("File '" + tmp.getName() + "' cannot be deleted...");
            }
        }
        iter = null;

        Iterator<File> iter2 = or.getUndeletableResourcesIterator();
        while (iter2.hasNext()) {

            File tmp = iter2.next();
            if (!tmp.exists() || !tmp.canRead()) {
                LOGGER.warning("Skip Undeletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

        }
    } finally {
        try {
            zos.close();
        } catch (IOException e) {
            LOGGER.severe(e.getMessage());
        }
    }
}

From source file:com.l2jfree.gameserver.util.DatabaseBackupManager.java

public static void makeBackup() {
    File f = new File(Config.DATAPACK_ROOT, Config.DATABASE_BACKUP_SAVE_PATH);
    if (!f.mkdirs() && !f.exists()) {
        _log.warn("Could not create folder " + f.getAbsolutePath());
        return;/*  w w  w.  j a  v a 2  s. c o  m*/
    }

    _log.info("DatabaseBackupManager: backing up `" + Config.DATABASE_BACKUP_DATABASE_NAME + "`...");

    Process run = null;
    try {
        run = Runtime.getRuntime().exec("mysqldump" + " --user=" + Config.DATABASE_LOGIN + " --password="
                + Config.DATABASE_PASSWORD
                + " --compact --complete-insert --default-character-set=utf8 --extended-insert --lock-tables --quick --skip-triggers "
                + Config.DATABASE_BACKUP_DATABASE_NAME, null, new File(Config.DATABASE_BACKUP_MYSQLDUMP_PATH));
    } catch (Exception e) {
    } finally {
        if (run == null) {
            _log.warn("Could not execute mysqldump!");
            return;
        }
    }

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        Date time = new Date();

        File bf = new File(f, sdf.format(time) + (Config.DATABASE_BACKUP_COMPRESSION ? ".zip" : ".sql"));
        if (!bf.createNewFile())
            throw new IOException("Cannot create backup file: " + bf.getCanonicalPath());
        InputStream input = run.getInputStream();
        OutputStream out = new FileOutputStream(bf);
        if (Config.DATABASE_BACKUP_COMPRESSION) {
            ZipOutputStream dflt = new ZipOutputStream(out);
            dflt.setMethod(ZipOutputStream.DEFLATED);
            dflt.setLevel(Deflater.BEST_COMPRESSION);
            dflt.setComment("L2JFree Schema Backup Utility\r\n\r\nBackup date: "
                    + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS z").format(time));
            dflt.putNextEntry(new ZipEntry(Config.DATABASE_BACKUP_DATABASE_NAME + ".sql"));
            out = dflt;
        }

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

            written += read;
        }
        input.close();
        out.close();

        if (written == 0) {
            bf.delete();
            BufferedReader br = new BufferedReader(new InputStreamReader(run.getErrorStream()));
            String line;
            while ((line = br.readLine()) != null)
                _log.warn("DatabaseBackupManager: " + line);
            br.close();
        } else
            _log.info("DatabaseBackupManager: Schema `" + Config.DATABASE_BACKUP_DATABASE_NAME
                    + "` backed up successfully in " + (System.currentTimeMillis() - time.getTime()) / 1000
                    + " s.");

        run.waitFor();
    } catch (Exception e) {
        _log.warn("DatabaseBackupManager: Could not make backup: ", e);
    }
}

From source file:org.xdi.util.io.ResponseHelper.java

public static ZipOutputStream createZipStream(OutputStream output, String comment) {
    ZipOutputStream zos = new ZipOutputStream(output);

    zos.setComment("Shibboleth2 SP configuration files");
    zos.setMethod(ZipOutputStream.DEFLATED);
    zos.setLevel(Deflater.DEFAULT_COMPRESSION);

    return zos;/*from  w ww  .  ja  v  a 2  s. c om*/
}

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

/**
 * pack a segment into the zip//  w  w w .ja  v a  2  s  .  c  o  m
 * @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:org.junitee.testngee.servlet.TestNGEEServlet.java

private void zipOutputDir(File outdir, ServletOutputStream outputStream) throws IOException {
    ZipOutputStream out = new ZipOutputStream(outputStream);
    File[] files = outdir.listFiles();

    out.setMethod(ZipOutputStream.DEFLATED);

    for (int i = 0; i < files.length; i++) {
        File file = files[i];/*from   w ww  . jav a 2 s  .  co  m*/

        if (!file.isDirectory()) {
            ZipEntry zipEntry = new ZipEntry(file.getName());
            zipEntry.setSize(file.length());
            zipEntry.setTime(file.lastModified());

            out.putNextEntry(zipEntry);

            FileInputStream in = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int r;

            while ((r = in.read(buffer)) > 0) {
                out.write(buffer, 0, r);
            }
            in.close();
            out.closeEntry();
        }
    }
    out.close();
}

From source file:jobhunter.persistence.Persistence.java

private void zip(final File file) {

    try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(file))) {
        l.debug("Generating JHF file");
        zout.setMethod(ZipOutputStream.DEFLATED);
        zout.setLevel(9);//from   www.  ja  va  2s  . com

        l.debug("Inserting profile XML");
        zout.putNextEntry(new ZipEntry("profile.xml"));
        xstream.toXML(ProfileRepository.getProfile(), zout);

        l.debug("Inserting subscriptions XML");
        zout.putNextEntry(new ZipEntry("subscriptions.xml"));
        xstream.toXML(SubscriptionRepository.getSubscriptions(), zout);

        updateLastMod(file);
    } catch (IOException e) {
        l.error("Failed to generate file", e);
    }

}

From source file:com.diffplug.gradle.ZipMisc.java

/**
 * Creates a single-entry zip file./*from www  .jav a2 s  .co m*/
 * 
 * @param input               an uncompressed file
 * @param pathWithinArchive      the path within the archive
 * @param output            the new zip file it will be compressed into
 */
public static void zip(File input, String pathWithinArchive, File output) throws IOException {
    try (ZipOutputStream zipStream = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(output)))) {
        zipStream.setMethod(ZipOutputStream.DEFLATED);
        zipStream.setLevel(9);
        zipStream.putNextEntry(new ZipEntry(pathWithinArchive));
        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(input))) {
            copy(inputStream, zipStream);
        }
    }
}

From source file:org.fusesource.meshkeeper.util.internal.FileSupport.java

public static void jar(File source, File target) throws IOException {
    ZipOutputStream os = new ZipOutputStream(new FileOutputStream(target));
    try {/*w w  w  .ja  va2  s. com*/
        os.setMethod(ZipOutputStream.DEFLATED);
        os.setLevel(5);
        recusiveJar(os, source, null);
    } catch (IOException ioe) {
        IOException nioe = new IOException("Error jarring " + source);
        nioe.initCause(ioe);
        throw nioe;
    } finally {
        close(os);
    }
}

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.
 * /* w w w. j a v  a2  s . co 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.sigmah.server.file.impl.BackupArchiveJob.java

/**
 * {@inheritDoc}//w w  w  .  j ava  2 s .  c  o m
 */
@Override
public void run() {

    final Path tempArchiveFile = arguments.tempArchiveFile;
    final Path finalArchiveFile = arguments.finalArchiveFile;

    try (final ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(
            Files.newOutputStream(tempArchiveFile))) {

        zipOutputStream.setMethod(ZipOutputStream.DEFLATED);
        zipOutputStream.setLevel(Deflater.BEST_COMPRESSION);

        final RepositoryElement repository = buildOrgUnitRepository(arguments.backup, arguments.userId);
        repository.setName("");

        zipRepository(repository, zipOutputStream, "");

        // TODO Delete existing previous organization file(s).

        // Renames temporary '.tmp' file to complete '.zip' file.
        Files.move(tempArchiveFile, finalArchiveFile, StandardCopyOption.REPLACE_EXISTING);

    } catch (final Throwable t) {

        if (LOG.isErrorEnabled()) {
            LOG.error("An error occurred during backup archive generation process.", t);
        }

        try {

            Files.deleteIfExists(tempArchiveFile);
            Files.deleteIfExists(finalArchiveFile);

        } catch (final IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("An error occurred while deleting archive error file.", e);
            }
        }
    }
}