Example usage for java.util.zip ZipEntry ZipEntry

List of usage examples for java.util.zip ZipEntry ZipEntry

Introduction

In this page you can find the example usage for java.util.zip ZipEntry ZipEntry.

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:fr.gael.dhus.datastore.FileSystemDataStore.java

/**
 * Generates a zip file./*w  w  w.j  a v a2s  .c o m*/
 *
 * @param source      source file or directory to compress.
 * @param destination destination of zipped file.
 * @return the zipped file.
 */
private void generateZip(File source, File destination) throws IOException {
    if (source == null || !source.exists()) {
        throw new IllegalArgumentException("source file should exist");
    }
    if (destination == null) {
        throw new IllegalArgumentException("destination file should be not null");
    }

    FileOutputStream output = new FileOutputStream(destination);
    ZipOutputStream zip_out = new ZipOutputStream(output);
    zip_out.setLevel(cfgManager.getDownloadConfiguration().getCompressionLevel());

    List<QualifiedFile> file_list = getFileList(source);
    byte[] buffer = new byte[BUFFER_SIZE];
    for (QualifiedFile qualified_file : file_list) {
        ZipEntry entry = new ZipEntry(qualified_file.getQualifier());
        InputStream input = new FileInputStream(qualified_file.getFile());

        int read;
        zip_out.putNextEntry(entry);
        while ((read = input.read(buffer)) != -1) {
            zip_out.write(buffer, 0, read);
        }
        input.close();
        zip_out.closeEntry();
    }
    zip_out.close();
    output.close();
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

/**
 * Copy zip file and remove ignored files
 *
 * @param srcFile/*from   w ww . j  a  v  a  2s  .  co  m*/
 * @param destFile
 * @throws IOException
 */
public void copyZip(final String srcFile, final String destFile) throws Exception {
    loadDefaultExcludePattern(getRootFolderInZip(srcFile));

    final ZipFile zipSrc = new ZipFile(srcFile);
    final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile));

    try {
        final Enumeration<? extends ZipEntry> entries = zipSrc.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            if (!isExcluded(LocalPath.combine(srcFile, entry.getName()), false, srcFile)) {
                final ZipEntry newEntry = new ZipEntry(entry.getName());
                out.putNextEntry(newEntry);

                final BufferedInputStream in = new BufferedInputStream(zipSrc.getInputStream(entry));
                int len;
                final byte[] buf = new byte[65536];
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
        }
        out.finish();
    } catch (final IOException e) {
        errorMsg = Messages.getString("CreateUploadZipCommand.CopyArchiveErrorMessageFormat"); //$NON-NLS-1$
        log.error("Exceptions when copying exising archive ", e); //$NON-NLS-1$
        throw e;
    } finally {
        out.close();
        zipSrc.close();
    }
}

From source file:com.googlecode.clearnlp.component.AbstractStatisticalComponent.java

/** Called by {@link AbstractStatisticalComponent#saveModels(ZipOutputStream)}}. */
protected void saveFeatureTemplates(ZipOutputStream zout, String entryName) throws Exception {
    int i, size = f_xmls.length;
    PrintStream fout;/*from w w w.ja  v a 2 s .c  o m*/
    LOG.info("Saving feature templates.\n");

    for (i = 0; i < size; i++) {
        zout.putNextEntry(new ZipEntry(entryName + i));
        fout = UTOutput.createPrintBufferedStream(zout);
        IOUtils.copy(UTInput.toInputStream(f_xmls[i].toString()), fout);
        fout.flush();
        zout.closeEntry();
    }
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

public static void addToZipFile(String fileName, ZipOutputStream zos)
        throws FileNotFoundException, IOException {
    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    ZipEntry zipEntry = new ZipEntry(fileName);
    zos.putNextEntry(zipEntry);//from   w  ww .j  a v  a2s.  c om

    byte[] bytes = new byte[2048];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
    }

    zos.closeEntry();
    fis.close();
}

From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java

