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.intellij.diagnostic.SubmitPerformanceReportAction.java

@Override
public void actionPerformed(final AnActionEvent e) {
    String reportFileName = "perf_" + ApplicationInfo.getInstance().getBuild().asString() + "_"
            + SystemProperties.getUserName() + "_" + myDateFormat.format(new Date()) + ".zip";
    final File reportPath = new File(SystemProperties.getUserHome(), reportFileName);
    final File logDir = new File(PathManager.getLogPath());
    final Project project = e.getData(CommonDataKeys.PROJECT);

    final boolean[] archiveCreated = new boolean[1];
    final boolean completed = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
        @Override//from  w w w. j av a 2s . co m
        public void run() {
            try {
                ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(reportPath));
                ZipUtil.addDirToZipRecursively(zip, reportPath, logDir, "", new FileFilter() {
                    @Override
                    public boolean accept(final File pathname) {
                        ProgressManager.checkCanceled();

                        if (logDir.equals(pathname.getParentFile())) {
                            return pathname.getPath().contains("threadDumps");
                        }
                        return true;
                    }
                }, null);
                zip.close();
                archiveCreated[0] = true;
            } catch (final IOException ex) {
                ApplicationManager.getApplication().invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        Messages.showErrorDialog(project,
                                "Failed to create performance report archive: " + ex.getMessage(),
                                MESSAGE_TITLE);
                    }
                });
            }
        }
    }, "Collecting Performance Report data", true, project);

    if (!completed || !archiveCreated[0]) {
        return;
    }

    int rc = Messages.showYesNoDialog(project,
            "The performance report has been saved to\n" + reportPath
                    + "\n\nWould you like to submit it to JetBrains?",
            MESSAGE_TITLE, Messages.getQuestionIcon());
    if (rc == Messages.YES) {
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "Uploading Performance Report") {
            @Override
            public void run(@NotNull final ProgressIndicator indicator) {
                final String error = uploadFileToFTP(reportPath, "ftp.intellij.net", ".uploads", indicator);
                if (error != null) {
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Messages.showErrorDialog(error, MESSAGE_TITLE);
                        }
                    });
                }
            }
        });
    }
}

From source file:interactivespaces.controller.client.node.SpaceControllerDataBundleManager.java

/**
 * Create a data bundle for this controller.
 *
 * @return the created data bundle file//  w ww .  jav  a 2  s  .  c  om
 */
private File createDataBundle() {
    File dataBundle = generateDataBundleTempFile();
    ZipOutputStream zipOutputStream = null;
    try {
        zipOutputStream = fileSupport.createZipOutputStream(dataBundle);
        addDataBundleSection(zipOutputStream, CONTROLLER_DATA_BUNDLE_ENTRY,
                getControllerDataContentDirectory());
        for (InstalledLiveActivity activity : spaceController.getAllInstalledLiveActivities()) {
            addDataBundleSection(zipOutputStream, ACTIVITY_DATA_BUNDLE_PREFIX + activity.getUuid(),
                    getActivityDataContentDirectory(activity));
        }
        zipOutputStream.close();
    } catch (Exception e) {
        dataBundle.delete();

        throw new InteractiveSpacesException(
                String.format("Error while zipping data bundle %s", dataBundle.getAbsolutePath()), e);
    } finally {
        Closeables.closeQuietly(zipOutputStream);
    }

    return dataBundle;
}

From source file:interactivespaces.controller.runtime.StandardSpaceControllerDataBundleManager.java

/**
 * Create a data bundle for this controller.
 *
 * @return the created data bundle file// w  w w .  ja v  a 2s  . co m
 */
private File createDataBundle() {
    File dataBundle = generateDataBundleTempFile();
    ZipOutputStream zipOutputStream = null;
    try {
        zipOutputStream = fileSupport.createZipOutputStream(dataBundle);
        addDataBundleSection(zipOutputStream, CONTROLLER_DATA_BUNDLE_ENTRY,
                getControllerDataContentDirectory());
        for (InstalledLiveActivity activity : spaceController.getAllInstalledLiveActivities()) {
            addDataBundleSection(zipOutputStream, ACTIVITY_DATA_BUNDLE_PREFIX + activity.getUuid(),
                    getActivityDataContentDirectory(activity));
        }
        zipOutputStream.close();
        zipOutputStream = null;
    } catch (Exception e) {
        dataBundle.delete();

        throw new InteractiveSpacesException(
                String.format("Error while zipping data bundle %s", dataBundle.getAbsolutePath()), e);
    } finally {
        fileSupport.close(zipOutputStream, true);
    }

    return dataBundle;
}

