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:com.Candy.center.AboutCandy.java

private boolean zip() {
    String[] source = { systemfile, logfile, last_kmsgfile, kmsgfile };
    try {/* w w w . j a  v a  2 s  .c  o m*/
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
        for (int i = 0; i < source.length; i++) {
            String file = source[i].substring(source[i].lastIndexOf("/"), source[i].length());
            FileInputStream in = new FileInputStream(source[i]);
            out.putNextEntry(new ZipEntry(file));
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            in.close();
        }
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.ephesoft.gxt.admin.server.ExportIndexFieldDownloadServlet.java

/**
 * This API is used to process request to export the documents .
 * //from   w ww  .  ja va 2 s.com
 * @param fieldTypeList {@link List<{@link FieldType}>} selected document type list to export.
 * @param resp {@link HttpServletResponse}.
 * @return
 */
private void process(final List<FieldType> fieldTypeList, final HttpServletResponse resp) throws IOException {
    final BatchSchemaService bSService = this.getSingleBeanOfType(BatchSchemaService.class);
    final String exportSerDirPath = bSService.getBatchExportFolderLocation();

    final String zipFileName = fieldTypeList.get(0).getDocType().getName() + "_" + "FieldTypes";

    final String copiedParentFolderPath = exportSerDirPath + File.separator + zipFileName;

    final File copiedFd = createDirectory(copiedParentFolderPath);

    processExportFieldTypes(fieldTypeList, bSService, resp, zipFileName);
    resp.setContentType("application/x-zip\r\n");
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
    ServletOutputStream out = null;
    ZipOutputStream zout = null;
    try {
        out = resp.getOutputStream();
        zout = new ZipOutputStream(out);
        FileUtils.zipDirectory(copiedParentFolderPath, zout, zipFileName);
        resp.setStatus(HttpServletResponse.SC_OK);
    } catch (final IOException e) {
        // Unable to create the temporary export file(s)/folder(s)
        log.error("Error occurred while creating the zip file." + e, e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
    } finally {
        // clean up code
        if (zout != null) {
            zout.close();
        }
        if (out != null) {
            out.flush();
        }
        FileUtils.deleteDirectoryAndContentsRecursive(copiedFd);
    }
}

From source file:com.cdd.bao.importer.ImportControlledVocab.java

private void writeMappedAssays() throws IOException {
    File f = new File(dstFN);
    Util.writeln("Writing to: " + f.getCanonicalPath());

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

    for (int n = 0; n < srcRows.length(); n++) {
        JSONObject json = null;/*w ww  .  j av a2  s . com*/
        try {
            json = map.createAssay(srcRows.getJSONObject(n), schema, treeCache);
        } catch (Exception ex) {
            zip.close();
            throw new IOException("Failed to translate assay at row #" + (n + 1), ex);
        }

        if (!json.has("uniqueID")) {
            Util.writeln("** Row#" + (n + 1) + " is missing an identifier: cannot proceed.");
            break;
        }

        String fn = "assay_" + (n + 1) + "_";
        for (char ch : json.getString("uniqueID").toCharArray()) {
            if (ch == ' ')
                fn += ' ';
            else if (ch == '_' || ch == ':' || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z')
                    || (ch >= 'A' && ch <= 'Z'))
                fn += ch;
            else
                fn += '-';
        }

        zip.putNextEntry(new ZipEntry(fn + ".json"));
        zip.write(json.toString(2).getBytes());
        zip.closeEntry();
    }

    zip.close();
}

From source file:org.cloudfoundry.tools.io.zip.ZipArchiveTest.java

private InputStream createSampleZip() throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    zipOutputStream.putNextEntry(new ZipEntry("a/"));
    zipOutputStream.closeEntry();//  ww  w  .j  a  v a2 s  . c  om
    zipOutputStream.putNextEntry(new ZipEntry("a/b.txt"));
    IOUtils.write("ab", zipOutputStream);
    zipOutputStream.closeEntry();
    zipOutputStream.putNextEntry(new ZipEntry("c/"));
    zipOutputStream.closeEntry();
    zipOutputStream.putNextEntry(new ZipEntry("c/d.txt"));
    IOUtils.write("cd", zipOutputStream);
    zipOutputStream.closeEntry();
    zipOutputStream.close();
    return new ByteArrayInputStream(outputStream.toByteArray());
}

From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java

private void zipFolder(String srcFolder, String destZipFile) throws IOException {
    ZipOutputStream zip = null;
    FileOutputStream fileWriter = null;
    try {/*from   w  w  w.  j a v a  2 s. co  m*/
        fileWriter = new FileOutputStream(destZipFile);
        zip = new ZipOutputStream(fileWriter);
        addFileToZip(srcFolder, zip);
    } finally {
        try {
            if (zip != null) {
                zip.flush();
                zip.close();
            }
        } catch (IOException e) {
            LOGGER.error("Error occured while closing the resources after zipping the folder.", e);
        }
    }
    LOGGER.info("Created zip folder {}", destZipFile);
}

From source file:com.aionlightning.slf4j.conversion.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 * /*from  w  w w  . j a  va2s .co  m*/
 * @param file
 *            file to truncate
 */
protected void truncate(File file) {
    File backupRoot = new File(backupDir);
    if (!backupRoot.exists() && !backupRoot.mkdirs()) {
        log.warn("Can't create backup dir for backup storage");
        return;
    }

    String date = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        date = reader.readLine().split("\f")[1];
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    try {
        zos = new ZipOutputStream(new FileOutputStream(zipFile));
        ZipEntry entry = new ZipEntry(file.getName());
        entry.setMethod(ZipEntry.DEFLATED);
        entry.setCrc(FileUtils.checksumCRC32(file));
        zos.putNextEntry(entry);
        fis = FileUtils.openInputStream(file);

        byte[] buffer = new byte[1024];
        int readed;
        while ((readed = fis.read(buffer)) != -1) {
            zos.write(buffer, 0, readed);
        }

    } catch (Exception e) {
        log.warn("Can't create zip file", e);
    } finally {
        if (zos != null) {
            try {
                zos.close();
            } catch (IOException e) {
                log.warn("Can't close zip file", e);
            }
        }

        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.warn("Can't close zipped file", e);
            }
        }
    }

    if (!file.delete()) {
        log.warn("Can't delete old log file " + file.getAbsolutePath());
    }
}

