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: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 {//from   w w  w  .ja va 2s .  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:de.unisaarland.swan.export.ExportUtil.java

private void createZipEntry(File file, ZipOutputStream zos) throws IOException {
    zos.putNextEntry(new ZipEntry(file.getName()));
    zos.write(FileUtils.readFileToByteArray(file));
    zos.closeEntry();/*from  www. j av a 2 s  . co  m*/
}

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

/**
 *
 * @param files//from w ww . j  a  v a  2s. c o 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:io.wcm.tooling.commons.contentpackagebuilder.ContentPackage.java

/**
 * Build java Properties XML file.//from  w ww .  ja  va 2 s .c  o m
 * @param path Path
 * @throws IOException
 */
private void buildPropertiesFile(String path) throws IOException {
    Properties properties = new Properties();
    properties.put("packageFormatVersion", "2");
    properties.put("requiresRoot", "false");

    for (Map.Entry<String, Object> entry : metadata.getVars().entrySet()) {
        String value = ObjectUtils.toString(entry.getValue());
        if (StringUtils.isNotEmpty(value)) {
            properties.put(entry.getKey(), value);
        }
    }

    zip.putNextEntry(new ZipEntry(path));
    try {
        properties.storeToXML(zip, null);
    } finally {
        zip.closeEntry();
    }
}

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.j av  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;
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibAj.java

private void copyExistingFiles(ZipFile inputFile, ZipOutputStream outputFile, Map<String, String> excludeFiles)
        throws IOException {
    // First, copy the contents from the existing outFile:
    Enumeration<? extends ZipEntry> entries = inputFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = new ZipEntry(entries.nextElement());
        if (excludeFiles.get(entry.getName()) != null) {
            //??.
            continue;
        }/*from  w w  w  .j a v  a2s. c  o m*/
        // We can't reuse the compressed size because it depends on compression sizes.
        entry.setCompressedSize(-1);
        outputFile.putNextEntry(entry);

        // No need to create directory entries in the final apk
        if (!entry.isDirectory()) {
            BrutIO.copy(inputFile, outputFile, entry);
        }

        outputFile.closeEntry();
    }
}

From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java

