Example usage for java.util.zip ZipOutputStream ZipOutputStream

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

Introduction

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

Prototype

public ZipOutputStream(OutputStream out) 

Source Link

Document

Creates a new ZIP output stream.

Usage

From source file:it.govpay.web.rs.dars.base.BaseDarsService.java

@POST
@Path("/{id}/esporta")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
public Response esportaDettaglio(@PathParam("id") long id, InputStream is, @Context UriInfo uriInfo)
        throws Exception {

    String methodName = "esporta " + this.getNomeServizio() + "[" + id + "]";
    this.initLogger(methodName);

    BasicBD bd = null;//from w w w  . j a  v  a 2  s  .co m
    DarsResponse darsResponse = new DarsResponse();
    darsResponse.setCodOperazione(this.codOperazione);

    try {
        bd = BasicBD.newInstance(this.codOperazione);
        bd.setIdOperatore(this.getOperatoreByPrincipal(bd).getId());

        ByteArrayOutputStream baosIn = new ByteArrayOutputStream();
        Utils.copy(is, baosIn);

        baosIn.flush();
        baosIn.close();

        JSONObject jsonObjectFormExport = JSONObject.fromObject(baosIn.toString());

        List<RawParamValue> rawValues = new ArrayList<RawParamValue>();
        for (Object key : jsonObjectFormExport.keySet()) {
            String value = jsonObjectFormExport.getString((String) key);
            if (StringUtils.isNotEmpty(value) && !"null".equals(value))
                rawValues.add(new RawParamValue((String) key, value));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zout = new ZipOutputStream(baos);

        String fileName = this.getDarsHandler().esporta(id, rawValues, uriInfo, bd, zout);
        this.log.info("Richiesta " + methodName + " evasa con successo, creato file: " + fileName);
        return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition", "attachment; filename=\"" + fileName + "\"").build();
    } catch (WebApplicationException e) {
        this.log.error("Riscontrato errore di autorizzazione durante l'esecuzione del metodo " + methodName
                + ":" + e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        this.log.error(
                "Riscontrato errore durante l'esecuzione del metodo " + methodName + ":" + e.getMessage(), e);
        if (bd != null)
            bd.rollback();
        return Response.serverError().build();
    } finally {
        this.response.setHeader("Access-Control-Allow-Origin", "*");
        this.response.setHeader("Access-Control-Expose-Headers", "content-disposition");
        if (bd != null)
            bd.closeConnection();
    }

}

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 ww. java2 s  .com

    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:com.pari.nm.utils.backup.BackupRestore.java

public boolean zipFolder(File backupDir, File backupZipFile) {
    FileOutputStream fileWriter = null;
    ZipOutputStream zip = null;//  w w  w.j a  v a  2s  . co  m
    try {
        fileWriter = new FileOutputStream(backupZipFile);
        zip = new ZipOutputStream(fileWriter);
        addFolderToZip("", backupDir, zip);
        zip.flush();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (zip != null) {
                zip.close();
            }
        } catch (IOException ignore) {
        }
        try {
            if (fileWriter != null) {
                fileWriter.close();
            }
        } catch (IOException ignore) {
        }
    }
    return true;
}

From source file:at.alladin.rmbt.statisticServer.export.ExportResource.java