From source file:org.openremote.beehive.configuration.www.UsersAPI.java

@GET
@Produces("application/octet-stream")
@Path("/{username}/openremote.zip")
public Response getConfigurationFile(@PathParam("username") String username) {
    log.info("Get configuration for user " + username);

    MinimalPersistentUser user = userRepository.findByUsername(username);
    if (user == null) {
        log.error("Configuration requested for unknown user " + username);
        throw new NotFoundException();
    }//from  www . j av a2 s.c  om

    Account account = accountRepository.findOne(user.getAccountId());
    if (account == null) {
        log.error("Account not found for user " + username);
        throw new NotFoundException();
    }

    java.nio.file.Path temporaryFolderForFinalCleanup = null;
    try {
        // Create temporary folder
        final java.nio.file.Path temporaryFolder = Files.createTempDirectory("OR");
        temporaryFolderForFinalCleanup = temporaryFolder;

        // Create panel.xml file
        final File panelXmlFile = createPanelXmlFile(temporaryFolder);

        // Create controller.xml file
        final File controllerXmlFile = createControllerXmlFile(temporaryFolder, account);

        // Create drools folder and rules file (rules/modeler_rules.drl)
        final File droolsFile = createRules(temporaryFolder, account);

        // Create and return openremote.zip file
        StreamingOutput stream = new StreamingOutput() {
            public void write(OutputStream output) throws IOException, WebApplicationException {
                try {
                    ZipOutputStream zipOutput = new ZipOutputStream(output);
                    writeZipEntry(zipOutput, panelXmlFile, temporaryFolder);
                    writeZipEntry(zipOutput, controllerXmlFile, temporaryFolder);
                    if (droolsFile != null) {
                        writeZipEntry(zipOutput, droolsFile, temporaryFolder);
                    }
                    zipOutput.close();
                } catch (Exception e) {
                    log.error("Impossible to stream openremote.zip file", e);
                    throw new WebApplicationException(e);
                } finally {
                    removeTemporaryFiles(temporaryFolder);
                }
            }
        };

        // We've been able to build everything we need, set this to null so the cleanup is done
        // after the streaming has been done and not before (in final block of this method)
        temporaryFolderForFinalCleanup = null;
        return Response.ok(stream).header("content-disposition", "attachment; filename = \"openremote.zip\"")
                .build();
    } catch (IOException e) {
        log.error("Issue creating openremote.zip file", e);
    } finally {
        removeTemporaryFiles(temporaryFolderForFinalCleanup);
    }

    return Response.serverError().build();
}

From source file:nc.noumea.mairie.appock.services.impl.ExportExcelServiceImpl.java

