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.olat.ims.qti.qpool.QTIPoolWordExport.java

@Override
public void prepare(HttpServletResponse hres) {
    try {/* w ww .  j  a  va 2  s  .c  o  m*/
        hres.setCharacterEncoding(encoding);
    } catch (Exception e) {
        log.error("", e);
    }

    ZipOutputStream zout = null;
    try {
        String label = "Items_Export";
        String secureLabel = StringHelper.transformDisplayNameToFileSystemName(label);

        List<Long> itemKeys = new ArrayList<Long>();
        for (QuestionItemShort item : items) {
            itemKeys.add(item.getKey());
        }

        List<QuestionItemFull> fullItems = questionItemDao.loadByIds(itemKeys);

        String file = secureLabel + ".zip";
        hres.setHeader("Content-Disposition",
                "attachment; filename*=UTF-8''" + StringHelper.urlEncodeUTF8(file));
        hres.setHeader("Content-Description", StringHelper.urlEncodeUTF8(label));

        zout = new ZipOutputStream(hres.getOutputStream());
        zout.setLevel(9);

        ZipEntry test = new ZipEntry(secureLabel + ".docx");
        zout.putNextEntry(test);
        exportTest(fullItems, zout, false);
        zout.closeEntry();

        ZipEntry responses = new ZipEntry(secureLabel + "_responses.docx");
        zout.putNextEntry(responses);
        exportTest(fullItems, zout, true);
        zout.closeEntry();
    } catch (Exception e) {
        log.error("", e);
    } finally {
        IOUtils.closeQuietly(zout);
    }
}

From source file:net.rptools.lib.io.PackedFile.java

public void save() throws IOException {
    CodeTimer saveTimer;// w  w w .j  ava2 s. c  om

    if (!dirty) {
        return;
    }
    saveTimer = new CodeTimer("PackedFile.save");
    saveTimer.setEnabled(log.isDebugEnabled());

    InputStream is = null;

    // Create the new file
    File newFile = new File(tmpDir, new GUID() + ".pak");
    ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)));
    zout.setLevel(Deflater.BEST_COMPRESSION); // fast compression
    try {
        saveTimer.start(CONTENT_FILE);
        if (hasFile(CONTENT_FILE)) {
            zout.putNextEntry(new ZipEntry(CONTENT_FILE));
            is = getFileAsInputStream(CONTENT_FILE); // When copying, always use an InputStream
            IOUtils.copy(is, zout);
            IOUtils.closeQuietly(is);
            zout.closeEntry();
        }
        saveTimer.stop(CONTENT_FILE);

        saveTimer.start(PROPERTY_FILE);
        if (getPropertyMap().isEmpty()) {
            removeFile(PROPERTY_FILE);
        } else {
            zout.putNextEntry(new ZipEntry(PROPERTY_FILE));
            xstream.toXML(getPropertyMap(), zout);
            zout.closeEntry();
        }
        saveTimer.stop(PROPERTY_FILE);

        // Now put each file
        saveTimer.start("addFiles");
        addedFileSet.remove(CONTENT_FILE);
        for (String path : addedFileSet) {
            zout.putNextEntry(new ZipEntry(path));
            is = getFileAsInputStream(path); // When copying, always use an InputStream
            IOUtils.copy(is, zout);
            IOUtils.closeQuietly(is);
            zout.closeEntry();
        }
        saveTimer.stop("addFiles");

        // Copy the rest of the zip entries over
        saveTimer.start("copyFiles");
        if (file.exists()) {
            Enumeration<? extends ZipEntry> entries = zFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory() && !addedFileSet.contains(entry.getName())
                        && !removedFileSet.contains(entry.getName()) && !CONTENT_FILE.equals(entry.getName())
                        && !PROPERTY_FILE.equals(entry.getName())) {
                    //                  if (entry.getName().endsWith(".png") ||
                    //                        entry.getName().endsWith(".gif") ||
                    //                        entry.getName().endsWith(".jpeg"))
                    //                     zout.setLevel(Deflater.NO_COMPRESSION); // none needed for images as they are already compressed
                    //                  else
                    //                     zout.setLevel(Deflater.BEST_COMPRESSION); // fast compression
                    zout.putNextEntry(entry);
                    is = getFileAsInputStream(entry.getName()); // When copying, always use an InputStream
                    IOUtils.copy(is, zout);
                    IOUtils.closeQuietly(is);
                    zout.closeEntry();
                } else if (entry.isDirectory()) {
                    zout.putNextEntry(entry);
                    zout.closeEntry();
                }
            }
        }
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        zFile = null;
        saveTimer.stop("copyFiles");

        saveTimer.start("close");
        IOUtils.closeQuietly(zout);
        zout = null;
        saveTimer.stop("close");

        // Backup the original
        saveTimer.start("backup");
        File backupFile = new File(tmpDir, new GUID() + ".mv");
        if (file.exists()) {
            backupFile.delete(); // Always delete the old backup file first; renameTo() is very platform-dependent
            if (!file.renameTo(backupFile)) {
                saveTimer.start("backup file");
                FileUtil.copyFile(file, backupFile);
                file.delete();
                saveTimer.stop("backup file");
            }
        }
        saveTimer.stop("backup");

        saveTimer.start("finalize");
        // Finalize
        if (!newFile.renameTo(file)) {
            saveTimer.start("backup newFile");
            FileUtil.copyFile(newFile, file);
            saveTimer.stop("backup newFile");
        }
        if (backupFile.exists())
            backupFile.delete();
        saveTimer.stop("finalize");

        dirty = false;
    } finally {
        saveTimer.start("cleanup");
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        if (newFile.exists())
            newFile.delete();
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(zout);
        saveTimer.stop("cleanup");

        if (log.isDebugEnabled())
            log.debug(saveTimer);
        saveTimer = null;
    }
}