@Get
public Representation request(final String entity) {
    //Before doing anything => check if a cached file already exists and is new enough
    String property = System.getProperty("java.io.tmpdir");

    final String filename_zip;
    final String filename_csv;

    //allow filtering by month/year
    int year = -1;
    int month = -1;
    int hours = -1;
    boolean hoursExport = false;
    boolean dateExport = false;

    if (getRequest().getAttributes().containsKey("hours")) { // export by hours
        try {//from   www. j a  va 2s  .c  om
            hours = Integer.parseInt(getRequest().getAttributes().get("hours").toString());
        } catch (NumberFormatException ex) {
            //Nothing -> just fall back
        }
        if (hours <= 7 * 24 && hours >= 1) { //limit to 1 week (avoid DoS)
            hoursExport = true;
        }
    } else if (!hoursExport && getRequest().getAttributes().containsKey("year")) { // export by month/year 
        try {
            year = Integer.parseInt(getRequest().getAttributes().get("year").toString());
            month = Integer.parseInt(getRequest().getAttributes().get("month").toString());
        } catch (NumberFormatException ex) {
            //Nothing -> just fall back
        }
        if (year < 2099 && month > 0 && month <= 12 && year > 2000) {
            dateExport = true;
        }
    }

    if (hoursExport) {
        filename_zip = FILENAME_ZIP_HOURS.replace("%HOURS%", String.format("%03d", hours));
        filename_csv = FILENAME_CSV_HOURS.replace("%HOURS%", String.format("%03d", hours));
        cacheThresholdMs = 5 * 60 * 1000; //5 minutes
    } else if (dateExport) {
        filename_zip = FILENAME_ZIP.replace("%YEAR%", Integer.toString(year)).replace("%MONTH%",
                String.format("%02d", month));
        filename_csv = FILENAME_CSV.replace("%YEAR%", Integer.toString(year)).replace("%MONTH%",
                String.format("%02d", month));
        cacheThresholdMs = 23 * 60 * 60 * 1000; //23 hours
    } else {
        filename_zip = FILENAME_ZIP_CURRENT;
        filename_csv = FILENAME_CSV_CURRENT;
        cacheThresholdMs = 3 * 60 * 60 * 1000; //3 hours
    }

    final File cachedFile = new File(property + File.separator + ((zip) ? filename_zip : filename_csv));
    final File generatingFile = new File(
            property + File.separator + ((zip) ? filename_zip : filename_csv) + "_tmp");
    if (cachedFile.exists()) {

        //check if file has been recently created OR a file is currently being created
        if (((cachedFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())
                || (generatingFile.exists()
                        && (generatingFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())) {

            //if so, return the cached file instead of a cost-intensive new one
            final OutputRepresentation result = new OutputRepresentation(
                    zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_CSV) {

                @Override
                public void write(OutputStream out) throws IOException {
                    InputStream is = new FileInputStream(cachedFile);
                    IOUtils.copy(is, out);
                    out.close();
                }

            };
            if (zip) {
                final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
                disposition.setFilename(filename_zip);
                result.setDisposition(disposition);
            }
            return result;

        }
    }

    final String timeClause;

    if (dateExport)
        timeClause = " AND (EXTRACT (month FROM t.time AT TIME ZONE 'UTC') = " + month
                + ") AND (EXTRACT (year FROM t.time AT TIME ZONE 'UTC') = " + year + ") ";
    else if (hoursExport)
        timeClause = " AND time > now() - interval '" + hours + " hours' ";
    else
        timeClause = " AND time > current_date - interval '31 days' ";

    final String sql = "SELECT" + " ('P' || t.open_uuid) open_uuid,"
            + " ('O' || t.open_test_uuid) open_test_uuid,"
            + " to_char(t.time AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') time_utc,"
            + " nt.group_name cat_technology," + " nt.name network_type,"
            + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') THEN"
            + " t.geo_lat" + " WHEN (t.geo_accuracy < ?) THEN" + " ROUND(t.geo_lat*1111)/1111" + " ELSE null"
            + " END) lat,"
            + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') THEN"
            + " t.geo_long" + " WHEN (t.geo_accuracy < ?) THEN" + " ROUND(t.geo_long*741)/741 " + " ELSE null"
            + " END) long," + " (CASE WHEN ((t.geo_provider = 'manual') OR (t.geo_provider = 'geocoder')) THEN"
            + " 'rastered'" + //make raster transparent
            " ELSE t.geo_provider" + " END) loc_src,"
            + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') "
            + " THEN round(t.geo_accuracy::float * 10)/10 "
            + " WHEN (t.geo_accuracy < 100) AND ((t.geo_provider = 'manual') OR (t.geo_provider = 'geocoder')) THEN 100"
            + // limit accuracy to 100m
            " WHEN (t.geo_accuracy < ?) THEN round(t.geo_accuracy::float * 10)/10"
            + " ELSE null END) loc_accuracy, "
            + " (CASE WHEN (t.zip_code < 1000 OR t.zip_code > 9999) THEN null ELSE t.zip_code END) zip_code,"
            + " t.gkz gkz," + " t.country_location country_location," + " t.speed_download download_kbit,"
            + " t.speed_upload upload_kbit," + " round(t.ping_median::float / 100000)/10 ping_ms,"
            + " t.lte_rsrp," + " t.lte_rsrq," + " ts.name server_name," + " duration test_duration,"
            + " num_threads," + " t.plattform platform," + " COALESCE(adm.fullname, t.model) model,"
            + " client_software_version client_version," + " network_operator network_mcc_mnc,"
            + " network_operator_name network_name," + " network_sim_operator sim_mcc_mnc," + " nat_type,"
            + " public_ip_asn asn," + " client_public_ip_anonymized ip_anonym,"
            + " (ndt.s2cspd*1000)::int ndt_download_kbit," + " (ndt.c2sspd*1000)::int ndt_upload_kbit,"
            + " COALESCE(t.implausible, false) implausible," + " t.signal_strength" + " FROM test t"
            + " LEFT JOIN network_type nt ON nt.uid=t.network_type"
            + " LEFT JOIN device_map adm ON adm.codename=t.model"
            + " LEFT JOIN test_server ts ON ts.uid=t.server_id" + " LEFT JOIN test_ndt ndt ON t.uid=ndt.test_id"
            + " WHERE " + " t.deleted = false" + timeClause + " AND status = 'FINISHED'" + " ORDER BY t.uid";

    final String[] columns;
    final List<String[]> data = new ArrayList<>();
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(sql);

        //insert filter for accuracy
        double accuracy = Double.parseDouble(settings.getString("RMBT_GEO_ACCURACY_DETAIL_LIMIT"));
        ps.setDouble(1, accuracy);
        ps.setDouble(2, accuracy);
        ps.setDouble(3, accuracy);
        ps.setDouble(4, accuracy);
        ps.setDouble(5, accuracy);
        ps.setDouble(6, accuracy);

        if (!ps.execute())
            return null;
        rs = ps.getResultSet();

        final ResultSetMetaData meta = rs.getMetaData();
        final int colCnt = meta.getColumnCount();
        columns = new String[colCnt];
        for (int i = 0; i < colCnt; i++)
            columns[i] = meta.getColumnName(i + 1);

        while (rs.next()) {
            final String[] line = new String[colCnt];

            for (int i = 0; i < colCnt; i++) {
                final Object obj = rs.getObject(i + 1);
                line[i] = obj == null ? null : obj.toString();
            }

            data.add(line);
        }
    } catch (final SQLException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (ps != null)
                ps.close();
        } catch (final SQLException e) {
            e.printStackTrace();
        }
    }

    final OutputRepresentation result = new OutputRepresentation(
            zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_CSV) {
        @Override
        public void write(OutputStream out) throws IOException {
            //cache in file => create temporary temporary file (to 
            // handle errors while fulfilling a request)
            String property = System.getProperty("java.io.tmpdir");
            final File cachedFile = new File(
                    property + File.separator + ((zip) ? filename_zip : filename_csv) + "_tmp");
            OutputStream outf = new FileOutputStream(cachedFile);

            if (zip) {
                final ZipOutputStream zos = new ZipOutputStream(outf);
                final ZipEntry zeLicense = new ZipEntry("LIZENZ.txt");
                zos.putNextEntry(zeLicense);
                final InputStream licenseIS = getClass().getResourceAsStream("DATA_LICENSE.txt");
                IOUtils.copy(licenseIS, zos);
                licenseIS.close();

                final ZipEntry zeCsv = new ZipEntry(filename_csv);
                zos.putNextEntry(zeCsv);
                outf = zos;
            }

            final OutputStreamWriter osw = new OutputStreamWriter(outf);
            final CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);

            for (final String c : columns)
                csvPrinter.print(c);
            csvPrinter.println();

            for (final String[] line : data) {
                for (final String f : line)
                    csvPrinter.print(f);
                csvPrinter.println();
            }
            csvPrinter.flush();

            if (zip)
                outf.close();

            //if we reach this code, the data is now cached in a temporary tmp-file
            //so, rename the file for "production use2
            //concurrency issues should be solved by the operating system
            File newCacheFile = new File(property + File.separator + ((zip) ? filename_zip : filename_csv));
            Files.move(cachedFile.toPath(), newCacheFile.toPath(), StandardCopyOption.ATOMIC_MOVE,
                    StandardCopyOption.REPLACE_EXISTING);

            FileInputStream fis = new FileInputStream(newCacheFile);
            IOUtils.copy(fis, out);
            fis.close();
            out.close();
        }
    };
    if (zip) {
        final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
        disposition.setFilename(filename_zip);
        result.setDisposition(disposition);
    }

    return result;
}