@Override
public void genereExcelFournisseur(Commande commande) throws IOException {
    List<String> listeMessageErreurAdresseService = construitMessageErreurAdresseService(commande);
    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(listeMessageErreurAdresseService)) {
        Messagebox.show(StringUtils.join(listeMessageErreurAdresseService, "\n"), "Erreur d'adresse",
                Messagebox.OK, Messagebox.ERROR);
        return;/*from  w w  w  .  j a va 2 s.c  om*/
    }

    Map<AbstractEntity, Map<Service, List<ArticleDemande>>> map = commandeService
            .construitMapFournisseurServiceListeArticleDemande(commande);
    List<AbstractEntity> listeAbstractEntity = new ArrayList(map.keySet());
    Comparator abstractEntityComparator = Comparator
            .comparing((AbstractEntity abstractEntity) -> abstractEntity.getLibelleCourt());
    Collections.sort(listeAbstractEntity, abstractEntityComparator);

    File result = File.createTempFile(UUID.randomUUID().toString(), ".zip");
    FileOutputStream fos = new FileOutputStream(result);
    ZipOutputStream zos = new ZipOutputStream(fos);

    for (AbstractEntity abstractEntity : listeAbstractEntity) {
        String nomFichierSansExtension = construitNomFichier(abstractEntity);
        File tempFile = createExcelTempFile(map, abstractEntity, nomFichierSansExtension);
        addToZipFile(tempFile, nomFichierSansExtension + ".xlsx", zos);
        tempFile.delete();
    }

    zos.close();
    fos.close();

    downloadService.downloadToUser(result, "Fichiers fournisseurs.zip");
    result.delete();
}

From source file:de.jwi.jfm.Folder.java

private String zip(OutputStream out, String[] selectedIDs) throws IOException, OutOfSyncException {

    Collection c = null;//from  w  w  w . j a  va2 s.c om

    List l = new ArrayList();

    for (int i = 0; i < selectedIDs.length; i++) {
        File f = checkAndGet(selectedIDs[i]);

        if (null == f) {
            throw new OutOfSyncException();
        }

        if (f.isDirectory()) {
            c = FileUtils.listFiles(f, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
            l.addAll(c);
        } else {
            l.add(f);
        }
    }

    ZipOutputStream z = new ZipOutputStream(out);
    try {
        new Zipper().zip(z, l, myFile);
    } finally {
        z.close();
    }

    return null;
}

From source file:com.stimulus.archiva.presentation.ExportBean.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    SearchBean searchBean = (SearchBean) form;

    String outputDir = Config.getFileSystem().getViewPath() + File.separatorChar;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String zipFileName = "export-" + sdf.format(new Date()) + ".zip";
    File zipFile = new File(outputDir + zipFileName);

    String agent = request.getHeader("USER-AGENT");
    if (null != agent && -1 != agent.indexOf("MSIE")) {
        String codedfilename = URLEncoder.encode(zipFileName, "UTF8");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        String codedfilename = MimeUtility.encodeText(zipFileName, "UTF8", "B");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else {/*from   ww  w  . j a  v a2 s.  c o  m*/
        response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
    }

    logger.debug("size of searchResult = " + searchBean.getSearchResults().size());
    //MessageBean.viewMessage
    List<File> files = new ArrayList<File>();
    for (SearchResultBean searchResult : searchBean.getSearchResults()) {
        if (searchResult.getSelected()) {
            Email email = MessageService.getMessageByID(searchResult.getVolumeID(), searchResult.getUniqueID(),
                    false);

            HttpServletRequest hsr = ActionContext.getActionContext().getRequest();
            String baseURL = hsr.getRequestURL().substring(0,
                    hsr.getRequestURL().lastIndexOf(hsr.getServletPath()));
            MessageExtraction messageExtraction = MessageService.extractMessage(email, baseURL, true); // can take a while to extract message

            //              MessageBean mbean = new MessageBean();
            //              mbean.setMessageID(searchResult.getUniqueID());
            //              mbean.setVolumeID(searchResult.getVolumeID());
            //              writer.println(searchResult.toString());
            //              writer.println(messageExtraction.getFileName());

            File fileToAdd = new File(outputDir, messageExtraction.getFileName());
            if (!files.contains(fileToAdd)) {
                files.add(fileToAdd);
            }
        }
    }

    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
    try {
        byte[] buf = new byte[1024];
        for (File f : files) {
            ZipEntry ze = new ZipEntry(f.getName());
            logger.debug("Adding file " + f.getName());
            zos.putNextEntry(ze);
            InputStream is = new BufferedInputStream(new FileInputStream(f));
            for (;;) {
                int len = is.read(buf);
                if (len < 0)
                    break;
                zos.write(buf, 0, len);
            }
            is.close();
            Config.getFileSystem().getTempFiles().markForDeletion(f);
        }
    } finally {
        zos.close();
    }
    logger.debug("download zipped emails {fileName='" + zipFileName + "'}");

    String contentType = "application/zip";
    Config.getFileSystem().getTempFiles().markForDeletion(zipFile);
    return new FileStreamInfo(contentType, zipFile);
}