From source file:com.lizardtech.expresszip.model.Job.java

private void writeZipFile(File baseDir, File archive, List<String> files)
        throws FileNotFoundException, IOException {
    FilterOutputStream out = null;
    ZipOutputStream stream = new ZipOutputStream(new FileOutputStream(archive));
    stream.setLevel(Deflater.DEFAULT_COMPRESSION);
    out = stream;//from   w w w .  ja va  2 s .c  om

    byte data[] = new byte[18024];

    for (String f : files) {
        logger.info(String.format("Writing %s to ZIP archive %s", f, archive));
        ((ZipOutputStream) out).putNextEntry(new ZipEntry(f));

        BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(baseDir, f)));

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

        out.flush();
        in.close();
    }

    out.close();
}

From source file:org.panbox.desktop.linux.dbus.PanboxInterfaceImpl.java

@Override
public byte backupIdentity() {
    logger.debug("[DBUS] backupIdentity()");

    byte ret = StatusCode.DBUS_OK;

    File confDir = new File(Settings.getInstance().getConfDir());
    String backupPath = confDir.getParent() + File.separator + ".pbbackup";
    File backupDir = new File(backupPath);

    if (!backupDir.exists()) {
        backupDir.mkdir();/*from w ww  .  j ava  2 s  . c o  m*/
    }

    Calendar cal = Calendar.getInstance();

    String datetime = String.valueOf(cal.get(Calendar.YEAR)) + String.valueOf(cal.get(Calendar.MONTH))
            + String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) + "_" + String.valueOf(cal.get(Calendar.MINUTE))
            + "-" + String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) + "-"
            + String.valueOf(cal.get(Calendar.SECOND));
    String outputFileName = backupDir.getPath() + File.separator + datetime + ".pbbak";

    List<String> filesToZip = new ArrayList<String>();

    try {
        IShareManager shareMgr = ShareManagerImpl.getInstance();

        File[] confFiles = confDir.listFiles();
        for (File f : confFiles) {
            filesToZip.add(f.getAbsolutePath());
        }

        List<String> installedShareNames = shareMgr.getInstalledShares();

        List<PanboxShare> installedShares = new ArrayList<PanboxShare>();
        for (String shareName : installedShareNames) {
            PanboxShare share = shareMgr.getShareForName(shareName);
            installedShares.add(share);
        }

        for (PanboxShare share : installedShares) {
            File f = new File(share.getPath() + ".panbox/");
            File[] files = f.listFiles();
            for (File file : files) {
                filesToZip.add(file.getAbsolutePath());
            }
        }

        FileOutputStream fos = new FileOutputStream(outputFileName);
        ZipOutputStream zos = new ZipOutputStream(fos);
        zos.setLevel(9);

        for (String ftz : filesToZip) {

            File fileToZip = new File(ftz);

            if (fileToZip.exists()) {
                ZipEntry ze = new ZipEntry(fileToZip.getAbsolutePath());
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(fileToZip.getPath());

                int len;
                byte buffer[] = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
            }
        }
        zos.finish();
        fos.close();

    } catch (Exception e) {
        ret = StatusCode.getAndLog(logger, e);
    }

    return ret;
}