From source file:be.ibridge.kettle.job.entry.zipfile.JobEntryZipFile.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);/*from  www  .  j  a va 2  s  .  c  o  m*/
    boolean Fileexists = false;

    String realZipfilename = StringUtil.environmentSubstitute(zipFilename);
    String realWildcard = StringUtil.environmentSubstitute(wildcard);
    String realWildcardExclude = StringUtil.environmentSubstitute(wildcardexclude);
    String realTargetdirectory = StringUtil.environmentSubstitute(sourcedirectory);
    String realMovetodirectory = StringUtil.environmentSubstitute(movetodirectory);

    if (realZipfilename != null) {
        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realZipfilename);
            // Check if Zip File exists
            if (fileObject.exists()) {
                Fileexists = true;
                log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label")
                        + realZipfilename + Messages.getString("JobZipFiles.Zip_FileExists2.Label"));
            } else {
                Fileexists = false;
            }

            // Let's start the process now
            if (ifzipfileexists == 3 && Fileexists) {
                // the zip file exists and user want to Fail
                result.setResult(false);
                result.setNrErrors(1);

            } else if (ifzipfileexists == 2 && Fileexists) {
                // the zip file exists and user want to do nothing
                result.setResult(true);

            } else if (afterzip == 2 && realMovetodirectory == null) {
                // After Zip, Move files..User must give a destination Folder
                result.setResult(false);
                result.setNrErrors(1);
                log.logError(toString(),
                        Messages.getString("JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label"));

            } else
            // After Zip, Move files..User must give a destination Folder
            {

                if (ifzipfileexists == 0 && Fileexists) {

                    // the zip file exists and user want to create new one with unique name
                    //Format Date

                    DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");
                    realZipfilename = realZipfilename + "_" + dateFormat.format(new Date()) + ".zip";
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileNameChange1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileNameChange1.Label"));

                } else if (ifzipfileexists == 1 && Fileexists) {
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileAppend1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileAppend2.Label"));
                }

                // Get all the files in the directory...

                File f = new File(realTargetdirectory);

                String[] filelist = f.list();

                log.logDetailed(toString(),
                        Messages.getString("JobZipFiles.Files_Found1.Label") + filelist.length
                                + Messages.getString("JobZipFiles.Files_Found2.Label") + realTargetdirectory
                                + Messages.getString("JobZipFiles.Files_Found3.Label"));

                Pattern pattern = null;
                if (!Const.isEmpty(realWildcard)) {
                    pattern = Pattern.compile(realWildcard);

                }
                Pattern patternexclude = null;
                if (!Const.isEmpty(realWildcardExclude)) {
                    patternexclude = Pattern.compile(realWildcardExclude);

                }

                // Prepare Zip File
                byte[] buffer = new byte[18024];

                FileOutputStream dest = new FileOutputStream(realZipfilename);
                BufferedOutputStream buff = new BufferedOutputStream(dest);
                ZipOutputStream out = new ZipOutputStream(buff);

                // Set the method
                out.setMethod(ZipOutputStream.DEFLATED);

                // Set the compression level
                if (compressionrate == 0) {
                    out.setLevel(Deflater.NO_COMPRESSION);
                } else if (compressionrate == 1) {
                    out.setLevel(Deflater.DEFAULT_COMPRESSION);
                }
                if (compressionrate == 2) {
                    out.setLevel(Deflater.BEST_COMPRESSION);
                }
                if (compressionrate == 3) {
                    out.setLevel(Deflater.BEST_SPEED);
                }

                // Specify Zipped files (After that we will move,delete them...)
                String[] ZippedFiles = new String[filelist.length];
                int FileNum = 0;

                // Get the files in the list...
                for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) {
                    boolean getIt = true;
                    boolean getItexclude = false;

                    // First see if the file matches the regular expression!
                    if (pattern != null) {
                        Matcher matcher = pattern.matcher(filelist[i]);
                        getIt = matcher.matches();
                    }

                    if (patternexclude != null) {
                        Matcher matcherexclude = patternexclude.matcher(filelist[i]);
                        getItexclude = matcherexclude.matches();
                    }

                    // Get processing File
                    String targetFilename = realTargetdirectory + Const.FILE_SEPARATOR + filelist[i];
                    File file = new File(targetFilename);

                    if (getIt && !getItexclude && !file.isDirectory()) {

                        // We can add the file to the Zip Archive

                        log.logDebug(toString(),
                                Messages.getString("JobZipFiles.Add_FilesToZip1.Label") + filelist[i]
                                        + Messages.getString("JobZipFiles.Add_FilesToZip2.Label")
                                        + realTargetdirectory
                                        + Messages.getString("JobZipFiles.Add_FilesToZip3.Label"));

                        // Associate a file input stream for the current file
                        FileInputStream in = new FileInputStream(targetFilename);

                        // Add ZIP entry to output stream.
                        out.putNextEntry(new ZipEntry(filelist[i]));

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

                        out.closeEntry();

                        // Close the current file input stream
                        in.close();

                        // Get Zipped File
                        ZippedFiles[FileNum] = filelist[i];
                        FileNum = FileNum + 1;
                    }
                }

                // Close the ZipOutPutStream
                out.close();

                //-----Get the list of Zipped Files and Move or Delete Them
                if (afterzip == 1 || afterzip == 2) {
                    // iterate through the array of Zipped files
                    for (int i = 0; i < ZippedFiles.length; i++) {
                        if (ZippedFiles[i] != null) {
                            // Delete File
                            FileObject fileObjectd = KettleVFS
                                    .getFileObject(realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);

                            // Here we can move, delete files
                            if (afterzip == 1) {
                                // Delete File
                                boolean deleted = fileObjectd.delete();
                                if (!deleted) {
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Delete_File1.Label")
                                                    + realTargetdirectory + Const.FILE_SEPARATOR
                                                    + ZippedFiles[i] + Messages
                                                            .getString("JobZipFiles.Cant_Delete_File2.Label"));

                                }
                                // File deleted
                                log.logDebug(toString(),
                                        Messages.getString("JobZipFiles.File_Deleted1.Label")
                                                + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]
                                                + Messages.getString("JobZipFiles.File_Deleted2.Label"));
                            } else if (afterzip == 2) {
                                // Move File   
                                try {
                                    FileObject fileObjectm = KettleVFS.getFileObject(
                                            realMovetodirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);
                                    fileObjectd.moveTo(fileObjectm);
                                } catch (IOException e) {
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Move_File1.Label")
                                                    + ZippedFiles[i]
                                                    + Messages.getString("JobZipFiles.Cant_Move_File2.Label")
                                                    + e.getMessage());
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                }
                                // File moved
                                log.logDebug(toString(), Messages.getString("JobZipFiles.File_Moved1.Label")
                                        + ZippedFiles[i] + Messages.getString("JobZipFiles.File_Moved2.Label"));
                            }
                        }
                    }
                }
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(),
                    Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") + realZipfilename
                            + Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        result.setResult(false);
        result.setNrErrors(1);
        log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label"));
    }

    return result;
}

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

