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.polimi.diceH2020.launcher.utility.FileUtility.java

private void zipFolder(@NotNull File srcFolder, @NotNull File destZipFile) throws IOException {
    try (ZipOutputStream zip = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(destZipFile)))) {
        addFolderToZip(null, srcFolder, zip);
    }//  w ww  . ja  va  2s. c  o m
}

From source file:game.com.HandleDownloadFolderServlet.java

private void handle(HttpServletRequest request, HttpServletResponse response, AjaxResponseEntity responseObject)
        throws Exception {

    String path = getPath(request);
    if (path == null) {
        responseObject.returnCode = 0;/*from   ww  w  .j a  va 2 s .  c  o  m*/
        responseObject.returnMessage = "invalid request";
        return;
    }
    File folder = new File(path);
    if (!folder.exists()) {
        responseObject.returnCode = 0;
        responseObject.returnMessage = "path not exist";
        return;
    }
    if (folder.getAbsolutePath().startsWith(AppConfig.OPENSHIFT_DATA_DIR) == false) {
        responseObject.returnCode = 0;
        responseObject.returnMessage = "invalid path";
        return;
    }
    try {

        File file = new File(path);

        if (!file.isDirectory()) {
            response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
            response.setHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
            Files.copy(file.toPath(), response.getOutputStream());
        } else {
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=\"allfiles.zip\"");

            try (ZipOutputStream output = new ZipOutputStream(
                    new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE))) {
                //                    for (File fileId : file.listFiles()) {
                //
                //                        InputStream input = null;
                //                        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                //                        try {
                //                            input = new BufferedInputStream(new FileInputStream(fileId), DEFAULT_BUFFER_SIZE);
                //                            output.putNextEntry(new ZipEntry(fileId.getName()));
                //                            for (int length = 0; (length = input.read(buffer)) > 0;) {
                //                                output.write(buffer, 0, length);
                //                            }
                //                            output.closeEntry();
                //                        } finally {
                //                            if (input != null) {
                //                                try {
                //                                    input.close();
                //                                } catch (Exception logOrIgnore) {
                //                                    logger.error(logOrIgnore.getMessage(), logOrIgnore);
                //                                }
                //                            }
                //                        }
                //                    }
                //                    outputZipStream(output, file);
                addDirToZipArchive(output, file, null);
            }
        }

        responseObject.returnCode = 1;
        responseObject.returnMessage = "success";

    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:gov.nih.nci.caintegrator.common.Cai2Util.java

/**
 * Takes in a directory and zips it up.//from w  w  w .  j  a  va 2  s . c  o m
 *
 * @param dir - Directory to zip.
 * @return Zipped file, stored in same location, with same name as the directory with .zip attached.
 * @throws IOException - In case cannot be read.
 */
public static File zipAndDeleteDirectory(String dir) throws IOException {
    File directory = new File(dir);
    if (!directory.isDirectory()) {
        throw new IllegalArgumentException("Not a directory:  " + dir);
    }
    int index = directory.getPath().indexOf(directory.getName());
    String[] entries = directory.list();
    if (entries.length == 0) {
        return null;
    }
    File zipfile = new File(dir + ZIP_FILE_SUFFIX);
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
    addDir(directory, out, index);
    out.close();
    FileUtils.deleteDirectory(directory);
    return zipfile;
}

From source file:com.adobe.communities.ugc.migration.legacyProfileExport.MessagesExportServlet.java

@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    final String headerKey = "Content-Disposition";
    final String headerValue = "attachment; filename=\"export.zip\"";
    response.setHeader(headerKey, headerValue);
    File outFile = null;/*from   w w  w. j  av a2 s . c  om*/
    exportedIds = new HashMap<String, Boolean>();
    messagesForExport = new HashMap<String, JSONObject>();
    try {
        outFile = File.createTempFile(UUID.randomUUID().toString(), ".zip");
        if (!outFile.canWrite()) {
            throw new ServletException("Cannot write to specified output file");
        }
        FileOutputStream fos = new FileOutputStream(outFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        zip = new ZipOutputStream(bos);
        responseWriter = new OutputStreamWriter(zip);
        OutputStream outStream = null;
        InputStream inStream = null;
        try {

            int start = 0;
            int increment = 100;
            try {
                do {
                    Iterable<Message> messages = messagingService.search(request.getResourceResolver(),
                            new MessageFilter(), start, start + increment);
                    if (messages.iterator().hasNext()) {
                        exportMessagesBatch(messages);
                    } else {
                        break;
                    }
                    start += increment;
                } while (true);
            } catch (final RepositoryException e) {
                // do nothing for now
            }
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            // obtains response's output stream
            outStream = response.getOutputStream();
            inStream = new FileInputStream(outFile);
            // copy from file to output
            IOUtils.copy(inStream, outStream);
        } catch (final IOException e) {
            throw new ServletException(e);
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(inStream);
            IOUtils.closeQuietly(outStream);
        }
    } finally {
        if (outFile != null) {
            outFile.delete();
        }
    }
}