From source file:fr.smile.alfresco.module.panier.scripts.SmilePanierExportZipWebScript.java

@Override
public void execute(WebScriptRequest request, WebScriptResponse res) throws IOException {

    String userName = AuthenticationUtil.getFullyAuthenticatedUser();

    PersonService personService = services.getPersonService();

    NodeRef userNodeRef = personService.getPerson(userName);

    MimetypeService mimetypeService = services.getMimetypeService();
    FileFolderService fileFolderService = services.getFileFolderService();

    Charset archiveEncoding = Charset.forName("ISO-8859-1");

    String encoding = request.getParameter("encoding");

    if (StringUtils.isNotEmpty(encoding)) {
        archiveEncoding = Charset.forName(encoding);
    }//from   www . j a  v a2  s. c  om

    ZipOutputStream fileZip = new ZipOutputStream(res.getOutputStream(), archiveEncoding);
    String folderName = "mon_panier";
    try {

        String zipFileExtension = "." + mimetypeService.getExtension(MimetypeMap.MIMETYPE_ZIP);

        res.setContentType(MimetypeMap.MIMETYPE_ZIP);

        res.setHeader("Content-Transfer-Encoding", "binary");
        res.addHeader("Content-Disposition",
                "attachment;filename=\"" + normalizeZipFileName(folderName) + zipFileExtension + "\"");

        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        res.setHeader("Expires", "0");

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

        String archiveRootPath = folderName + "/";

        List<NodeRef> list = smilePanierService.getSelection(userNodeRef);
        List<FileInfo> filesInfos = new ArrayList<FileInfo>();
        for (int i = 0; i < list.size(); i++) {
            FileInfo fileInfo = fileFolderService.getFileInfo(list.get(i));
            filesInfos.add(fileInfo);
        }

        for (FileInfo file : filesInfos) {
            addEntry(file, fileZip, archiveRootPath);
        }
        fileZip.closeEntry();

    } catch (Exception e) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Erreur exportation Zip", e);
    } finally {
        fileZip.close();
    }

}

From source file:eu.europa.esig.dss.asic.signature.ASiCService.java

private void storeSignedFiles(final DSSDocument detachedDocument, final ZipOutputStream outZip)
        throws IOException {
    DSSDocument currentDetachedDocument = detachedDocument;
    do {/* ww  w  . j a v  a 2 s  .c  o m*/

        final String detachedDocumentName = currentDetachedDocument.getName();
        final String name = detachedDocumentName != null ? detachedDocumentName : ZIP_ENTRY_DETACHED_FILE;
        final ZipEntry entryDocument = new ZipEntry(name);
        outZip.setLevel(ZipEntry.DEFLATED);
        try {
            createZipEntry(outZip, entryDocument);
            final InputStream inputStream = currentDetachedDocument.openStream();
            IOUtils.copy(inputStream, outZip);
            IOUtils.closeQuietly(inputStream);
        } catch (DSSException e) {
            if (!((e.getCause() instanceof ZipException)
                    && e.getCause().getMessage().startsWith("duplicate entry:"))) {
                throw e;
            }
        }
        currentDetachedDocument = currentDetachedDocument.getNextDocument();
    } while (currentDetachedDocument != null);
}

