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.ephesoft.gxt.batchinstance.server.BatchInfoDownloadServlet.java

/**
 * Closes the open resources./*from  w  ww  .  j  a  v a  2  s.  c o m*/
 * 
 * @param out {@link ServletOutputStream} the servlet output stream
 * @param zout {@link ZipOutputStream} the output stream for zip file
 * @param fout {@link FileOutputStream} the file output stream of zip file
 * @throws IOException if an exception occurs while closing the resources
 */
private void closeResources(final ServletOutputStream out, final ZipOutputStream zout,
        final FileOutputStream fout, final PrintWriter writer) throws IOException {
    if (writer != null) {
        writer.close();
    }
    if (zout != null) {
        zout.close();
    }
    if (out != null) {
        out.close();
    }
    if (fout != null) {
        fout.close();
    }
}

From source file:com.healthcit.analytics.servlet.DataExportServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String token = request.getParameter("token");
    TOKENS_MAP.put(token, DownloadStatus.STARTED);
    String keys = request.getParameter("keys");
    if (keys != null) {
        //JSONArray ownerIdsJSON = (JSONArray)JSONSerializer.toJSON(ownerIds ) ;
        String[] ownerIdsArray = StringUtils.split(keys, ",");

        response.setContentType(Constants.JSON_CONTENT_TYPE);
        response.addHeader(Constants.CONTENT_DISPOSITION, "attachment; filename=dataExport.zip");
        response.addHeader(Constants.PRAGMA_HEADER, Constants.NO_CACHE);

        response.setHeader(Constants.CACHE_CONTROL_HEADER, Constants.NO_CACHE);
        ServletOutputStream os = response.getOutputStream();
        ZipOutputStream zos = new ZipOutputStream(os);
        //         ZipEntry entry = new ZipEntry("dataExport."+OutputFormat.JSON.toString().toLowerCase());
        ZipEntry entry = new ZipEntry("dataExport." + OutputFormat.XML.toString().toLowerCase());
        zos.putNextEntry(entry);//from   ww  w. ja  v  a 2 s .co m
        //         OwnerDataManager ownerManager = new OwnerDataManager(OutputFormat.JSON);
        OwnerDataManager ownerManager = new OwnerDataManager(OutputFormat.XML);
        try {
            ownerManager.getEntitiesData(ownerIdsArray, zos);
            TOKENS_MAP.put(token, DownloadStatus.FINISHED);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            TOKENS_MAP.put(token, DownloadStatus.ERROR);
        } finally {
            zos.close();
            //            os.flush();

            //            os.close();
        }
    } else {
        TOKENS_MAP.put(token, DownloadStatus.ERROR);
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void attachOutputs(ReportExecutionJob job, MimeMessageHelper messageHelper, List reportOutputs)
        throws MessagingException, JobExecutionException {
    String attachmentName = null;
    DataContainer attachmentData = job.createDataContainer();
    boolean close = true;
    ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
    try {//from  www  .  ja  v a2s  . c o  m
        for (Iterator it = reportOutputs.iterator(); it.hasNext();) {
            ReportOutput output = (ReportOutput) it.next();
            if (attachmentName == null)
                attachmentName = removeExtension(output.getFilename()) + ".zip";
            zipOutput(job, output, zipOut);
        }
        zipOut.finish();
        zipOut.flush();
        close = false;
        zipOut.close();
    } catch (IOException e) {
        throw new JSExceptionWrapper(e);
    } finally {
        if (close) {
            try {
                zipOut.close();
            } catch (IOException e) {
                log.error("Error closing stream", e);
            }
        }
    }
    try {
        attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
    } catch (UnsupportedEncodingException e) {
        throw new JSExceptionWrapper(e);
    }
    messageHelper.addAttachment(attachmentName, new DataContainerResource(attachmentData));
}

From source file:com.genericworkflownodes.knime.workflowexporter.export.impl.GuseKnimeWorkflowExporter.java

@Override
public void export(final Workflow workflow, final File destination) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(/*from   ww  w .j av a  2 s .c o m*/
                "exporting using " + getShortDescription() + " to [" + destination.getAbsolutePath() + "]");
    }
    final StringBuilder builder = new StringBuilder();
    generateWorkflowXml(workflow, builder);

    final ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(destination));
    zipOutputStream.putNextEntry(new ZipEntry("workflow.xml"));

    zipOutputStream.write(formatXml(builder.toString()).getBytes());

    zipOutputStream.closeEntry();
    zipOutputStream.close();
}

From source file:mergedoc.core.MergeManager.java

/**
 * ????<br>//from  w ww .  ja v  a2  s.c  o  m
 * @throws MergeDocException ??????
 * @throws SAXException SAX ????
 * @throws IOException ????
 */