/**
 * This API is used to process request to export the documents .
 * /*from  www .ja  v a2 s . co  m*/
 * @param docTypeList {@link List<{@link DocumentType}>} selected document type list to export.
 * @param resp {@link HttpServletResponse}.
 * @return
 */
private void process(final List<DocumentType> docTypeList, final HttpServletResponse resp) throws IOException {

    final BatchSchemaService bSService = this.getSingleBeanOfType(BatchSchemaService.class);
    final String exportSerDirPath = bSService.getBatchExportFolderLocation();
    final BatchClass batchClass = docTypeList.get(0).getBatchClass();

    final String zipFileName = batchClass.getIdentifier() + "_" + "DocumentTypes";
    final String copiedParentFolderPath = exportSerDirPath + File.separator + zipFileName;
    final File copiedFd = createDirectory(copiedParentFolderPath);
    // final boolean isIMFdSelected = checkBaseDirectorySelection("image-classification-sample",
    // bSService.getImagemagickBaseFolderName());
    // final boolean isSSFdSelected = checkBaseDirectorySelection("lucene-search-classification-sample",
    // bSService.getSearchSampleName());
    final boolean isIMFdSelected = true;
    final boolean isSSFdSelected = true;
    processDocumentTypes(docTypeList, batchClass, bSService, isIMFdSelected, isSSFdSelected, resp);
    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:eu.scape_project.planning.xml.ProjectExportAction.java

/**
 * new helper method that was refactored from
 * {@link #exportAllProjectsToZip()} It takes a list of
 * {@link PlanProperties} and exports it to a zip file.
 * //from  w  ww.j  av  a 2  s.  c  o m
 * @param ppList
 *            {@link PlanProperties} for plans to export
 * 
 * @return True if export was successful, false otherwise.
 */
private boolean exportPPListToZip(List<PlanProperties> ppList) {
    if (!ppList.isEmpty()) {
        log.debug("number of plans to export: " + ppList.size());
        String filename = "allprojects.zip";

        lastProjectExportPath = OS.getTmpPath() + "export" + System.currentTimeMillis() + "/";
        new File(lastProjectExportPath).mkdirs();

        String binarydataTempPath = lastProjectExportPath + "binarydata/";
        File binarydataTempDir = new File(binarydataTempPath);
        binarydataTempDir.mkdirs();

        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(lastProjectExportPath + filename));
            ZipOutputStream zipOut = new ZipOutputStream(out);

            for (PlanProperties pp : ppList) {
                log.debug("EXPORTING: " + pp.getName());
                ZipEntry zipAdd = new ZipEntry(String.format("%1$03d", pp.getId()) + "-"
                        + FileUtils.makeFilename(pp.getName()) + ".xml");
                zipOut.putNextEntry(zipAdd);
                // export the complete project, including binary data
                exportComplete(pp.getId(), zipOut, binarydataTempPath);
                zipOut.closeEntry();
            }
            zipOut.close();
            out.close();
            new File(lastProjectExportPath + "finished.info").createNewFile();

            // FacesMessages.instance().add(FacesMessage.SEVERITY_INFO,
            // "Export was written to: " + exportPath);
            log.info("Export was written to: " + lastProjectExportPath);
        } catch (IOException e) {
            // FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
            // "An error occured while generating the export file.");
            log.error("An error occured while generating the export file.", e);
            File errorInfo = new File(lastProjectExportPath + "error.info");
            try {
                Writer w = new FileWriter(errorInfo);
                w.write("An error occured while generating the export file:");
                w.write(e.getMessage());
                w.close();
            } catch (IOException e1) {
                log.error("Could not write error file.");
            }

            return false;
        } finally {
            // remove all binary temp files
            OS.deleteDirectory(binarydataTempDir);
        }
    }

    return true;
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

