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:eu.europa.esig.dss.asic.signature.ASiCService.java

@Override
public DSSDocument extendDocument(final DSSDocument toExtendDocument, final ASiCSignatureParameters parameters)
        throws DSSException {
    try {//w ww  . jav  a 2s . c o  m
        final DocumentValidator validator = SignedDocumentValidator.fromDocument(toExtendDocument);
        final DocumentValidator subordinatedValidator = validator.getSubordinatedValidator();
        final DocumentSignatureService specificService = getSpecificService(
                parameters.aSiC().getUnderlyingForm());
        specificService.setTspSource(tspSource);

        final AbstractSignatureParameters underlyingParameters = getParameters(parameters);
        final DSSDocument detachedContent = parameters.getDetachedContent();
        final DSSDocument detachedContents = getDetachedContents(subordinatedValidator, detachedContent);
        underlyingParameters.setDetachedContent(detachedContents);
        final DSSDocument signature = subordinatedValidator.getDocument();
        final DSSDocument signedDocument = specificService.extendDocument(signature, underlyingParameters);

        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        final ZipOutputStream zipOutputStream = new ZipOutputStream(output);
        final ZipInputStream zipInputStream = new ZipInputStream(toExtendDocument.openStream());
        ZipEntry entry;
        while ((entry = getNextZipEntry(zipInputStream)) != null) {

            final String name = entry.getName();
            final ZipEntry newEntry = new ZipEntry(name);
            if (ASiCContainerValidator.isMimetype(name)) {

                storeMimetype(parameters.aSiC(), zipOutputStream);
            } else if (ASiCContainerValidator.isXAdES(name) || ASiCContainerValidator.isCAdES(name)) {

                createZipEntry(zipOutputStream, newEntry);
                final InputStream inputStream = signedDocument.openStream();
                IOUtils.copy(inputStream, zipOutputStream);
                IOUtils.closeQuietly(inputStream);
            } else {

                createZipEntry(zipOutputStream, newEntry);
                IOUtils.copy(zipInputStream, zipOutputStream);
            }
        }
        IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(zipOutputStream);
        DSSDocument asicSignature = new InMemoryDocument(output.toByteArray(), null,
                getMimeType(parameters.aSiC().getContainerForm()));
        asicSignature.setName(DSSUtils.getFinalFileName(toExtendDocument, SigningOperation.EXTEND,
                parameters.getSignatureLevel()));
        return asicSignature;
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java

/**
 * saves a sound package with all meta information and audio files to a ZIP
 * file and creates the security tokens.
 *
 * @param packageFile the zip file, where the soundpackage should be stored
 * @param soundPackage the sound package info
 * @throws com.dreikraft.infactory.sound.SoundPackageException encapsulates
 * all low level (IO) exceptions/*from  w w w.jav a2  s  . c  o  m*/
 */
public static void exportSoundPackage(final File packageFile, final SoundPackage soundPackage)
        throws SoundPackageException {

    if (packageFile == null) {
        throw new SoundPackageException(new IllegalArgumentException("null package file"));
    }

    if (packageFile.delete()) {
        log.info("successfully deleted file: " + packageFile.getAbsolutePath());
    }

    ZipOutputStream out = null;
    InputStream in = null;
    try {
        out = new ZipOutputStream(new FileOutputStream(packageFile));
        out.setLevel(9);

        // write package info
        writePackageInfoZipEntry(soundPackage, out);

        // create path entries
        ZipEntry soundDir = new ZipEntry(SOUNDS_PATH_PREFIX + SL);
        out.putNextEntry(soundDir);
        out.flush();
        out.closeEntry();

        // write files
        for (Sound sound : soundPackage.getSounds()) {
            File axboFile = new File(sound.getAxboFile().getPath());
            in = new FileInputStream(axboFile);
            writeZipEntry(SOUNDS_PATH_PREFIX + SL + axboFile.getName(), out, in);
            in.close();
        }
    } catch (FileNotFoundException ex) {
        throw new SoundPackageException(ex);
    } catch (IOException ex) {
        throw new SoundPackageException(ex);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ex) {
                log.error("failed to close ZipOutputStream", ex);
            }
        }
        try {
            if (in != null)
                in.close();
        } catch (IOException ex) {
            log.error("failed to close FileInputStream", ex);
        }
    }
}

From source file:com.thejustdo.util.Utils.java

/**
 * Creates a ZIP file containing all the files inside a directory.
 * @param location Directory to read.//w w w . j  a  va 2 s  .  co  m
 * @param pathname Name and path where to store the file.
 * @throws FileNotFoundException If can't find the initial directory.
 * @throws IOException If can't read/write.
 */
