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.saiku.plugin.resources.PentahoRepositoryResource2.java

@GET
@Path("/zip")
public Response getResourcesAsZip(@QueryParam("directory") String directory, @QueryParam("files") String files,
        @QueryParam("type") String type) {
    try {//  w  w w.j a  v  a  2  s .c  om
        if (StringUtils.isBlank(directory))
            return Response.ok().build();

        final String fileType = type;
        IUserContentAccess access = contentAccessFactory.getUserContentAccess(null);

        if (!access.fileExists(directory) && access.hasAccess(directory, FileAccess.READ)) {
            throw new SaikuServiceException(
                    "Access to Repository has failed File does not exist or no read right: " + directory);
        }

        IBasicFileFilter txtFilter = StringUtils.isBlank(type) ? null : new IBasicFileFilter() {
            public boolean accept(IBasicFile file) {
                return file.isDirectory() || file.getExtension().equals(fileType);
            }
        };

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(bos);

        List<IBasicFile> basicFiles = access.listFiles(directory, txtFilter);

        for (IBasicFile basicFile : basicFiles) {
            if (!basicFile.isDirectory()) {
                String entry = basicFile.getName();
                byte[] doc = IOUtils.toByteArray(basicFile.getContents());
                ZipEntry ze = new ZipEntry(entry);
                zos.putNextEntry(ze);
                zos.write(doc);

            }
        }

        zos.closeEntry();
        zos.close();
        byte[] zipDoc = bos.toByteArray();

        return Response.ok(zipDoc, MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition", "attachment; filename = " + directory + ".zip")
                .header("content-length", zipDoc.length).build();

    } catch (Exception e) {
        log.error("Cannot zip resources " + files, e);
        String error = ExceptionUtils.getRootCauseMessage(e);
        return Response.serverError().entity(error).build();
    }

}

From source file:com.thoughtworks.go.server.service.BackupService.java

private void backupConfigRepo(List<BackupUpdateListener> backupUpdateListeners, File destDir)
        throws IOException {
    notifyUpdateToListeners(backupUpdateListeners, BackupProgressStatus.BACKUP_CONFIG_REPO);
    configRepository.doLocked(new VoidThrowingFn<IOException>() {
        @Override//from w ww.  j  a va2 s  .  co m
        public void run() throws IOException {
            File configRepoDir = systemEnvironment.getConfigRepoDir();
            try (ZipOutputStream configRepoZipStream = new ZipOutputStream(new BufferedOutputStream(
                    new FileOutputStream(new File(destDir, CONFIG_REPOSITORY_BACKUP_ZIP))))) {
                new DirectoryStructureWalker(configRepoDir.getAbsolutePath(), configRepoZipStream).walk();
            }
        }
    });
}

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.
 * /*from w w w.  j  ava  2  s .c om*/
 * @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:azkaban.common.utils.Utils.java

public static void zip(File input, File output) throws IOException {
    FileOutputStream out = new FileOutputStream(output);
    ZipOutputStream zOut = new ZipOutputStream(out);
    zipFile("", input, zOut);
    zOut.close();/*  w  ww . ja v  a2s . co m*/
}

From source file:com.mcleodmoores.mvn.natives.PackageMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().debug("Skipping step");
        return;/*from  w  w w.j a v  a2  s  .c o m*/
    }
    applyDefaults();
    final MavenProject project = (MavenProject) getPluginContext().get("project");
    final File targetDir = new File(project.getBuild().getDirectory());
    targetDir.mkdirs();
    final File targetFile = new File(targetDir, project.getArtifactId() + ".zip");
    getLog().debug("Writing to " + targetFile);
    final OutputStream output;
    try {
        output = getOutputStreams().open(targetFile);
    } catch (final IOException e) {
        throw new MojoFailureException("Can't write to " + targetFile);
    }
    final IOExceptionHandler errorLog = new MojoLoggingErrorCallback(this);
    if ((new IOCallback<OutputStream, Boolean>(output) {

        @Override
        protected Boolean apply(final OutputStream output) throws IOException {
            final byte[] buffer = new byte[4096];
            final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(output));
            for (final Map.Entry<Source, String> sourceInfo : gatherSources().entrySet()) {
                final Source source = sourceInfo.getKey();
                getLog().info("Processing " + source.getPath() + " into " + sourceInfo.getValue() + " ("
                        + source.getPattern() + ")");
                final File folder = new File(source.getPath());
                final String[] files = folder.list(new PatternFilenameFilter(regex(source.getPattern())));
                if (files != null) {
                    for (final String file : files) {
                        getLog().debug("Adding " + file + " to archive");
                        final ZipEntry entry = new ZipEntry(sourceInfo.getValue() + file);
                        zip.putNextEntry(entry);
                        if ((new IOCallback<InputStream, Boolean>(
                                getInputStreams().open(new File(folder, file))) {

                            @Override
                            protected Boolean apply(final InputStream input) throws IOException {
                                int bytes;
                                while ((bytes = input.read(buffer, 0, buffer.length)) > 0) {
                                    zip.write(buffer, 0, bytes);
                                }
                                return Boolean.TRUE;
                            }

                        }).call(errorLog) != Boolean.TRUE) {
                            return Boolean.FALSE;
                        }
                        zip.closeEntry();
                    }
                } else {
                    getLog().debug("Source folder is empty or does not exist");
                }
            }
            zip.close();
            return Boolean.TRUE;
        }

    }).call(errorLog) != Boolean.TRUE) {
        throw new MojoFailureException("Error writing to " + targetFile);
    }
    project.getArtifact().setFile(targetFile);
}

