Example usage for java.util.zip ZipOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

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);
    }//ww w  .  ja va 2 s .  c o m

    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:com.datasalt.pangool.solr.SolrRecordWriter.java

private void packZipFile() throws IOException {
    FSDataOutputStream out = null;//www.ja  va  2s.  c om
    ZipOutputStream zos = null;
    int zipCount = 0;
    LOG.info("Packing zip file for " + perm);
    try {
        out = fs.create(perm, false);
        zos = new ZipOutputStream(out);

        String name = perm.getName().replaceAll(".zip$", "");
        LOG.info("adding index directory" + local);
        zipCount = zipDirectory(conf, zos, name, local.toString(), local);
    } catch (Throwable ohFoo) {
        LOG.error("packZipFile exception", ohFoo);
        if (ohFoo instanceof RuntimeException) {
            throw (RuntimeException) ohFoo;
        }
        if (ohFoo instanceof IOException) {
            throw (IOException) ohFoo;
        }
        throw new IOException(ohFoo);

    } finally {
        if (zos != null) {
            if (zipCount == 0) { // If no entries were written, only close out, as
                                 // the zip will throw an error
                LOG.error("No entries written to zip file " + perm);
                fs.delete(perm, false);
                // out.close();
            } else {
                LOG.info(String.format("Wrote %d items to %s for %s", zipCount, perm, local));
                zos.close();
            }
        }
    }
}

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  v  a2s  .co  m
 *            (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()));
    }
}

From source file:nl.nn.adapterframework.soap.Wsdl.java

/**
 * Generates a zip file (and writes it to the given outputstream), containing the WSDL and all referenced XSD's.
 * @see #wsdl(java.io.OutputStream, String)
 *//*from w ww .  ja va  2 s  . co m*/
public void zip(OutputStream stream, String servletName)
        throws IOException, ConfigurationException, XMLStreamException, NamingException {
    ZipOutputStream out = new ZipOutputStream(stream);

    // First an entry for the WSDL itself:
    ZipEntry wsdlEntry = new ZipEntry(getFilename() + ".wsdl");
    out.putNextEntry(wsdlEntry);
    wsdl(out, servletName);
    out.closeEntry();

    //And then all XSD's
    Set<String> entries = new HashSet<String>();
    for (XSD xsd : xsds) {
        String zipName = xsd.getResourceTarget();
        if (entries.add(zipName)) {
            ZipEntry xsdEntry = new ZipEntry(zipName);
            out.putNextEntry(xsdEntry);
            XMLStreamWriter writer = WsdlUtils.getWriter(out, false);
            SchemaUtils.xsdToXmlStreamWriter(xsd, writer);
            out.closeEntry();
        } else {
            warn("Duplicate xsds in " + this + " " + xsd + " " + xsds);
        }
    }
    out.close();
}

From source file:edu.dfci.cccb.mev.dataset.rest.controllers.WorkspaceController.java

@RequestMapping(value = "/export/zip", method = POST, consumes = "multipart/form-data")
@ResponseStatus(OK)//w  w  w . j  a va2 s  . c o  m
public byte[] export(@RequestParam("name") String name, @RequestParam("rows") List<String> rows,
        @RequestParam("columns") List<String> columns, @RequestParam("rowSelections") String jsonRowSelections,
        @RequestParam("columnSelections") String jsonColumnSelections,
        @RequestParam("analyses") String[] analyses, HttpServletResponse response)
        throws DatasetException, IOException {
    log.info(String.format("Offline %s, %s, %s, %s", name, rows, columns, analyses));

    //creating byteArray stream, make it bufforable and passing this buffor to ZipOutputStream
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
    ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

    //nw zip entry for dataset
    Dataset dataset = workspace.get(name);
    zipOutputStream.putNextEntry(new ZipEntry("dataset.json"));
    IOUtils.copy(new ByteArrayInputStream(mapper.writeValueAsBytes(dataset)), zipOutputStream);
    zipOutputStream.closeEntry();

    zipAnnotations(name, "row", zipOutputStream);
    zipAnnotations(name, "column", zipOutputStream);

    if (dataset.values() instanceof IFlatFileValues) {
        IFlatFileValues values = (IFlatFileValues) dataset.values();
        zipOutputStream.putNextEntry(new ZipEntry("values.bin"));
        InputStream valuesIs = values.asInputStream();
        IOUtils.copy(valuesIs, zipOutputStream);
        zipOutputStream.closeEntry();
        zipOutputStream.flush();
        valuesIs.close();
    }

    //new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
    int i = 0;
    for (String analysis : analyses) {
        InputStream analysisOs = new ByteArrayInputStream(analysis.getBytes(StandardCharsets.UTF_8));
        zipOutputStream.putNextEntry(new ZipEntry(String.format("analysis_%d.json", i)));
        JsonNode analysisJson = mapper.readTree(analysis);
        IOUtils.copy(analysisOs, zipOutputStream);
        zipOutputStream.closeEntry();
        zipOutputStream.flush();
        analysisOs.close();
        i++;
    }
    zipOutputStream.flush();
    zipOutputStream.close();

    byte[] ret = byteArrayOutputStream.toByteArray();
    IOUtils.closeQuietly(bufferedOutputStream);
    IOUtils.closeQuietly(byteArrayOutputStream);

    response.setContentLength(ret.length);
    response.setContentType("application/zip"); //or something more generic...
    response.setHeader("Accept-Ranges", "bytes");
    response.setStatus(HttpServletResponse.SC_OK);
    response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s.zip\"", name));
    return ret;
}