public void execute() throws MergeDocException, SAXException, IOException {

    if (workingState.isCanceled()) {
        return;
    }
    ArchiveInputStream in = null;
    ZipOutputStream out = null;

    try {
        in = ArchiveInputStream.create(pref.getInputArchive());

        out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(pref.getOutputArchive())));
        out.setLevel(Deflater.BEST_SPEED);

        long start = System.currentTimeMillis();
        merge(in, out);
        long end = System.currentTimeMillis();
        workingState.setWorkTime((end - start) / 1000);

    } finally {

        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.xpn.xwiki.plugin.packaging.AbstractPackageTest.java

/**
 * Create a XAR file using java.util.zip.
 *
 * @param docs The documents to include.
 * @param encodings The charset for each document.
 * @param packageXmlEncoding The encoding of package.xml
 * @return the XAR file as a byte array.
 */// w  w  w.j  ava 2  s. co m
protected byte[] createZipFile(XWikiDocument docs[], String[] encodings, String packageXmlEncoding)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry zipp = new ZipEntry("package.xml");
    zos.putNextEntry(zipp);
    zos.write(getEncodedByteArray(getPackageXML(docs, packageXmlEncoding), packageXmlEncoding));
    for (int i = 0; i < docs.length; i++) {
        String zipEntryName = docs[i].getSpace() + "/" + docs[i].getName();
        if (docs[i].getTranslation() != 0) {
            zipEntryName += "." + docs[i].getLanguage();
        }
        ZipEntry zipe = new ZipEntry(zipEntryName);
        zos.putNextEntry(zipe);
        String xmlCode = docs[i].toXML(false, false, false, false, getContext());
        zos.write(getEncodedByteArray(xmlCode, encodings[i]));
    }
    zos.finish();
    zos.close();
    return baos.toByteArray();
}

From source file:isl.FIMS.utils.Utils.java

public static void createZip(String zipFile, String sourceDirectory) {
    try {/*  w w  w  .  j a  va  2 s  .  c  o m*/
        // String zipFile = "C:/FileIO/zipdemo.zip";
        // String sourceDirectory = "C:/examples";

        //create byte buffer
        byte[] buffer = new byte[1024];
        //create object of FileOutputStream
        FileOutputStream fout = new FileOutputStream(zipFile);
        //create object of ZipOutputStream from FileOutputStream
        ZipOutputStream zout = new ZipOutputStream(fout);
        //create File object from directory name
        File dir = new File(sourceDirectory);

        //check to see if this directory exists
        if (!dir.isDirectory()) {
        } else {
            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    //create object of FileInputStream for source file
                    FileInputStream fin = new FileInputStream(files[i]);
                    zout.putNextEntry(new ZipEntry(files[i].getName()));
                    int length;
                    while ((length = fin.read(buffer)) > 0) {
                        zout.write(buffer, 0, length);
                    }
                    zout.closeEntry();
                    //close the InputStream
                    fin.close();
                }
            }
        }

        //close the ZipOutputStream
        zout.close();
    } catch (IOException ioe) {
    }
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private String firmarImagen(int fileName) throws IOException {

    String result = "";
    try {/* ww  w  .j  a va  2 s  . c o  m*/
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();
        String theFolder = s + "/" + "archivos";

        FileOutputStream fos = new FileOutputStream(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
        ZipOutputStream zos = new ZipOutputStream(fos);

        String file1Name = theFolder + "/" + Integer.toString(fileName) + ".jpg";
        File image = new File(file1Name);

        ZipEntry zipEntry = new ZipEntry(image.getName());
        zos.putNextEntry(zipEntry);
        FileInputStream fileInputStream = new FileInputStream(image);

        byte[] buf = new byte[2048];
        int bytesRead;

        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            zos.write(buf, 0, bytesRead);
        }
        zos.closeEntry();
        zos.close();
        fos.close();

        Path path = Paths.get(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
        byte[] data = Files.readAllBytes(path);
        byte[] byteArray = Base64.encodeBase64(data);
        String b64 = new String(byteArray);

        result = firma(b64, Integer.toString(fileName), "pruebita");
        System.out.println("User : " + idSimulatedUser + " ENVIADO");
        nFilesSend++;

    } catch (FileNotFoundException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (WriterException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "http://" + result;
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private void consultarFirma(int fileNameId) {
    try {/*from   ww w.j  a v a 2 s.co m*/
        FileOutputStream fos = new FileOutputStream(
                userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.zip");
        ZipOutputStream zos = new ZipOutputStream(fos);

        String file1Name = userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.png";
        File image = new File(file1Name);

        ZipEntry zipEntry = new ZipEntry(image.getName());
        zos.putNextEntry(zipEntry);
        FileInputStream fileInputStream = new FileInputStream(image);

        byte[] buf = new byte[2048];
        int bytesRead;

        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            zos.write(buf, 0, bytesRead);
        }
        zos.closeEntry();
        zos.close();
        fos.close();

        Path path = Paths.get(userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.zip");

        byte[] data = Files.readAllBytes(path);
        byte[] byteArray = Base64.encodeBase64(data);
        String b64 = new String(byteArray);

        System.out.println(consultaFirma(b64, Integer.toString(fileNameId) + "Firmada"));

        nFilesVerified++;
        System.out.println("User : " + idSimulatedUser + " FIRMA VERIFICADA");
    } catch (IOException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        nNotFileFound++;
    } catch (IOException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        nVerifyErrors++;
    }
}

From source file:fr.simon.marquis.secretcodes.util.ExportContentProvider.java

private void saveZipFile() {
    File[] files = getContext().getFilesDir().listFiles();
    String zipPath = getContext().getFilesDir().getAbsolutePath() + "/" + ZIP_FILE_NAME;
    try {/*from   ww w .  ja v a 2  s  . c  om*/
        BufferedInputStream origin = null;
        FileOutputStream zipFile = new FileOutputStream(zipPath);

        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(zipFile));

        byte data[] = new byte[BUFFER];
        for (int i = 0; i < files.length; i++) {
            FileInputStream fi = new FileInputStream(files[i]);
            origin = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(
                    files[i].getAbsolutePath().substring(files[i].getAbsolutePath().lastIndexOf("/") + 1));
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }

        out.close();
        Log.d(this.getClass().getSimpleName(),
                "zipFile created at " + zipPath + " with " + files.length + " files");
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(this.getClass().getSimpleName(),
                "error while zipping at " + zipPath + " with " + files.length + " files", e);
    }

}