From source file:de.unisaarland.swan.export.ExportUtil.java

private ZipOutputStream createZipOutputStream(File file) throws FileNotFoundException {
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    return new ZipOutputStream(bos);
}

From source file:com.xpn.xwiki.export.html.HtmlPackager.java

/**
 * Apply export and create the ZIP package.
 * // www  .j av a  2s.c  om
 * @param context the XWiki context used to render pages.
 * @throws IOException error when creating the package.
 * @throws XWikiException error when render the pages.
 */
public void export(XWikiContext context) throws IOException, XWikiException {
    context.getResponse().setContentType("application/zip");
    context.getResponse().addHeader("Content-disposition",
            "attachment; filename=" + Util.encodeURI(this.name, context) + ".zip");
    context.setFinished(true);

    ZipOutputStream zos = new ZipOutputStream(context.getResponse().getOutputStream());

    File dir = context.getWiki().getTempDirectory(context);
    File tempdir = new File(dir, RandomStringUtils.randomAlphanumeric(8));
    tempdir.mkdirs();
    File attachmentDir = new File(tempdir, "attachment");
    attachmentDir.mkdirs();

    // Create custom URL factory
    ExportURLFactory urlf = new ExportURLFactory();

    // Render pages to export
    renderDocuments(zos, tempdir, urlf, context);

    // Add required skins to ZIP file
    for (String skinName : urlf.getNeededSkins()) {
        addSkinToZip(skinName, zos, urlf.getExportedSkinFiles(), context);
    }

    // add "resources" folder
    File file = new File(context.getWiki().getEngineContext().getRealPath("/resources/"));
    addDirToZip(file, zos, "resources" + ZIPPATH_SEPARATOR, urlf.getExportedSkinFiles());

    // Add attachments and generated skin files files to ZIP file
    addDirToZip(tempdir, zos, "", null);

    zos.setComment(this.description);

    // Finish ZIP file
    zos.finish();
    zos.flush();

    // Delete temporary directory
    deleteDirectory(tempdir);
}

From source file:es.sm2.openppm.core.plugin.action.GenericAction.java

/**
 *
 * @param files/*from  w  ww.j a va  2  s. co m*/
 * @return
 * @throws IOException
 */
public static byte[] zipFiles(List<File> files) throws IOException {

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

    for (File f : files) {

        zos.putNextEntry(new ZipEntry(f.getName()));

        zos.write(getBytesFromFile(f.getAbsoluteFile()));

        zos.closeEntry();
    }

    zos.flush();
    baos.flush();
    zos.close();
    baos.close();

    return baos.toByteArray();
}

From source file:com.ikanow.aleph2.analytics.storm.utils.TestStormControllerUtil_Cache.java

private static File createFakeZipFile(String file_name) throws IOException {
    File file;/*from ww  w  . jav  a  2s. co  m*/
    if (file_name == null)
        file = File.createTempFile("recent_date_test_", ".zip");
    else
        file = new File(file_name);
    Random r = new Random();
    ZipOutputStream outputZip = new ZipOutputStream(new FileOutputStream(file));
    ZipEntry e = new ZipEntry("some_file.tmp");
    outputZip.putNextEntry(e);
    outputZip.write(r.nextInt());
    outputZip.close();
    return file;
}