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:org.cloudfoundry.tools.io.zip.ZipArchiveTest.java

@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.zipFile = this.temporaryFolder.newFile("zipfile.zip");
    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(this.zipFile));
    try {//from   w w w  .  jav  a2  s. c  om
        zipOutputStream.putNextEntry(new ZipEntry("/a/b/c.txt"));
        zipOutputStream.write("c".getBytes());
        zipOutputStream.putNextEntry(new ZipEntry("/d/"));
        zipOutputStream.putNextEntry(new ZipEntry("/d/e/"));
        zipOutputStream.putNextEntry(new ZipEntry("/d/f/"));
        zipOutputStream.putNextEntry(new ZipEntry("/d/f/g.txt"));
        zipOutputStream.putNextEntry(new ZipEntry("/d/f/h/"));
        zipOutputStream.write("g".getBytes());
    } finally {
        zipOutputStream.close();
    }
    this.zip = new ZipArchive(new LocalFolder(this.zipFile.getParentFile()).getFile(this.zipFile.getName()));
}

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  a va  2  s .c  o  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:gov.nih.nci.caarray.services.external.v1_0.grid.client.GridDataApiUtils.java

/**
 * {@inheritDoc}//from  w w  w  .  j a  va2 s .c o m
 */
public void copyFileContentsZipToOutputStream(Iterable<CaArrayEntityReference> fileRefs, OutputStream ostream)
        throws InvalidReferenceException, DataTransferException, IOException {
    ZipOutputStream zos = new ZipOutputStream(ostream);
    for (CaArrayEntityReference fileRef : fileRefs) {
        TransferServiceContextReference transferRef = getFileContentsTransfer(fileRef, true);
        addToZip(transferRef, zos);
    }
    zos.finish();
}

From source file:com.metamx.druid.loading.S3SegmentPusher.java