public static void zipDirectory(File location, File pathname) throws FileNotFoundException, IOException {

    BufferedInputStream origin;
    FileOutputStream dest = new FileOutputStream(pathname);
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
    byte data[] = new byte[2048];

    // 1. Get a list of files from current directory
    String files[] = location.list();
    File f;

    // 2. Adding each file to the zip-set.
    for (String s : files) {
        log.info(String.format("Adding: %s", s));
        f = new File(location, s);
        FileInputStream fi = new FileInputStream(f);
        origin = new BufferedInputStream(fi, 2048);
        ZipEntry entry = new ZipEntry(location.getName() + File.separator + s);
        out.putNextEntry(entry);
        int count;
        while ((count = origin.read(data, 0, 2048)) != -1) {
            out.write(data, 0, count);
        }
        origin.close();
    }
    out.close();
}

From source file:gov.nasa.ensemble.resources.ResourceUtil.java

public static void zipContainer(final IContainer container, final OutputStream os,
        final IProgressMonitor monitor) throws CoreException {
    final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(os));
    container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    // monitor.beginTask("Zipping " + container.getName(), container.get);
    container.accept(new IResourceVisitor() {
        @Override//from   w w  w .  ja  va 2 s . c  o  m
        public boolean visit(IResource resource) throws CoreException {
            // MSLICE-1258
            for (IProjectPublishFilter filter : publishFilters)
                if (!filter.shouldInclude(resource))
                    return true;

            if (resource instanceof IFile) {
                final IFile file = (IFile) resource;
                final IPath relativePath = ResourceUtil.getRelativePath(container, file).some();
                final ZipEntry entry = new ZipEntry(relativePath.toString());
                try {
                    out.putNextEntry(entry);
                    out.write(ResourceUtil.getContents(file));
                    out.closeEntry();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                            "Failed to write contents of " + file.getName(), e));
                }
            } else if (resource instanceof IFolder) {
                final IFolder folder = (IFolder) resource;
                if (folder.members().length > 0)
                    return true;
                final IPath relativePath = ResourceUtil.getRelativePath(container, folder).some();
                final ZipEntry entry = new ZipEntry(relativePath.toString() + "/");
                try {
                    out.putNextEntry(entry);
                    out.closeEntry();
                } catch (IOException e) {
                    LogUtil.error(e);
                    throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                            "Failed to compress directory " + folder.getName(), e));
                }
            }
            return true;
        }
    });
    try {
        out.close();
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                "Failed to close output stream", e));
    }
}

From source file:co.pugo.convert.ConvertServlet.java

/**
 * Setup XSL Transformation and execute/*from   w ww.ja  v  a 2 s . c o m*/
 * @param response HttpServletResponse
 * @param configuration object
 * @param content document content as String
 * @param xslParameters map of parameters passed to the transformer
 * @throws IOException
 */
private void setupAndRunXSLTransformation(HttpServletResponse response, Configuration configuration,
        String content, Map<String, String> xslParameters) throws IOException {
    InputStream source = IOUtils.toInputStream(content, "utf-8");
    InputStream xsl = getServletContext().getResourceAsStream(CONFIG_DIR + configuration.getXsl());
    Transformation transformation;

    if (configuration.isZipOutputSet())
        transformation = new Transformation(xsl, source, new ZipOutputStream(response.getOutputStream()));
    else
        transformation = new Transformation(xsl, source, response.getWriter());

    transformation.setParameters(xslParameters);
    transformation.transform();
}

From source file:org.eclipse.cft.server.core.internal.CloudUtil.java

public static IStatus[] publishZip(List<IModuleResource> allResources, File tempFile,
        Set<IModuleResource> filterInFiles, IProgressMonitor monitor) {

    monitor = ProgressUtil.getMonitorFor(monitor);

    try {/*from   ww w. ja v a2  s  .c om*/
        BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(tempFile));
        ZipOutputStream zout = new ZipOutputStream(bout);
        addZipEntries(zout, allResources, filterInFiles);
        zout.close();

    } catch (CoreException e) {
        return new IStatus[] { e.getStatus() };
    } catch (Exception e) {

        return new Status[] { new Status(IStatus.ERROR, ServerPlugin.PLUGIN_ID, 0,
                NLS.bind(Messages.ERROR_CREATE_ZIP, tempFile.getName(), e.getLocalizedMessage()), e) };
    } finally {
        if (tempFile != null && tempFile.exists())
            tempFile.deleteOnExit();
    }
    return EMPTY_STATUS;
}

From source file:com.sencko.basketball.stats.advanced.FIBAJsonParser.java