protected File generateZipFile(final String contextPath, final String password, byte[] idpMetadata,
        byte[] keystore, EntityDescriptor descriptor) throws IOException {
    File zipFile = File.createTempFile("oiosaml-", ".zip");
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
    zos.putNextEntry(new ZipEntry("oiosaml-sp.properties"));
    zos.write(renderTemplate("defaultproperties.vm", new HashMap<String, Object>() {
        {//from ww w  . ja v  a 2s .  c om
            put("homename", Constants.PROP_HOME);

            put("servletPath", contextPath);
            put("password", password);
        }
    }, false).getBytes());
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("metadata/SP/SPMetadata.xml"));
    zos.write(SAMLUtil.getSAMLObjectAsPrettyPrintXML(descriptor).getBytes());
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("metadata/IdP/IdPMetadata.xml"));
    zos.write(idpMetadata);
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("certificate/keystore"));
    zos.write(keystore);
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("oiosaml-sp.log4j.xml"));
    IOUtils.copy(getClass().getResourceAsStream("oiosaml-sp.log4j.xml"), zos);
    zos.closeEntry();

    zos.close();
    return zipFile;
}

From source file:gov.va.chir.tagline.dao.FileDao.java

private static void saveZipFile(final File zipFile, final File... inputFiles) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

    for (File file : inputFiles) {
        final ZipEntry entry = new ZipEntry(file.getName());
        zos.putNextEntry(entry);/*www .j  av  a2  s.  c om*/

        final FileInputStream in = new FileInputStream(file);
        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

        in.close();
        zos.closeEntry();
    }

    zos.close();
}

From source file:com.mvdb.etl.actions.ActionUtils.java

public static void zipFullDirectory(String sourceDir, String targetZipFile) {
    FileOutputStream fos = null;/*from  w w w.  jav  a 2s . c o  m*/
    BufferedOutputStream bos = null;
    ZipOutputStream zos = null;

    try {
        fos = new FileOutputStream(targetZipFile);
        bos = new BufferedOutputStream(fos);
        zos = new ZipOutputStream(bos);
        zipDir(sourceDir, new File(sourceDir), zos);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (zos != null) {
            try {
                zos.flush();
                zos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (bos != null) {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}