From source file:org.egov.ptis.actions.reports.SearchNoticesAction.java

/**
 * @param inputStream//from w  ww. j  a v a2s.c o  m
 * @param noticeNo
 * @param out
 * @return zip output stream file
 */
private ZipOutputStream addFilesToZip(final InputStream inputStream, final String noticeNo,
        final ZipOutputStream out) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Entered into addFilesToZip method");
    final byte[] buffer = new byte[1024];
    try {
        out.setLevel(Deflater.DEFAULT_COMPRESSION);
        out.putNextEntry(new ZipEntry(noticeNo.replaceAll("/", "_")));
        int len;
        while ((len = inputStream.read(buffer)) > 0)
            out.write(buffer, 0, len);
        inputStream.close();

    } catch (final IllegalArgumentException iae) {
        LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, iae);
        throw new ValidationException(Arrays.asList(new ValidationError(ERROR1, iae.getMessage())));
    } catch (final FileNotFoundException fnfe) {
        LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, fnfe);
        throw new ValidationException(Arrays.asList(new ValidationError(ERROR1, fnfe.getMessage())));
    } catch (final IOException ioe) {
        LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, ioe);
        throw new ValidationException(Arrays.asList(new ValidationError(ERROR1, ioe.getMessage())));
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Exit from addFilesToZip method");
    return out;
}

From source file:ch.randelshofer.cubetwister.HTMLExporter.java

public void exportToDirectory(String documentName, DocumentModel model, File dir, ProgressObserver p)
        throws IOException {
    this.documentName = documentName;
    this.model = model;
    this.dir = dir;
    this.zipFile = null;
    this.p = p;/*  w w w  .j  a va 2 s .  c o m*/
    init();
    processHTMLTemplates(p);
    new File(dir, "applets").mkdir();
    ZipOutputStream zout = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(new File(dir, "applets/resources.xml.zip"))));
    zout.setLevel(Deflater.BEST_COMPRESSION);
    try {
        //model.writeXML(new PrintWriter(new File(dir, "applets/resources.xml")));
        zout.putNextEntry(new ZipEntry("resources.xml"));
        PrintWriter pw = new PrintWriter(zout);
        model.writeXML(pw);
        pw.flush();
        zout.closeEntry();
    } finally {
        zout.close();
    }
    p.setProgress(p.getProgress() + 1);
}

From source file:org.olat.ims.qti.qpool.QTIPoolWordExport.java