From source file:io.smartspaces.spacecontroller.runtime.StandardSpaceControllerDataBundleManager.java

/**
 * Create a data bundle for this controller.
 *
 * @return the created data bundle file/*  w  w w  .  j av a2 s .  c o  m*/
 */
private File createDataBundle() {
    File dataBundle = generateDataBundleTempFile();
    ZipOutputStream zipOutputStream = null;
    try {
        zipOutputStream = fileSupport.createZipOutputStream(dataBundle);
        addDataBundleSection(zipOutputStream, CONTROLLER_DATA_BUNDLE_ENTRY,
                getControllerDataContentDirectory());
        for (InstalledLiveActivity activity : spaceController.getAllInstalledLiveActivities()) {
            addDataBundleSection(zipOutputStream, ACTIVITY_DATA_BUNDLE_PREFIX + activity.getUuid(),
                    getActivityDataContentDirectory(activity));
        }
        zipOutputStream.close();
        zipOutputStream = null;
    } catch (Exception e) {
        dataBundle.delete();

        throw new SmartSpacesException(
                String.format("Error while zipping data bundle %s", dataBundle.getAbsolutePath()), e);
    } finally {
        fileSupport.close(zipOutputStream, true);
    }

    return dataBundle;
}

From source file:hudson.FilePathTest.java

private InputStream someZippedContent() throws IOException {
    final ByteArrayOutputStream buf = new ByteArrayOutputStream();
    final ZipOutputStream zip = new ZipOutputStream(buf);

    zip.putNextEntry(new ZipEntry("abc"));
    zip.write("abc".getBytes());
    zip.close();

    return new ByteArrayInputStream(buf.toByteArray());
}

From source file:com.joliciel.talismane.extensions.corpus.CorpusStatistics.java