From source file:org.openmeetings.servlet.outputhandler.BackupExport.java

public void writeZipFile(File directoryToZip, List<File> fileList, FileOutputStream fos) {

    try {//from   ww w . j  a v a 2 s . c o  m
        ZipOutputStream zos = new ZipOutputStream(fos);

        for (File file : fileList) {
            if (!file.isDirectory()) { // we only zip files, not directories
                addToZip(directoryToZip, file, zos);
            }
        }

        zos.close();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:io.openvidu.server.recording.service.SingleStreamRecordingService.java

private void generateZipFileAndCleanFolder(String folder, String fileName) {
    FileOutputStream fos = null;//from  w  w w . j  a  v  a2 s .  c  o  m
    ZipOutputStream zipOut = null;

    final File[] files = new File(folder).listFiles();

    try {
        fos = new FileOutputStream(folder + fileName);
        zipOut = new ZipOutputStream(fos);

        for (int i = 0; i < files.length; i++) {
            String fileExtension = FilenameUtils.getExtension(files[i].getName());

            if (files[i].isFile() && (fileExtension.equals("json") || fileExtension.equals("webm"))) {

                // Zip video files and json sync metadata file
                FileInputStream fis = new FileInputStream(files[i]);
                ZipEntry zipEntry = new ZipEntry(files[i].getName());
                zipOut.putNextEntry(zipEntry);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) >= 0) {
                    zipOut.write(bytes, 0, length);
                }
                fis.close();

            }
            if (!files[i].getName().startsWith(RecordingManager.RECORDING_ENTITY_FILE)) {
                // Clean inspected file if it is not
                files[i].delete();
            }
        }
    } catch (IOException e) {
        log.error("Error generating ZIP file {}. Error: {}", folder + fileName, e.getMessage());
    } finally {
        try {
            zipOut.close();
            fos.close();
            this.updateFilePermissions(folder);
        } catch (IOException e) {
            log.error("Error closing FileOutputStream or ZipOutputStream. Error: {}", e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java

public String exportZippedResultsForUser(String deviceId) throws FileNotFoundException {
    String resultsDir = deviceId + File.separator;
    String zipFilename = deviceId + ".zip";
    new File(resultsDir).mkdir();
    saveResultsToFilesForDeviceId(deviceId, resultsDir);

    ZipOutputStream zipOutputStream = null;
    try {/*w w w  .j  ava  2s.  c  o m*/
        zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilename));
        File zipDir = new File(resultsDir);
        String[] dirList = zipDir.list();
        byte[] readBuffer = new byte[4096];
        int bytesIn = 0;

        for (int i = 0; i < dirList.length; i++) {
            FileInputStream fis = null;
            try {
                File f = new File(zipDir, dirList[i]);
                fis = new FileInputStream(f);
                ZipEntry anEntry = new ZipEntry(f.getPath());
                zipOutputStream.putNextEntry(anEntry);
                while ((bytesIn = fis.read(readBuffer)) != -1) {
                    zipOutputStream.write(readBuffer, 0, bytesIn);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    } finally {
        if (zipOutputStream != null) {
            try {
                zipOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    removeDir(resultsDir);
    return zipFilename;
}

From source file:com.baasbox.db.async.ExportJob.java

@Override
public void run() {
    FileOutputStream dest = null;
    ZipOutputStream zip = null;
    FileOutputStream tempJsonOS = null;
    FileInputStream in = null;//from   w w  w  .java2  s.co  m
    try {
        //File f = new File(this.fileName);
        File f = File.createTempFile("export", ".temp");

        dest = new FileOutputStream(f);
        zip = new ZipOutputStream(dest);

        File tmpJson = File.createTempFile("export", ".json");
        tempJsonOS = new FileOutputStream(tmpJson);
        DbHelper.exportData(this.appcode, tempJsonOS);
        BaasBoxLogger.info(String.format("Writing %d bytes ", tmpJson.length()));
        tempJsonOS.close();

        ZipEntry entry = new ZipEntry("export.json");
        zip.putNextEntry(entry);
        in = new FileInputStream(tmpJson);
        final int BUFFER = BBConfiguration.getImportExportBufferSize();
        byte buffer[] = new byte[BUFFER];

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

        File manifest = File.createTempFile("manifest", ".txt");
        FileUtils.writeStringToFile(manifest,
                BBInternalConstants.IMPORT_MANIFEST_VERSION_PREFIX + BBConfiguration.getApiVersion());

        ZipEntry entryManifest = new ZipEntry("manifest.txt");
        zip.putNextEntry(entryManifest);
        zip.write(FileUtils.readFileToByteArray(manifest));
        zip.closeEntry();

        tmpJson.delete();
        manifest.delete();

        File finaldestination = new File(this.fileName);
        FileUtils.moveFile(f, finaldestination);

    } catch (Exception e) {
        BaasBoxLogger.error(ExceptionUtils.getMessage(e));
    } finally {
        try {
            if (zip != null)
                zip.close();
            if (dest != null)
                dest.close();
            if (tempJsonOS != null)
                tempJsonOS.close();
            if (in != null)
                in.close();

        } catch (Exception ioe) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(ioe));
        }
    }
}