private void exportTest(List<QuestionItemFull> fullItems, OutputStream out, boolean withResponses) {
    ZipOutputStream zout = null;
    try {//from ww w.  j  a  va  2 s  .  co m
        OpenXMLDocument document = new OpenXMLDocument();
        document.setDocumentHeader("");
        Translator translator = Util.createPackageTranslator(QTIWordExport.class, locale);

        for (Iterator<QuestionItemFull> itemIt = fullItems.iterator(); itemIt.hasNext();) {
            QuestionItemFull fullItem = itemIt.next();

            String dir = fullItem.getDirectory();
            VFSContainer container = qpoolFileStorage.getContainer(dir);
            document.setMediaContainer(container);

            VFSItem rootItem = container.resolve(fullItem.getRootFilename());
            Item item = QTIEditHelper.readItemXml((VFSLeaf) rootItem);
            if (item.isAlient()) {
                QTIWordExport.renderAlienItem(item, document, translator);
            } else {
                QTIWordExport.renderItem(item, document, withResponses, translator);
            }
            if (itemIt.hasNext()) {
                document.appendPageBreak();
            }
        }

        zout = new ZipOutputStream(out);
        zout.setLevel(9);

        OpenXMLDocumentWriter writer = new OpenXMLDocumentWriter();
        writer.createDocument(zout, document);
    } catch (Exception e) {
        log.error("", e);
    } finally {
        if (zout != null) {
            try {
                zout.finish();
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }
}

From source file:com.netscape.cms.publish.publishers.FileBasedPublisher.java

/**
 * Publishes a object to the ldap directory.
 *
 * @param conn a Ldap connection/*from  w  ww .  j a  va 2s. c  om*/
 *            (null if LDAP publishing is not enabled)
 * @param dn dn of the ldap entry to publish cert
 *            (null if LDAP publishing is not enabled)
 * @param object object to publish
 *            (java.security.cert.X509Certificate or,
 *            java.security.cert.X509CRL)
 */
public void publish(LDAPConnection conn, String dn, Object object) throws ELdapException {
    CMS.debug("FileBasedPublisher: publish");

    try {
        if (object instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) object;
            BigInteger sno = cert.getSerialNumber();
            String name = mDir + File.separator + "cert-" + sno.toString();
            if (mDerAttr) {
                FileOutputStream fos = null;
                try {
                    String fileName = name + ".der";
                    fos = new FileOutputStream(fileName);
                    fos.write(cert.getEncoded());
                } finally {
                    if (fos != null)
                        fos.close();
                }
            }
            if (mB64Attr) {
                String fileName = name + ".b64";
                PrintStream ps = null;
                Base64OutputStream b64 = null;
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(fileName);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    b64 = new Base64OutputStream(new PrintStream(new FilterOutputStream(output)));
                    b64.write(cert.getEncoded());
                    b64.flush();
                    ps = new PrintStream(fos);
                    ps.print(output.toString("8859_1"));
                } finally {
                    if (ps != null) {
                        ps.close();
                    }
                    if (b64 != null) {
                        b64.close();
                    }
                    if (fos != null)
                        fos.close();
                }
            }
        } else if (object instanceof X509CRL) {
            X509CRL crl = (X509CRL) object;
            String[] namePrefix = getCrlNamePrefix(crl, mTimeStamp.equals("GMT"));
            String baseName = mDir + File.separator + namePrefix[0];
            String tempFile = baseName + ".temp";
            ZipOutputStream zos = null;
            byte[] encodedArray = null;
            File destFile = null;
            String destName = null;
            File renameFile = null;

            if (mDerAttr) {
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(tempFile);
                    encodedArray = crl.getEncoded();
                    fos.write(encodedArray);
                } finally {
                    if (fos != null)
                        fos.close();
                }
                if (mZipCRL) {
                    try {
                        zos = new ZipOutputStream(new FileOutputStream(baseName + ".zip"));
                        zos.setLevel(mZipLevel);
                        zos.putNextEntry(new ZipEntry(baseName + ".der"));
                        zos.write(encodedArray, 0, encodedArray.length);
                        zos.closeEntry();
                    } finally {
                        if (zos != null)
                            zos.close();
                    }
                }
                destName = baseName + ".der";
                destFile = new File(destName);

                if (destFile.exists()) {
                    destFile.delete();
                }
                renameFile = new File(tempFile);
                renameFile.renameTo(destFile);

                if (mLatestCRL) {
                    String linkExt = ".";
                    if (mLinkExt != null && mLinkExt.length() > 0) {
                        linkExt += mLinkExt;
                    } else {
                        linkExt += "der";
                    }
                    String linkName = mDir + File.separator + namePrefix[1] + linkExt;
                    createLink(linkName, destName);
                    if (mZipCRL) {
                        linkName = mDir + File.separator + namePrefix[1] + ".zip";
                        createLink(linkName, baseName + ".zip");
                    }
                }
            }

            // output base64 file
            if (mB64Attr == true) {
                if (encodedArray == null)
                    encodedArray = crl.getEncoded();
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(tempFile);
                    fos.write(Utils.base64encode(encodedArray, true).getBytes());
                } finally {
                    if (fos != null)
                        fos.close();
                }
                destName = baseName + ".b64";
                destFile = new File(destName);

                if (destFile.exists()) {
                    destFile.delete();
                }
                renameFile = new File(tempFile);
                renameFile.renameTo(destFile);
            }
            purgeExpiredFiles();
            purgeExcessFiles();
        }
    } catch (IOException e) {
        mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
                CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
    } catch (CertificateEncodingException e) {
        mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
                CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
    } catch (CRLException e) {
        mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
                CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
    }
}