From source file:jobhunter.persistence.Persistence.java

private void zip(final File file) {

    try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(file))) {
        l.debug("Generating JHF file");
        zout.setMethod(ZipOutputStream.DEFLATED);
        zout.setLevel(9);//w w w  . j  a  v  a2s  .  c  om

        l.debug("Inserting profile XML");
        zout.putNextEntry(new ZipEntry("profile.xml"));
        xstream.toXML(ProfileRepository.getProfile(), zout);

        l.debug("Inserting subscriptions XML");
        zout.putNextEntry(new ZipEntry("subscriptions.xml"));
        xstream.toXML(SubscriptionRepository.getSubscriptions(), zout);

        updateLastMod(file);
    } catch (IOException e) {
        l.error("Failed to generate file", e);
    }

}

From source file:ZipUtilInPlaceTest.java

public void testByteArrayTransformer() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file1 = File.createTempFile("temp", null);
    try {//w w  w . ja v  a  2 s.c  om
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Transform the ZIP file
        ZipUtil.transformEntry(file1, name, new ByteArrayZipEntryTransformer() {
            protected byte[] transform(ZipEntry zipEntry, byte[] input) throws IOException {
                String s = new String(input);
                assertEquals(new String(contents), s);
                return s.toUpperCase().getBytes();
            }
        });

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file1, name);
        assertNotNull(actual);
        assertEquals(new String(contents).toUpperCase(), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file1);
    }
}

From source file:com.cordys.coe.ac.emailio.archive.FileArchiver.java

/**
 * This method starts the actual archiving of the passed on context containers.
 *
 * @param   lccContainers  The containers to archive.
 * @param   spqmManager    The QueryManager to use.
 *
 * @throws  ArchiverException  In case of any exceptions.
 *
 * @see     com.cordys.coe.ac.emailio.archive.IArchiver#doArchive(java.util.List, com.cordys.coe.ac.emailio.objects.IStorageProviderQueryManager)
 *///  www . j  a  v a 2s  .  c  o m
@Override
public void doArchive(List<ContextContainer> lccContainers, IStorageProviderQueryManager spqmManager)
        throws ArchiverException {
    File fArchive = getArchiveFolder();

    for (ContextContainer ccContainer : lccContainers) {
        int iWrapperXML = 0;
        ZipOutputStream zosZip = null;
        File fZipFile = null;
        List<EmailMessage> lEmails = null;

        try {
            lEmails = spqmManager.getEmailMessagesByContextID(ccContainer.getID());

            // Create the ZipFile
            fZipFile = new File(fArchive, ccContainer.getID().replaceAll("[^a-zA-Z0-9]", "") + ".zip");
            zosZip = new ZipOutputStream(new FileOutputStream(fZipFile, false));
            zosZip.setLevel(m_iZipLevel);

            // Now we have both the container and the emails. We will create an XML
            // to hold all data.
            int iObjectData = ccContainer._getObjectData();

            // Create the zip entry for it.
            ZipEntry zeContainer = new ZipEntry("container.xml");
            zosZip.putNextEntry(zeContainer);

            String sXML = Node.writeToString(iObjectData, true);
            zosZip.write(sXML.getBytes());
            zosZip.closeEntry();

            // Add the email messages to the zip file.
            int iCount = 0;

            for (EmailMessage emMessage : lEmails) {
                iObjectData = emMessage._getObjectData();

                ZipEntry zeEmail = new ZipEntry("email_" + iCount++ + ".xml");
                zosZip.putNextEntry(zeEmail);

                sXML = Node.writeToString(iObjectData, true);
                zosZip.write(sXML.getBytes());
                zosZip.closeEntry();
            }

            // Now all files are written into a single Zip file, so we can close it.
        } catch (Exception e) {
            throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ARCHIVING_CONTAINER_0,
                    ccContainer.getID());
        } finally {
            if (iWrapperXML != 0) {
                Node.delete(iWrapperXML);
            }

            if (zosZip != null) {
                try {
                    zosZip.close();
                } catch (IOException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Error closing zip file " + fZipFile.getAbsolutePath(), e);
                    }
                }
            }
        }

        // If we get here the zipfile was successfully created. So now we need to remove the
        // mails and the container from the current storage provider.
        try {
            spqmManager.removeContextContainer(ccContainer);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Archived the container with id " + ccContainer.getID());
            }
        } catch (StorageProviderException e) {
            throw new ArchiverException(e,
                    ArchiverExceptionMessages.ARE_ERROR_REMOVING_CONTEXT_CONTAINER_0_FROM_THE_STORAGE,
                    ccContainer.getID());
        }
    }

    // Now all containers have been archived, we will create a single zip file.
    try {
        File fFinalArchive = new File(fArchive.getParentFile(), fArchive.getName() + ".zip");

        if (LOG.isDebugEnabled()) {
            LOG.debug("Archiving folder " + fArchive.getCanonicalPath() + " into file "
                    + fFinalArchive.getCanonicalPath());
        }

        new ZipUtil().compress(fArchive, fFinalArchive.getAbsolutePath());
    } catch (Exception e) {
        throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ZIPPING_ALL_ARCHIVE_FILES);
    }
}