@Override
public void onCompleteParse() {
    try {/*w  w w .  ja v  a2 s .  c o m*/
        if (writer != null) {
            double unknownLexiconPercent = 1;
            if (referenceWords != null) {
                int unknownLexiconCount = 0;
                for (String word : words) {
                    if (!referenceWords.contains(word))
                        unknownLexiconCount++;
                }
                unknownLexiconPercent = (double) unknownLexiconCount / (double) words.size();
            }
            double unknownLowercaseLexiconPercent = 1;
            if (referenceLowercaseWords != null) {
                int unknownLowercaseLexiconCount = 0;
                for (String lowercase : lowerCaseWords) {
                    if (!referenceLowercaseWords.contains(lowercase))
                        unknownLowercaseLexiconCount++;
                }
                unknownLowercaseLexiconPercent = (double) unknownLowercaseLexiconCount
                        / (double) lowerCaseWords.size();
            }

            writer.write(CSV.format("sentenceCount") + CSV.format(sentenceCount) + "\n");
            writer.write(CSV.format("sentenceLengthMean") + CSV.format(sentenceLengthStats.getMean()) + "\n");
            writer.write(CSV.format("sentenceLengthStdDev")
                    + CSV.format(sentenceLengthStats.getStandardDeviation()) + "\n");
            writer.write(CSV.format("tokenLexiconSize") + CSV.format(words.size()) + "\n");
            writer.write(CSV.format("tokenLexiconUnknown") + CSV.format(unknownLexiconPercent * 100.0) + "\n");
            writer.write(CSV.format("tokenCount") + CSV.format(tokenCount) + "\n");

            double unknownTokenPercent = ((double) unknownTokenCount / (double) tokenCount) * 100.0;
            writer.write(CSV.format("tokenUnknown") + CSV.format(unknownTokenPercent) + "\n");

            writer.write(CSV.format("lowercaseLexiconSize") + CSV.format(lowerCaseWords.size()) + "\n");
            writer.write(CSV.format("lowercaseLexiconUnknown")
                    + CSV.format(unknownLowercaseLexiconPercent * 100.0) + "\n");
            writer.write(CSV.format("alphanumericCount") + CSV.format(alphanumericCount) + "\n");

            double unknownAlphanumericPercent = ((double) unknownAlphanumericCount / (double) alphanumericCount)
                    * 100.0;
            writer.write(CSV.format("alphanumericUnknown") + CSV.format(unknownAlphanumericPercent) + "\n");

            writer.write(CSV.format("syntaxDepthMean") + CSV.format(syntaxDepthStats.getMean()) + "\n");
            writer.write(CSV.format("syntaxDepthStdDev") + CSV.format(syntaxDepthStats.getStandardDeviation())
                    + "\n");
            writer.write(CSV.format("maxSyntaxDepthMean") + CSV.format(maxSyntaxDepthStats.getMean()) + "\n");
            writer.write(CSV.format("maxSyntaxDepthStdDev")
                    + CSV.format(maxSyntaxDepthStats.getStandardDeviation()) + "\n");
            writer.write(
                    CSV.format("sentAvgSyntaxDepthMean") + CSV.format(avgSyntaxDepthStats.getMean()) + "\n");
            writer.write(CSV.format("sentAvgSyntaxDepthStdDev")
                    + CSV.format(avgSyntaxDepthStats.getStandardDeviation()) + "\n");
            writer.write(CSV.format("syntaxDistanceMean") + CSV.format(syntaxDistanceStats.getMean()) + "\n");
            writer.write(CSV.format("syntaxDistanceStdDev")
                    + CSV.format(syntaxDistanceStats.getStandardDeviation()) + "\n");

            double nonProjectivePercent = ((double) nonProjectiveCount / (double) totalDepCount) * 100.0;
            writer.write(CSV.format("nonProjectiveCount") + CSV.format(nonProjectiveCount) + "\n");
            writer.write(CSV.format("nonProjectivePercent") + CSV.format(nonProjectivePercent) + "\n");
            writer.write(CSV.format("PosTagCounts") + "\n");

            for (String posTag : posTagCounts.keySet()) {
                int count = posTagCounts.get(posTag);
                writer.write(CSV.format(posTag) + CSV.format(count)
                        + CSV.format(((double) count / (double) tokenCount) * 100.0) + "\n");
            }

            writer.write(CSV.format("DepLabelCounts") + "\n");
            for (String depLabel : depLabelCounts.keySet()) {
                int count = depLabelCounts.get(depLabel);
                writer.write(CSV.format(depLabel) + CSV.format(count)
                        + CSV.format(((double) count / (double) totalDepCount) * 100.0) + "\n");
            }
            writer.flush();
            writer.close();
        }

        if (this.serializationFile != null) {
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(serializationFile, false));
            zos.putNextEntry(new ZipEntry("Contents.obj"));
            ObjectOutputStream oos = new ObjectOutputStream(zos);
            try {
                oos.writeObject(this);
            } finally {
                oos.flush();
            }
            zos.flush();
            zos.close();
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }

}

From source file:de.hybris.platform.impex.jalo.ImpExMediasImportTest.java

/**
 * Calls the <code>importData</code> method of given handler with an zip-file path in different formats.
 * /*w  w w . ja  va  2 s.  com*/
 * @param handler
 *           handler which will be used for test
 * @param media
 *           media where the data will be imported to
 */
private void mediaImportFromMediasMedia(final MediaDataHandler handler, final Media media,
        final ImpExImportCronJob cronJob) {
    MediaDataHandler myHandler = handler;
    File testFile = null;
    try {
        testFile = File.createTempFile("mediaImportTest", ".zip");
        final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testFile));
        zos.putNextEntry(new ZipEntry(new File("notunzip\\notexist.txt").getPath()));
        zos.putNextEntry(new ZipEntry(new File("files\\dummy.txt").getPath()));
        zos.putNextEntry(new ZipEntry(new File("files\\test.txt").getPath()));
        final PrintWriter printer = new PrintWriter(zos);
        printer.print("testest");
        printer.flush();
        zos.flush();
        printer.close();
        zos.close();
    } catch (final IOException e) {
        fail(e.getMessage());
    }
    try {
        final Media mediasMedia = ImpExManager.getInstance().createImpExMedia("mediasMedia", "UTF-8",
                new FileInputStream(testFile));
        cronJob.setMediasMedia(mediasMedia);

        mediaImport(myHandler, media, "files/test.txt", "testest");
        myHandler.cleanUp();
        myHandler = new DefaultCronJobMediaDataHandler(cronJob);
        mediaImport(myHandler, media, "files\\test.txt", "testest");
        myHandler.cleanUp();
        cronJob.setMediasTarget("files");
        myHandler = new DefaultCronJobMediaDataHandler(cronJob);
        mediaImport(myHandler, media, "test.txt", "testest");
        myHandler.cleanUp();
        cronJob.setMediasTarget(null);
    } catch (final Exception e) {
        fail(e.getMessage());
    }
    if (!testFile.delete()) {
        fail("Can not delete temp file: " + testFile.getPath());
    }
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 * @param basePath/*from  w  w w  . j a va2s.  c  o m*/
 * @param zipPath
 * @param filePaths
 * @throws java.io.IOException
 */