private static void addToCache(String cacheName, Game game)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    logger.log(Level.FINEST, "Saving file {0} to cache", cacheName);
    File file = new File("archive.zip");
    File file1 = null;//from  w  w  w  .j a v a2  s.  c o m
    if (file.exists()) {
        //copy to archive1, return
        file1 = new File("archive1.zip");
        if (file1.exists()) {
            if (!file1.delete()) {
                logger.log(Level.WARNING, "Unable to delete file {0}", file1.getCanonicalPath());
                return;
            }
        }
        if (!file.renameTo(file1)) {
            logger.log(Level.WARNING, "Unable to rename file {0} to {1}",
                    new Object[] { file.getCanonicalPath(), file1.getCanonicalPath() });
            // unable to move to archive1 and whole operation fails!!!
            return;
        }
    }

    try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file))) {
        out.setLevel(9);
        // name the file inside the zip  file 
        out.putNextEntry(new ZipEntry(cacheName));
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out, "UTF-8");
        JsonWriter jsonWriter = new JsonWriter(outputStreamWriter);
        jsonWriter.setIndent("  ");
        builder.create().toJson(game, Game.class, jsonWriter);
        jsonWriter.flush();

        if (file1 != null) {
            try (ZipFile zipFile = new ZipFile(file1)) {
                Enumeration<? extends ZipEntry> files = zipFile.entries();
                while (files.hasMoreElements()) {
                    ZipEntry entry = files.nextElement();
                    try (InputStream in = zipFile.getInputStream(entry)) {
                        out.putNextEntry(new ZipEntry(entry.getName()));

                        IOUtils.copy(in, out);
                    }
                }
            }
            file1.delete();

        }
    }
}

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

public String export(OutputStream os, XWikiContext context) throws IOException, XWikiException {
    if (this.files.size() == 0) {
        return "No Selected file";
    }//from  ww  w.j a va  2  s. c  o m

    ZipOutputStream zos = new ZipOutputStream(os);
    for (int i = 0; i < this.files.size(); i++) {
        DocumentInfo docinfo = this.files.get(i);
        XWikiDocument doc = docinfo.getDoc();
        addToZip(doc, zos, this.withVersions, context);
    }
    addInfosToZip(zos, context);
    zos.finish();
    zos.flush();

    return "";
}

From source file:org.commonjava.aprox.depgraph.rest.RepositoryController.java

public void getZipRepository(final WebOperationConfigDTO dto, final OutputStream zipStream)
        throws AproxWorkflowException {
    ZipOutputStream stream = null;
    try {/*from www .  j av a2s .c  o m*/
        final Map<ProjectVersionRef, Map<ArtifactRef, ConcreteResource>> contents = resolveContents(dto);

        final Set<ConcreteResource> entries = new HashSet<ConcreteResource>();
        final Set<String> seenPaths = new HashSet<String>();

        logger.info("Iterating contents with {} GAVs.", contents.size());
        for (final Map<ArtifactRef, ConcreteResource> artifactResources : contents.values()) {
            for (final Entry<ArtifactRef, ConcreteResource> entry : artifactResources.entrySet()) {
                final ArtifactRef ref = entry.getKey();
                final ConcreteResource resource = entry.getValue();

                //                        logger.info( "Checking {} ({}) for inclusion...", ref, resource );

                final String path = resource.getPath();
                if (seenPaths.contains(path)) {
                    logger.warn("Conflicting path: {}. Skipping {}.", path, ref);
                    continue;
                }

                seenPaths.add(path);

                //                        logger.info( "Adding to batch: {} via resource: {}", ref, resource );
                entries.add(resource);
            }
        }

        logger.info("Starting batch retrieval of {} artifacts.", entries.size());
        TransferBatch batch = new TransferBatch(entries);
        batch = transferManager.batchRetrieve(batch);

        logger.info("Retrieved {} artifacts. Creating zip.", batch.getTransfers().size());

        // FIXME: Stream to a temp file, then pass that to the Response.ok() handler...
        stream = new ZipOutputStream(zipStream);

        final List<Transfer> items = new ArrayList<Transfer>(batch.getTransfers().values());
        Collections.sort(items, new Comparator<Transfer>() {
            @Override
            public int compare(final Transfer f, final Transfer s) {
                return f.getPath().compareTo(s.getPath());
            }
        });

        for (final Transfer item : items) {
            //                    logger.info( "Adding: {}", item );
            final String path = item.getPath();
            if (item != null) {
                final ZipEntry ze = new ZipEntry(path);
                stream.putNextEntry(ze);

                InputStream itemStream = null;
                try {
                    itemStream = item.openInputStream();
                    copy(itemStream, stream);
                } finally {
                    closeQuietly(itemStream);
                }
            }
        }
    } catch (final IOException e) {
        throw new AproxWorkflowException("Failed to generate runtime repository. Reason: {}", e,
                e.getMessage());
    } catch (final TransferException e) {
        throw new AproxWorkflowException("Failed to generate runtime repository. Reason: {}", e,
                e.getMessage());
    } finally {
        closeQuietly(stream);
    }
}

From source file:freenet.client.async.ContainerInserter.java

private String createZipBucket(OutputStream os) throws IOException {
    if (logMINOR)
        Logger.minor(this, "Create a ZIP Bucket");

    ZipOutputStream zos = new ZipOutputStream(os);
    try {//from  ww w .  j av  a 2 s .co m
        ZipEntry ze;

        for (ContainerElement ph : containerItems) {
            ze = new ZipEntry(ph.targetInArchive);
            ze.setTime(0);
            zos.putNextEntry(ze);
            BucketTools.copyTo(ph.data, zos, ph.data.size());
            zos.closeEntry();
        }
    } finally {
        zos.close();
    }

    return ARCHIVE_TYPE.ZIP.mimeTypes[0];
}