From source file:com.adobe.communities.ugc.migration.export.MessagesExportServlet.java

@Override
protected void doGet(@Nonnull final SlingHttpServletRequest request,
        @Nonnull final SlingHttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    final String headerKey = "Content-Disposition";
    final String headerValue = "attachment; filename=\"export.zip\"";
    response.setHeader(headerKey, headerValue);
    File outFile = null;//from www. j av  a  2 s . co  m
    exportedIds = new HashMap<String, Boolean>();
    messagesForExport = new HashMap<String, JSONObject>();
    try {
        outFile = File.createTempFile(UUID.randomUUID().toString(), ".zip");
        if (!outFile.canWrite()) {
            throw new ServletException("Cannot write to specified output file");
        }
        FileOutputStream fos = new FileOutputStream(outFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        zip = new ZipOutputStream(bos);
        responseWriter = new OutputStreamWriter(zip);
        OutputStream outStream = null;
        InputStream inStream = null;
        try {

            int start = 0;
            int increment = 100;
            try {
                do {
                    Iterable<Message> messages = messagingService.search(request.getResourceResolver(),
                            new MessageFilter(), start, start + increment);
                    if (messages.iterator().hasNext()) {
                        exportMessagesBatch(messages);
                    } else {
                        break;
                    }
                    start += increment;
                } while (true);
            } catch (final RepositoryException e) {
                // do nothing for now
            }
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            // obtains response's output stream
            outStream = response.getOutputStream();
            inStream = new FileInputStream(outFile);
            // copy from file to output
            IOUtils.copy(inStream, outStream);
        } catch (final IOException e) {
            throw new ServletException(e);
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(inStream);
            IOUtils.closeQuietly(outStream);
        }
    } finally {
        if (outFile != null) {
            outFile.delete();
        }
    }
}

From source file:com.cenrise.test.azkaban.Utils.java

public static void zipFolderContent(final File folder, final File output) throws IOException {
    final FileOutputStream out = new FileOutputStream(output);
    final ZipOutputStream zOut = new ZipOutputStream(out);
    try {/*w ww  .j a va 2 s.  c  om*/
        final File[] files = folder.listFiles();
        if (files != null) {
            for (final File f : files) {
                zipFile("", f, zOut);
            }
        }
    } finally {
        zOut.close();
    }
}

From source file:com.facebook.buck.util.zip.ZipScrubberTest.java

@Test
public void modificationZip64Times() throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] data = "data1".getBytes(Charsets.UTF_8);
    try (ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream)) {
        for (long i = 0; i < 2 * Short.MAX_VALUE + 1; i++) {
            ZipEntry entry = new ZipEntry("file" + i);
            entry.setSize(data.length);/*from  www  .  j a  v a2 s .c  om*/
            out.putNextEntry(entry);
            out.write(data);
            out.closeEntry();
        }
    }

    byte[] bytes = byteArrayOutputStream.toByteArray();
    ZipScrubber.scrubZipBuffer(bytes.length, ByteBuffer.wrap(bytes));

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new ByteArrayInputStream(bytes))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}