public static void zip(File basePath, File zipPath, Map<String, String> filePaths) throws IOException {
    BufferedInputStream origin = null;
    ZipOutputStream out = null;
    FileOutputStream dest = null;
    try {
        dest = new FileOutputStream(zipPath);
        out = new ZipOutputStream(new BufferedOutputStream(dest));
        //out.setMethod(ZipOutputStream.DEFLATED);
        byte data[] = new byte[BUFFER];
        for (Map.Entry<String, String> file : filePaths.entrySet()) {
            String filename = file.getKey();
            String filePath = file.getValue();
            System.out.println("Adding: " + basePath.getPath() + filePath + " => " + filename);
            File f = new File(basePath, filePath);
            if (f.exists()) {
                FileInputStream fi = new FileInputStream(f);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(filename);
                entry.setCrc(FileUtils.checksumCRC32(new File(basePath, filePath)));
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
        }
    } finally {
        if (origin != null)
            origin.close();
        if (out != null)
            out.close();
        if (dest != null)
            dest.close();
    }
}

From source file:net.librec.util.FileUtil.java

/**
 * Zip a given folder/*from w  ww.ja v  a  2s.  co  m*/
 *
 * @param dirPath    a given folder: must be all files (not sub-folders)
 * @param filePath   zipped file
 * @throws Exception if error occurs
 */
public static void zipFolder(String dirPath, String filePath) throws Exception {
    File outFile = new File(filePath);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outFile));
    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();
    for (File file : listFiles(dirPath)) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        crc.reset();
        while ((bytesRead = bis.read(buffer)) != -1) {
            crc.update(buffer, 0, bytesRead);
        }
        bis.close();

        // Reset to beginning of input stream
        bis = new BufferedInputStream(new FileInputStream(file));
        ZipEntry entry = new ZipEntry(file.getName());
        entry.setMethod(ZipEntry.STORED);
        entry.setCompressedSize(file.length());
        entry.setSize(file.length());
        entry.setCrc(crc.getValue());
        zos.putNextEntry(entry);
        while ((bytesRead = bis.read(buffer)) != -1) {
            zos.write(buffer, 0, bytesRead);
        }
        bis.close();
    }
    zos.close();

    LOG.debug("A zip-file is created to: " + outFile.getPath());
}

From source file:it.geosolutions.tools.compress.file.Compressor.java

/**
 * This function zip the input directory.
 * //from w  w  w . j a  v a2s.  c  om
 * @param directory
 *            The directory to be zipped.
 * @param base
 *            The base directory.
 * @param out
 *            The zip output stream.
 * @throws IOException
 */
public static void zipDirectory(final File directory, final File base, final ZipOutputStream out)
        throws IOException {

    if (directory != null && base != null && out != null) {
        File[] files = directory.listFiles();
        byte[] buffer = new byte[4096];
        int read = 0;

        FileInputStream in = null;
        ZipEntry entry = null;

        try {
            for (int i = 0, n = files.length; i < n; i++) {
                if (files[i].isDirectory()) {
                    zipDirectory(files[i], base, out);
                } else {
                    in = new FileInputStream(files[i]);
                    entry = new ZipEntry(base.getName().concat("\\")
                            .concat(files[i].getPath().substring(base.getPath().length() + 1)));
                    out.putNextEntry(entry);

                    while (-1 != (read = in.read(buffer))) {
                        out.write(buffer, 0, read);
                    }

                    // //////////////////////
                    // Complete the entry
                    // //////////////////////

                    out.closeEntry();

                    in.close();
                    in = null;
                }
            }

        } catch (IOException e) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error(e.getLocalizedMessage(), e);
            if (out != null)
                out.close();
        } finally {
            if (in != null)
                in.close();
        }

    } else
        throw new IOException("One or more input parameters are null!");
}