public void attach() {

    selectedDir = cb.getVfsUrl();//from w w  w.jav a 2s.co  m
    try {

        final VFSFileExplorerPortlet app = instance;
        final User user = (User) app.getUser();
        final FileSystemManager fFileSystemManager = fileSystemManager;
        final FileSystemOptions fOpts = opts;

        final Table table = new Table() {

            private static final long serialVersionUID = 1L;

            protected String formatPropertyValue(Object rowId, Object colId, Property property) {

                if (TABLE_PROP_FILE_NAME.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        return getDisplayPath(property.getValue().toString());
                    }
                }
                if (TABLE_PROP_FILE_DATE.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("dd.MMM yyyy HH:mm:ss");
                        return sdf.format((Date) property.getValue());
                    }
                }
                return super.formatPropertyValue(rowId, colId, property);
            }

        };
        table.setSizeFull();
        table.setMultiSelect(true);
        table.setSelectable(true);
        table.setImmediate(true);
        table.addContainerProperty(TABLE_PROP_FILE_NAME, String.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_SIZE, Long.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_DATE, Date.class, null);
        if (app != null) {
            app.getEventBus().addHandler(TableChangedEvent.class, new TableChangedEventHandler() {
                private static final long serialVersionUID = 1L;

                @Override
                public void onValueChanged(TableChangedEvent event) {
                    try {
                        selectedDir = event.getNewDirectory();
                        fillTableData(event.getNewDirectory(), table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        table.addListener(new Table.ValueChangeListener() {
            private static final long serialVersionUID = 1L;

            public void valueChange(ValueChangeEvent event) {

                Set<?> value = (Set<?>) event.getProperty().getValue();
                if (null == value || value.size() == 0) {
                    markedRows = null;
                } else {
                    markedRows = value;
                }
            }
        });

        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);

        Button btDownload = new Button("Download File(s)");
        btDownload.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    String[] files = new String[markedRows.size()];
                    int fileCount = 0;

                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        files[fileCount] = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        fileCount++;
                    }

                    File dlFile = null;
                    if (fileCount == 1) {
                        try {
                            String fileName = files[0];
                            dlFile = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                            logger.log(Level.INFO,
                                    "vfs2portlet: download file " + fileName + " by " + user.getScreenName());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        byte[] buf = new byte[1024];

                        try {
                            dlFile = File.createTempFile("Files", ".zip");
                            ZipOutputStream out = new ZipOutputStream(
                                    new FileOutputStream(dlFile.getAbsolutePath()));
                            for (int i = 0; i < files.length; i++) {
                                String fileName = files[i];
                                logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by "
                                        + user.getScreenName());
                                File f = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                                FileInputStream in = new FileInputStream(f);
                                out.putNextEntry(new ZipEntry(f.getName()));
                                int len;
                                while ((len = in.read(buf)) > 0) {
                                    out.write(buf, 0, len);
                                }
                                out.closeEntry();
                                in.close();
                            }
                            out.close();
                        } catch (IOException e) {
                        }

                    }

                    if (dlFile != null) {
                        try {
                            DownloadResource downloadResource = new DownloadResource(dlFile, getApplication());
                            getApplication().getMainWindow().open(downloadResource, "_new");
                        } catch (FileNotFoundException e) {
                            getWindow().showNotification("File not found !",
                                    Window.Notification.TYPE_ERROR_MESSAGE);
                            e.printStackTrace();
                        }

                    }

                    if (dlFile != null) {
                        dlFile.delete();
                    }
                }

            }
        });

        Button btDelete = new Button("Delete File(s)");
        btDelete.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {

                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        String fileToDelete = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        logger.log(Level.INFO, "Delete File " + fileToDelete);
                        try {
                            FileObject delFile = fFileSystemManager.resolveFile(fileToDelete, fOpts);
                            logger.log(Level.INFO, "vfs2portlet: delete file " + delFile.getName() + " by "
                                    + user.getScreenName());
                            boolean b = delFile.delete();
                            if (b)
                                logger.log(Level.INFO, "delete ok");
                            else
                                logger.log(Level.INFO, "delete failed");
                        } catch (FileSystemException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        Button selAll = new Button("Select All", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(table.getItemIds());
            }
        });

        Button selNone = new Button("Select None", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(null);
            }
        });

        final UploadReceiver receiver = new UploadReceiver();
        upload = new Upload(null, receiver);
        upload.setImmediate(true);
        upload.setButtonCaption("File Upload");

        upload.addListener((new Upload.SucceededListener() {

            private static final long serialVersionUID = 1L;

            public void uploadSucceeded(SucceededEvent event) {

                try {
                    String fileName = receiver.getFileName();
                    ByteArrayOutputStream bos = receiver.getUploadedFile();
                    byte[] buf = bos.toByteArray();
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    app.getMainWindow().showNotification("Upload " + fileName + " successful ! ",
                            Notification.TYPE_TRAY_NOTIFICATION);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }));

        upload.addListener(new Upload.FailedListener() {
            private static final long serialVersionUID = 1L;

            public void uploadFailed(FailedEvent event) {
                System.out.println("Upload failed ! ");
            }
        });

        multiFileUpload = new MultiFileUpload() {

            private static final long serialVersionUID = 1L;

            protected void handleFile(File file, String fileName, String mimeType, long length) {
                try {
                    byte[] buf = FileUtils.readFileToByteArray(file);
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (FileSystemException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            protected FileBuffer createReceiver() {
                FileBuffer receiver = super.createReceiver();
                /*
                 * Make receiver not to delete files after they have been
                 * handled by #handleFile().
                 */
                receiver.setDeleteFiles(false);
                return receiver;
            }
        };
        multiFileUpload.setUploadButtonCaption("Upload File(s)");

        HorizontalLayout filterGrp = new HorizontalLayout();
        filterGrp.setSpacing(true);
        final TextField tfFilter = new TextField();
        Button btFileFilter = new Button("Filter", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                String filterVal = (String) tfFilter.getValue();
                try {
                    if (filterVal == null || filterVal.length() == 0) {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } else {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, filterVal);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Button btResetFileFilter = new Button("Reset", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                try {
                    tfFilter.setValue("");
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (ReadOnlyException e) {
                    e.printStackTrace();
                } catch (ConversionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        filterGrp.addComponent(tfFilter);
        filterGrp.addComponent(btFileFilter);
        filterGrp.addComponent(btResetFileFilter);

        addComponent(filterGrp);

        addComponent(table);

        HorizontalLayout btGrp = new HorizontalLayout();

        btGrp.setSpacing(true);
        btGrp.addComponent(selAll);
        btGrp.setComponentAlignment(selAll, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(selNone);
        btGrp.setComponentAlignment(selNone, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(btDownload);
        btGrp.setComponentAlignment(btDownload, Alignment.MIDDLE_CENTER);

        List<Role> roles = null;
        boolean matchUserRole = false;
        try {

            if (user != null) {
                roles = user.getRoles();

            }
        } catch (SystemException e) {
            e.printStackTrace();
        }

        if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() == 0) {
            btGrp.addComponent(btDelete);
            btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
        } else if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() > 0) {
            matchUserRole = isUserInRole(roles, cb.getDeleteRoles());
            if (matchUserRole) {
                btGrp.addComponent(btDelete);
                btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
            }

        }
        if (cb.isUploadEnabled() && cb.getUploadRoles().length() == 0) {
            btGrp.addComponent(upload);
            btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
            btGrp.addComponent(multiFileUpload);
            btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
        } else if (cb.isUploadEnabled() && cb.getUploadRoles().length() > 0) {

            matchUserRole = isUserInRole(roles, cb.getUploadRoles());
            if (matchUserRole) {
                btGrp.addComponent(upload);
                btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
                btGrp.addComponent(multiFileUpload);
                btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
            }
        }
        addComponent(btGrp);

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:edu.stanford.muse.email.JarDocCache.java

@Override
public synchronized void saveContents(String contents, String prefix, int msgNum)
        throws IOException, GeneralSecurityException {
    JarOutputStream jos = getContentsJarOS(prefix);

    // create the bytes
    ZipEntry ze = new ZipEntry(msgNum + ".content");
    ze.setMethod(ZipEntry.DEFLATED);
    //      byte[] buf = CryptoUtils.getEncryptedBytes(contents.getBytes("UTF-8"));
    byte[] buf = contents.getBytes("UTF-8");
    jos.putNextEntry(ze);/*from w w w .  j  a  va  2 s  .c o m*/
    jos.write(buf, 0, buf.length);
    jos.closeEntry();
    jos.flush();
}

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/*www. j  a v a 2s  . c  om*/
 */
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:it.unimi.di.big.mg4j.document.SimpleCompressedDocumentCollectionBuilder.java

public void close() throws IOException {
    documentsOutputBitStream.close();/*from w ww  .  j  a va  2s .co m*/
    termsOutputStream.close();
    IOUtils.closeQuietly(nonTermsOutputStream);
    documentOffsetsObs.close();
    termOffsetsObs.close();
    if (nonTermOffsetsObs != null)
        nonTermOffsetsObs.close();
    if (hasNonText) {
        if (documents == 0)
            nonTextZipOutputStream.putNextEntry(new ZipEntry("dummy"));
        nonTextZipDataOutputStream.close();
    }

    final SimpleCompressedDocumentCollection simpleCompressedDocumentCollection = new SimpleCompressedDocumentCollection(
            relative ? new File(basenameSuffix).getName().toString() : basenameSuffix, documents, terms.size(),
            nonTerms != null ? nonTerms.size() : -1, exact, documentFactory);
    IOFactories.storeObject(ioFactory, simpleCompressedDocumentCollection,
            basenameSuffix + DocumentCollection.DEFAULT_EXTENSION);
    simpleCompressedDocumentCollection.close();

    final PrintStream stats = new PrintStream(
            ioFactory.getOutputStream(basenameSuffix + SimpleCompressedDocumentCollection.STATS_EXTENSION));
    final long overallBits = bitsForTitles + bitsForUris + bitsForFieldLengths + bitsForWords + bitsForNonWords;
    stats.println("Documents: " + Util.format(documents) + " (" + Util.format(overallBits) + ", "
            + Util.format(overallBits / (double) documents) + " bits per document)");
    stats.println("Terms: " + Util.format(terms.size()) + " (" + Util.format(words) + " words, "
            + Util.format(bitsForWords) + " bits, " + Util.format(bitsForWords / (double) words)
            + " bits per word)");
    if (exact)
        stats.println("Nonterms: " + Util.format(nonTerms.size()) + " (" + Util.format(words) + " nonwords, "
                + Util.format(bitsForNonWords) + " bits, " + Util.format(bitsForNonWords / (double) words)
                + " bits per nonword)");
    stats.println("Bits for field lengths: " + Util.format(bitsForFieldLengths) + " ("
            + Util.format(bitsForFieldLengths / (double) fields) + " bits per field)");
    stats.println("Bits for URIs: " + Util.format(bitsForUris) + " ("
            + Util.format(bitsForUris / (double) documents) + " bits per URI)");
    stats.println("Bits for titles: " + Util.format(bitsForTitles) + " ("
            + Util.format(bitsForTitles / (double) documents) + " bits per title)");
    stats.close();

}