@Override
public DataSegment push(File file, DataSegment segment) throws IOException {
    log.info("Uploading [%s] to S3", file);
    String outputKey = JOINER.join(config.getBaseKey().isEmpty() ? null : config.getBaseKey(),
            segment.getDataSource(),//from w  ww  . j  a  va  2s  .co  m
            String.format("%s_%s", segment.getInterval().getStart(), segment.getInterval().getEnd()),
            segment.getVersion(), segment.getShardSpec().getPartitionNum());

    File indexFilesDir = file;

    long indexSize = 0;
    final File zipOutFile = File.createTempFile("druid", "index.zip");
    ZipOutputStream zipOut = null;
    try {
        zipOut = new ZipOutputStream(new FileOutputStream(zipOutFile));
        File[] indexFiles = indexFilesDir.listFiles();
        for (File indexFile : indexFiles) {
            log.info("Adding indexFile[%s] with size[%,d].  Total size[%,d]", indexFile, indexFile.length(),
                    indexSize);
            if (indexFile.length() >= Integer.MAX_VALUE) {
                throw new ISE("indexFile[%s] too large [%,d]", indexFile, indexFile.length());
            }
            zipOut.putNextEntry(new ZipEntry(indexFile.getName()));
            IOUtils.copy(new FileInputStream(indexFile), zipOut);
            indexSize += indexFile.length();
        }
    } finally {
        Closeables.closeQuietly(zipOut);
    }

    try {
        S3Object toPush = new S3Object(zipOutFile);

        final String outputBucket = config.getBucket();
        toPush.setBucketName(outputBucket);
        toPush.setKey(outputKey + "/index.zip");

        log.info("Pushing %s.", toPush);
        s3Client.putObject(outputBucket, toPush);

        DataSegment outputSegment = segment.withSize(indexSize).withLoadSpec(ImmutableMap
                .<String, Object>of("type", "s3_zip", "bucket", outputBucket, "key", toPush.getKey()));

        File descriptorFile = File.createTempFile("druid", "descriptor.json");
        StreamUtils.copyToFileAndClose(new ByteArrayInputStream(jsonMapper.writeValueAsBytes(segment)),
                descriptorFile);
        S3Object descriptorObject = new S3Object(descriptorFile);
        descriptorObject.setBucketName(outputBucket);
        descriptorObject.setKey(outputKey + "/descriptor.json");

        log.info("Pushing %s", descriptorObject);
        s3Client.putObject(outputBucket, descriptorObject);

        log.info("Deleting Index File[%s]", indexFilesDir);
        FileUtils.deleteDirectory(indexFilesDir);

        log.info("Deleting zipped index File[%s]", zipOutFile);
        zipOutFile.delete();

        log.info("Deleting descriptor file[%s]", descriptorFile);
        descriptorFile.delete();

        return outputSegment;
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (S3ServiceException e) {
        throw new IOException(e);
    }
}

From source file:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java

/**
 * Given a DITA map bounded object set, zips it up into a DXP Zip package.
 * @param mapBos//ww  w  .j  av  a 2 s.  co  m
 * @param outputZipFile
 * @throws Exception 
 */
public static void zipMapBos(DitaBoundedObjectSet mapBos, File outputZipFile, MapBosProcessorOptions options)
        throws Exception {
    /*
     *  Some potential complexities:
     *  
     *  - DXP package spec requires either a map manifest or that 
     *  there be exactly one map at the root of the zip package. This 
     *  means that the file structure of the BOS needs to be checked to
     *  see if the files already conform to this structure and, if not,
     *  they need to be reorganized and have pointers rewritten if a 
     *  map manifest has not been requested.
     *  
     *  - If the file structure of the original data includes files not
     *  below the root map, the file organization must be reworked whether
     *  or not a map manifest has been requested.
     *  
     *  - Need to generate DXP map manifest if a manifest is requested.
     *  
     *  - If user has requested that the original file structure be 
     *  remembered, a manifest must be generated.
     */

    log.debug("Determining zip file organization...");

    BosVisitor visitor = new DxpFileOrganizingBosVisitor();
    visitor.visit(mapBos);

    if (!options.isQuiet())
        log.info("Creating DXP package \"" + outputZipFile.getAbsolutePath() + "\"...");
    OutputStream outStream = new FileOutputStream(outputZipFile);
    ZipOutputStream zipOutStream = new ZipOutputStream(outStream);

    ZipEntry entry = null;

    // At this point, URIs of all members should reflect their
    // storage location within the resulting DXP package. There
    // must also be a root map, either the original map
    // we started with or a DXP manifest map.

    URI rootMapUri = mapBos.getRoot().getEffectiveUri();
    URI baseUri = null;
    try {
        baseUri = AddressingUtil.getParent(rootMapUri);
    } catch (URISyntaxException e) {
        throw new BosException("URI syntax exception getting parent URI: " + e.getMessage());
    }

    Set<String> dirs = new HashSet<String>();

    if (!options.isQuiet())
        log.info("Constructing DXP package...");
    for (BosMember member : mapBos.getMembers()) {
        if (!options.isQuiet())
            log.info("Adding member " + member + " to zip...");
        URI relativeUri = baseUri.relativize(member.getEffectiveUri());
        File temp = new File(relativeUri.getPath());
        String parentPath = temp.getParent();
        if (parentPath != null && !"".equals(parentPath) && !parentPath.endsWith("/")) {
            parentPath += "/";
        }
        log.debug("parentPath=\"" + parentPath + "\"");
        if (!"".equals(parentPath) && parentPath != null && !dirs.contains(parentPath)) {
            entry = new ZipEntry(parentPath);
            zipOutStream.putNextEntry(entry);
            zipOutStream.closeEntry();
            dirs.add(parentPath);
        }
        entry = new ZipEntry(relativeUri.getPath());
        zipOutStream.putNextEntry(entry);
        IOUtils.copy(member.getInputStream(), zipOutStream);
        zipOutStream.closeEntry();
    }

    zipOutStream.close();
    if (!options.isQuiet())
        log.info("DXP package \"" + outputZipFile.getAbsolutePath() + "\" created.");
}

From source file:com.microsoft.tfs.client.common.ui.framework.diagnostics.export.ExportRunnable.java

@Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    error = null;// w  ww . ja v a  2 s .  c om
    errored = false;

    ZipOutputStream zipout = null;

    final DataProviderWrapper[] exportableDataProviders = allProvidersCollection.getExportableDataProviders();
    final DataProviderCollection exportableCollection = new DataProviderCollection(exportableDataProviders);
    final DataProviderWrapper[] providersWithExportHandlers = exportableCollection
            .getDataProvidersWithExportHandlers();

    monitor.beginTask(Messages.getString("ExportRunnable.ExportingProgress"), //$NON-NLS-1$
            exportableDataProviders.length + providersWithExportHandlers.length);

    try {
        final FileOutputStream fos = new FileOutputStream(outputFile);
        final BufferedOutputStream bos = new BufferedOutputStream(fos);
        zipout = new ZipOutputStream(bos);

        processDataProviders(exportableCollection, zipout, monitor);
        processExportHandlers(providersWithExportHandlers, zipout, monitor);
    } catch (final Throwable t) {
        error = t;
        errored = true;
    } finally {
        if (zipout != null) {
            try {
                zipout.close();
            } catch (final IOException e) {
            }
        }

        cancelled = monitor.isCanceled();

        if (cancelled || errored) {
            outputFile.delete();
        }
    }
}