public String exportZippedResultsForUser(String deviceId) throws FileNotFoundException {
    String resultsDir = deviceId + File.separator;
    String zipFilename = deviceId + ".zip";
    new File(resultsDir).mkdir();
    saveResultsToFilesForDeviceId(deviceId, resultsDir);

    ZipOutputStream zipOutputStream = null;
    try {// ww  w.  j av a2s . c  o m
        zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilename));
        File zipDir = new File(resultsDir);
        String[] dirList = zipDir.list();
        byte[] readBuffer = new byte[4096];
        int bytesIn = 0;

        for (int i = 0; i < dirList.length; i++) {
            FileInputStream fis = null;
            try {
                File f = new File(zipDir, dirList[i]);
                fis = new FileInputStream(f);
                ZipEntry anEntry = new ZipEntry(f.getPath());
                zipOutputStream.putNextEntry(anEntry);
                while ((bytesIn = fis.read(readBuffer)) != -1) {
                    zipOutputStream.write(readBuffer, 0, bytesIn);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    } finally {
        if (zipOutputStream != null) {
            try {
                zipOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    removeDir(resultsDir);
    return zipFilename;
}

From source file:de.brendamour.jpasskit.signing.PKFileBasedSigningUtil.java

private final void zip(final File directory, final File base, final ZipOutputStream zipOutputStream)
        throws PKSigningException {
    File[] files = directory.listFiles();
    for (int i = 0, n = files.length; i < n; i++) {
        if (files[i].isDirectory()) {
            zip(files[i], base, zipOutputStream);
        } else {//  w w w . j ava 2s .  c  o m
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(files[i]);
                ZipEntry entry = new ZipEntry(getRelativePathOfZipEntry(files[i].getPath(), base.getPath()));
                zipOutputStream.putNextEntry(entry);
                IOUtils.copy(fileInputStream, zipOutputStream);
            } catch (IOException e) {
                IOUtils.closeQuietly(zipOutputStream);
                throw new PKSigningException("Error when zipping file", e);
            } finally {
                IOUtils.closeQuietly(fileInputStream);
            }
        }
    }
}

From source file:de.unikassel.puma.openaccess.sword.SwordService.java

/**
 * collects all informations to send Documents with metadata to repository 
 * @throws SwordException // ww  w  .j a  v a  2s  .c  o  m
 */
public void submitDocument(PumaData<?> pumaData, User user) throws SwordException {
    log.info("starting sword");
    DepositResponse depositResponse = new DepositResponse(999);
    File swordZipFile = null;

    Post<?> post = pumaData.getPost();

    // -------------------------------------------------------------------------------
    /*
     * retrieve ZIP-FILE
     */
    if (post.getResource() instanceof BibTex) {

        // fileprefix
        String fileID = HashUtils.getMD5Hash(user.getName().getBytes()) + "_"
                + post.getResource().getIntraHash();

        // Destination directory 
        File destinationDirectory = new File(repositoryConfig.getDirTemp() + "/" + fileID);

        // zip-filename
        swordZipFile = new File(destinationDirectory.getAbsoluteFile() + "/" + fileID + ".zip");

        byte[] buffer = new byte[18024];

        log.info("getIntraHash = " + post.getResource().getIntraHash());

        /*
         * get documents
         */

        // At the moment, there are no Documents delivered by method parameter post.
        // retrieve list of documents from database - workaround

        // get documents for post and insert documents into post 
        ((BibTex) post.getResource())
                .setDocuments(retrieveDocumentsFromDatabase(user, post.getResource().getIntraHash()));

        if (((BibTex) post.getResource()).getDocuments().isEmpty()) {
            // Wenn kein PDF da, dann Fehlermeldung ausgeben!!
            log.info("throw SwordException: noPDFattached");
            throw new SwordException("error.sword.noPDFattached");
        }

        try {
            // create directory
            boolean mkdir_success = (new File(destinationDirectory.getAbsolutePath())).mkdir();
            if (mkdir_success) {
                log.info("Directory: " + destinationDirectory.getAbsolutePath() + " created");
            }

            // open zip archive to add files to
            log.info("zipFilename: " + swordZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(swordZipFile));

            ArrayList<String> fileList = new ArrayList<String>();

            for (final Document document : ((BibTex) post.getResource()).getDocuments()) {

                //getpostdetails
                // get file and store it in hard coded folder "/tmp/"
                //final Document document2 = logic.getDocument(user.getName(), post.getResource().getIntraHash(), document.getFileName());

                // move file to user folder with username_resource-hash as folder name

                // File (or directory) to be copied 
                //File fileToZip = new File(document.getFileHash());

                fileList.add(document.getFileName());

                // Move file to new directory 
                //boolean rename_success = fileToCopy.renameTo(new File(destinationDirectory, fileToMove.getName()));
                /*
                if (!rename_success) { 
                   // File was not successfully moved } 
                   log.info("File was not successfully moved: "+fileToMove.getName());
                }
                */
                ZipEntry zipEntry = new ZipEntry(document.getFileName());

                // Set the compression ratio
                zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

                String inputFilePath = projectDocumentPath + document.getFileHash().substring(0, 2) + "/"
                        + document.getFileHash();
                FileInputStream in = new FileInputStream(inputFilePath);

                // Add ZIP entry to output stream.
                zipOutputStream.putNextEntry(zipEntry);

                // Transfer bytes from the current file to the ZIP file
                //out.write(buffer, 0, in.read(buffer));

                int len;
                while ((len = in.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }

                zipOutputStream.closeEntry();

                // Close the current file input stream
                in.close();
            }

            // write meta data into zip archive
            ZipEntry zipEntry = new ZipEntry("mets.xml");
            zipOutputStream.putNextEntry(zipEntry);

            // create XML-Document
            // PrintWriter from a Servlet

            MetsBibTexMLGenerator metsBibTexMLGenerator = new MetsBibTexMLGenerator(urlRenderer);
            metsBibTexMLGenerator.setUser(user);
            metsBibTexMLGenerator.setFilenameList(fileList);
            //metsGenerator.setMetadata(metadataMap);
            metsBibTexMLGenerator.setMetadata((PumaData<BibTex>) pumaData);

            //            PumaPost additionalMetadata = new PumaPost();
            //            additionalMetadata.setExaminstitution(null);
            //            additionalMetadata.setAdditionaltitle(null);
            //            additionalMetadata.setExamreferee(null);
            //            additionalMetadata.setPhdoralexam(null);
            //            additionalMetadata.setSponsors(null);
            //            additionalMetadata.setAdditionaltitle(null);   

            //            metsBibTexMLGenerator.setMetadata((Post<BibTex>) post);

            //StreamResult streamResult = new StreamResult(zipOutputStream);

            zipOutputStream.write(metsBibTexMLGenerator.generateMets().getBytes("UTF-8"));

            zipOutputStream.closeEntry();

            // close zip archive  
            zipOutputStream.close();

            log.debug("saved to " + swordZipFile.getPath());

        } catch (MalformedURLException e) {
            // e.printStackTrace();
            log.info("MalformedURLException! " + e.getMessage());
        } catch (IOException e) {
            //e.printStackTrace();
            log.info("IOException! " + e.getMessage());

        } catch (ResourceNotFoundException e) {
            // e.printStackTrace();
            log.warn("ResourceNotFoundException! SwordService-retrievePost");
        }
    }
    /*
     * end of retrieve ZIP-FILE
     */
    //---------------------------------------------------

    /*
     * do the SWORD stuff
     */

    if (null != swordZipFile) {

        // get an instance of SWORD-Client
        Client swordClient = new Client();

        PostMessage swordMessage = new PostMessage();

        // create sword post message

        // message file
        // create directory in temp-folder
        // store post documents there
        // store meta data there in format http://purl.org/net/sword-types/METSDSpaceSIP
        // delete post document files and meta data file

        // add files to zip archive
        // -- send zip archive
        // -- delete zip archive

        swordClient.setServer(repositoryConfig.getHttpServer(), repositoryConfig.getHttpPort());
        swordClient.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordClient.setCredentials(repositoryConfig.getAuthUsername(), repositoryConfig.getAuthPassword());

        // message meta
        swordMessage.setNoOp(false);
        swordMessage.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordMessage.setFilepath(swordZipFile.getAbsolutePath());
        swordMessage.setFiletype("application/zip");
        swordMessage.setFormatNamespace("http://purl.org/net/sword-types/METSDSpaceSIP"); // sets packaging!
        swordMessage.setVerbose(false);

        try {
            // check depositurl against service document
            if (checkServicedokument(retrieveServicedocument(), repositoryConfig.getHttpServicedocumentUrl(),
                    SWORDFILETYPE, SWORDFORMAT)) {
                // transmit sword message (zip file with document metadata and document files
                swordMessage.setDestination(repositoryConfig.getHttpDepositUrl());

                depositResponse = swordClient.postFile(swordMessage);

                /*
                 * 200 OK Used in response to successful GET operations and
                 * to Media Resource Creation operations where X-No-Op is
                 * set to true and the server supports this header.
                 * 
                 * 201 Created
                 * 
                 * 202 Accepted - One of these MUST be used to indicate that
                 * a deposit was successful. 202 Accepted is used when
                 * processing of the data is not yet complete.
                 * 
                 * 
                 * 400 Bad Request - used to indicate that there is some
                 * problem with the request where there is no more
                 * appropriate 4xx code.
                 * 
                 * 401 Unauthorized - In addition to the usage described in
                 * HTTP, servers that support mediated deposit SHOULD use
                 * this status code when the server does not understand the
                 * value given in the X-Behalf-Of header. In this case a
                 * human-readable explanation MUST be provided.
                 * 
                 * 403 Forbidden - indicates that there was a problem making
                 * the deposit, it may be that the depositor is not
                 * authorised to deposit on behalf of the target owner, or
                 * the target owner does not have permission to deposit into
                 * the specified collection.
                 * 
                 * 412 Precondition failed - MUST be returned by server
                 * implementations if a calculated checksum does not match a
                 * value provided by the client in the Content-MD5 header.
                 * 
                 * 415 Unsupported Media Type - MUST be used to indicate
                 * that the format supplied in either a Content-Type header
                 * or in an X-Packaging header or the combination of the two
                 * is not accepted by the server.
                 */

                log.info("throw SwordException: errcode" + depositResponse.getHttpResponse());
                throw new SwordException("error.sword.errcode" + depositResponse.getHttpResponse());

            }

        } catch (SWORDClientException e) {
            log.warn("SWORDClientException: " + e.getMessage() + "\n" + e.getCause() + " / "
                    + swordMessage.getDestination());
            throw new SwordException("error.sword.urlnotaccessable");
        }

    }

}

From source file:edu.dfci.cccb.mev.dataset.rest.controllers.WorkspaceController.java

@RequestMapping(value = "/export/zip", method = POST, consumes = "multipart/form-data")
@ResponseStatus(OK)//from www.  j a va2s . c  o  m
public byte[] export(@RequestParam("name") String name, @RequestParam("rows") List<String> rows,
        @RequestParam("columns") List<String> columns, @RequestParam("rowSelections") String jsonRowSelections,
        @RequestParam("columnSelections") String jsonColumnSelections,
        @RequestParam("analyses") String[] analyses, HttpServletResponse response)
        throws DatasetException, IOException {
    log.info(String.format("Offline %s, %s, %s, %s", name, rows, columns, analyses));

    //creating byteArray stream, make it bufforable and passing this buffor to ZipOutputStream
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
    ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

    //nw zip entry for dataset
    Dataset dataset = workspace.get(name);
    zipOutputStream.putNextEntry(new ZipEntry("dataset.json"));
    IOUtils.copy(new ByteArrayInputStream(mapper.writeValueAsBytes(dataset)), zipOutputStream);
    zipOutputStream.closeEntry();

    zipAnnotations(name, "row", zipOutputStream);
    zipAnnotations(name, "column", zipOutputStream);

    if (dataset.values() instanceof IFlatFileValues) {
        IFlatFileValues values = (IFlatFileValues) dataset.values();
        zipOutputStream.putNextEntry(new ZipEntry("values.bin"));
        InputStream valuesIs = values.asInputStream();
        IOUtils.copy(valuesIs, zipOutputStream);
        zipOutputStream.closeEntry();
        zipOutputStream.flush();
        valuesIs.close();
    }

    //new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
    int i = 0;
    for (String analysis : analyses) {
        InputStream analysisOs = new ByteArrayInputStream(analysis.getBytes(StandardCharsets.UTF_8));
        zipOutputStream.putNextEntry(new ZipEntry(String.format("analysis_%d.json", i)));
        JsonNode analysisJson = mapper.readTree(analysis);
        IOUtils.copy(analysisOs, zipOutputStream);
        zipOutputStream.closeEntry();
        zipOutputStream.flush();
        analysisOs.close();
        i++;
    }
    zipOutputStream.flush();
    zipOutputStream.close();

    byte[] ret = byteArrayOutputStream.toByteArray();
    IOUtils.closeQuietly(bufferedOutputStream);
    IOUtils.closeQuietly(byteArrayOutputStream);

    response.setContentLength(ret.length);
    response.setContentType("application/zip"); //or something more generic...
    response.setHeader("Accept-Ranges", "bytes");
    response.setStatus(HttpServletResponse.SC_OK);
    response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s.zip\"", name));
    return ret;
}

From source file:com.coinblesk.client.backup.BackupDialogFragment.java

private void addZipEntry(String filename, byte[] data, ZipOutputStream zos) throws IOException {
    ZipEntry entry = new ZipEntry(filename);
    zos.putNextEntry(entry);/*ww w.  j  a v a  2s  .  c o  m*/
    zos.write(data);
    zos.closeEntry();
    zos.flush();
}

From source file:com.asakusafw.testdriver.compiler.util.DeploymentUtil.java

private static void putEntry(ZipOutputStream zip, File source, String path, Set<String> saw)
        throws IOException {
    assert zip != null;
    assert source != null;
    assert !(source.isFile() && path == null);
    if (source.isDirectory()) {
        for (File child : list(source)) {
            String next = (path == null) ? child.getName() : path + '/' + child.getName();
            putEntry(zip, child, next, saw);
        }/* www .  j  av  a2  s  .  co  m*/
    } else {
        if (saw.contains(path)) {
            return;
        }
        saw.add(path);
        zip.putNextEntry(new ZipEntry(path));
        try (InputStream in = new BufferedInputStream(new FileInputStream(source))) {
            LOG.trace("Copy into archive: {} -> {}", source, path);
            copyStream(in, zip);
        }
        zip.closeEntry();
    }
}