From source file:ch.rgw.compress.CompEx.java

public static byte[] CompressZIP(InputStream in) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[8192];
    baos.write(buf, 0, 4); // Lnge des Originalstroms
    ZipOutputStream zo = new ZipOutputStream(baos);
    zo.putNextEntry(new ZipEntry("Data"));
    int l;/*  ww  w.  ja  v  a  2 s .c  o m*/
    long total = 0;
    ;
    while ((l = in.read(buf, 0, buf.length)) != -1) {
        zo.write(buf, 0, l);
        total += l;
    }
    zo.close();
    byte[] ret = baos.toByteArray();
    // Die hchstwertigen 3 Bit als Typmarker setzen
    total &= 0x1fffffff;
    total |= ZIP;
    BinConverter.intToByteArray((int) total, ret, 0);
    return ret;
}

From source file:hudson.plugins.doclinks.artifacts.testtools.TestZipBuilder.java

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {
    FilePath file = build.getWorkspace().child(filename);
    FilePath dir = file.getParent();//from  w  w w  .j a  v a 2 s  .  com

    if (dir != null && !dir.exists()) {
        dir.mkdirs();
    }

    String seperator = System.getProperty("file.separator");
    String resourceDirName = StringUtils.join(getClass().getName().split("\\."), seperator);
    File resourceDir = null;
    try {
        resourceDir = new File(ClassLoader.getSystemResource(resourceDirName).toURI());
    } catch (URISyntaxException e) {
        listener.getLogger().println("Failed to retrieve contents to zip");
        e.printStackTrace(listener.getLogger());
    }

    OutputStream os = null;
    ZipOutputStream zos = null;

    try {
        os = file.write();
        zos = new ZipOutputStream(os);

        compress(zos, resourceDir, null);
    } finally {
        if (zos != null) {
            zos.close();
        }

        if (os != null) {
            os.close();
        }
    }

    return true;
}

From source file:de.tor.tribes.util.AttackToTextWriter.java

private static boolean writeBlocksToZip(List<String> pBlocks, Tribe pTribe, File pPath) {
    int fileNo = 1;
    String baseFilename = pTribe.getName().replaceAll("\\W+", "");
    ZipOutputStream zout = null;//ww  w  . j  ava 2 s  . c o m
    try {
        zout = new ZipOutputStream(
                new FileOutputStream(FilenameUtils.concat(pPath.getPath(), baseFilename + ".zip")));
        for (String block : pBlocks) {
            String entryName = baseFilename + fileNo + ".txt";
            ZipEntry entry = new ZipEntry(entryName);
            try {
                zout.putNextEntry(entry);
                zout.write(block.getBytes());
                zout.closeEntry();
            } catch (IOException ioe) {
                logger.error("Failed to write attack to zipfile", ioe);
                return false;
            }
            fileNo++;
        }
    } catch (IOException ioe) {
        logger.error("Failed to write content to zip file", ioe);
        return false;
    } finally {
        if (zout != null) {
            try {
                zout.flush();
                zout.close();
            } catch (IOException ignored) {
            }
        }
    }
    return true;
}

From source file:com.ibm.liberty.starter.ProjectZipConstructor.java

public void buildZip(OutputStream os)
        throws IOException, SAXException, ParserConfigurationException, TransformerException {
    initializeMap();/*from ww  w. j a v  a 2 s  .  co  m*/
    addHtmlToMap();
    addTechSamplesToMap();
    addPomFileToMap();
    ZipOutputStream zos = new ZipOutputStream(os);
    createZipFromMap(zos);
    zos.close();
}