Example usage for java.util.zip ZipOutputStream write

List of usage examples for java.util.zip ZipOutputStream write

Introduction

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

Prototype

public synchronized void write(byte[] b, int off, int len) throws IOException 

Source Link

Document

Writes an array of bytes to the current ZIP entry data.

Usage

From source file:com.esd.ps.EmployerController.java

/**
 * txtzip//  w  ww .j  a  v a2s  . c o m
 * 
 * @param zos
 * @param url
 * @param packId
 */
public void writeTXTInZIP(ZipOutputStream zos, String url, int packId) {
    byte[] bufs = new byte[1024 * 10];
    if (creatTxtFile(url)) {
        ZipEntry zipEntry = new ZipEntry("readme.txt");
        try {
            zos.putNextEntry(zipEntry);
            writeInTXT(url, packId);
            InputStream txtIs = new FileInputStream(new File(url + "/readme.txt"));
            BufferedInputStream txtBis = new BufferedInputStream(txtIs, 1024);
            int readme;
            while ((readme = txtBis.read(bufs)) > 0) {
                zos.write(bufs, 0, readme);//
            }
            txtBis.close();
            txtIs.close();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}

From source file:org.obiba.mica.file.service.FileSystemService.java

/**
 * Creates a zipped file of the path and it's subdirectories/files
 *
 * @param path/*from  ww  w.  ja v  a2s  .  co  m*/
 * @param publishedFS
 * @return
   */
public String zipDirectory(String path, boolean publishedFS) {
    List<AttachmentState> attachmentStates = getAllowedStates(path, publishedFS);
    String zipName = Paths.get(path).getFileName().toString() + ".zip";

    FileOutputStream fos = null;

    try {
        byte[] buffer = new byte[1024];

        fos = tempFileService.getFileOutputStreamFromFile(zipName);

        ZipOutputStream zos = new ZipOutputStream(fos);

        for (AttachmentState state : attachmentStates) {
            if (FileUtils.isDirectory(state)) {
                zos.putNextEntry(new ZipEntry(relativizePaths(path, state.getFullPath()) + File.separator));
            } else {
                zos.putNextEntry(new ZipEntry(relativizePaths(path, state.getFullPath())));

                InputStream in = fileStoreService
                        .getFile(publishedFS ? state.getPublishedAttachment().getFileReference()
                                : state.getAttachment().getFileReference());

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

                in.close();
            }

            zos.closeEntry();
        }

        zos.finish();
    } catch (IOException ioe) {
        Throwables.propagate(ioe);
    } finally {
        IOUtils.closeQuietly(fos);
    }

    return zipName;
}

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

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().debug("Skipping step");
        return;//from   ww  w.ja v a 2  s .c om
    }
    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:org.auscope.portal.server.web.controllers.JobListController.java

/**
 * Sends the contents of one or more job files as a ZIP archive to the
 * client.//from w  w w  .j a  va  2  s .c o  m
 *
 * @param request The servlet request including a jobId parameter and a
 *                files parameter with the filenames separated by comma
 * @param response The servlet response receiving the data
 *
 * @return null on success or the joblist view with an error parameter on
 *         failure.
 */
@RequestMapping("/downloadAsZip.do")
public ModelAndView downloadAsZip(HttpServletRequest request, HttpServletResponse response) {

    String jobIdStr = request.getParameter("jobId");
    String filesParam = request.getParameter("files");
    GeodesyJob job = null;
    String errorString = null;

    if (jobIdStr != null) {
        try {
            int jobId = Integer.parseInt(jobIdStr);
            job = jobManager.getJobById(jobId);
        } catch (NumberFormatException e) {
            logger.error("Error parsing job ID!");
        }
    }

    if (job != null && filesParam != null) {
        String[] fileNames = filesParam.split(",");
        logger.debug("Archiving " + fileNames.length + " file(s) of job " + jobIdStr);

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"jobfiles.zip\"");

        try {
            boolean readOneOrMoreFiles = false;
            ZipOutputStream zout = new ZipOutputStream(response.getOutputStream());
            for (String fileName : fileNames) {
                File f = new File(job.getOutputDir() + File.separator + fileName);
                if (!f.canRead()) {
                    // if a file could not be read we go ahead and try the
                    // next one.
                    logger.error("File " + f.getPath() + " not readable!");
                } else {
                    byte[] buffer = new byte[16384];
                    int count = 0;
                    zout.putNextEntry(new ZipEntry(fileName));
                    FileInputStream fin = new FileInputStream(f);
                    while ((count = fin.read(buffer)) != -1) {
                        zout.write(buffer, 0, count);
                    }
                    zout.closeEntry();
                    readOneOrMoreFiles = true;
                }
            }
            if (readOneOrMoreFiles) {
                zout.finish();
                zout.flush();
                zout.close();
                return null;

            } else {
                zout.close();
                errorString = new String("Could not access the files!");
                logger.error(errorString);
            }

        } catch (IOException e) {
            errorString = new String("Could not create ZIP file: " + e.getMessage());
            logger.error(errorString);
        }
    }

    // We only end up here in case of an error so return a suitable message
    if (errorString == null) {
        if (job == null) {
            errorString = new String("Invalid job specified!");
            logger.error(errorString);
        } else if (filesParam == null) {
            errorString = new String("No filename(s) provided!");
            logger.error(errorString);
        } else {
            // should never get here
            errorString = new String("Something went wrong.");
            logger.error(errorString);
        }
    }
    return new ModelAndView("joblist", "error", errorString);
}

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

private static void addZipEntries(ZipOutputStream out, List<IModuleResource> allResources,
        Set<IModuleResource> filterInFiles) throws Exception {
    if (allResources == null)
        return;/*from w w  w . j  ava 2s  . co m*/

    for (IModuleResource resource : allResources) {
        if (resource instanceof IModuleFolder) {

            IModuleResource[] folderResources = ((IModuleFolder) resource).members();

            String entryPath = getZipRelativeName(resource);

            ZipEntry zipEntry = new ZipEntry(entryPath);

            long timeStamp = 0;
            IContainer folder = (IContainer) resource.getAdapter(IContainer.class);
            if (folder != null) {
                timeStamp = folder.getLocalTimeStamp();
            }

            if (timeStamp != IResource.NULL_STAMP && timeStamp != 0) {
                zipEntry.setTime(timeStamp);
            }

            out.putNextEntry(zipEntry);
            out.closeEntry();

            addZipEntries(out, Arrays.asList(folderResources), filterInFiles);
            continue;
        }

        IModuleFile moduleFile = (IModuleFile) resource;
        // Only add files that are in the filterInList
        if (!filterInFiles.contains(moduleFile)) {
            continue;
        }

        String entryPath = getZipRelativeName(resource);

        ZipEntry zipEntry = new ZipEntry(entryPath);

        InputStream input = null;
        long timeStamp = 0;
        IFile iFile = (IFile) moduleFile.getAdapter(IFile.class);
        if (iFile != null) {
            timeStamp = iFile.getLocalTimeStamp();
            input = iFile.getContents();
        } else {
            File file = (File) moduleFile.getAdapter(File.class);
            timeStamp = file.lastModified();
            input = new FileInputStream(file);
        }

        if (timeStamp != IResource.NULL_STAMP && timeStamp != 0) {
            zipEntry.setTime(timeStamp);
        }

        out.putNextEntry(zipEntry);

        try {
            int n = 0;
            while (n > -1) {
                n = input.read(buf);
                if (n > 0) {
                    out.write(buf, 0, n);
                }
            }
        } finally {
            input.close();
        }

        out.closeEntry();
    }
}

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

public void attach() {

    selectedDir = cb.getVfsUrl();//w w w . jav a2  s  .  c  o  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:fr.smile.alfresco.module.panier.scripts.SmilePanierExportZipWebScript.java

/**
 * Adds the entry./*  w  w w  .  ja va2 s . com*/
 *
 * @param content the content
 * @param zipOutputStream the zip output stream
 * @param path the path
 */
private void addEntry(FileInfo content, ZipOutputStream zipOutputStream, String path) {
    try {
        DictionaryService dictionaryService = services.getDictionaryService();
        ContentService contentService = services.getContentService();
        FileFolderService fileFolderService = services.getFileFolderService();

        String calculatePath = path;

        QName typeContent = content.getType();
        String inContentName = content.getName();
        NodeRef inContentNodeRef = content.getNodeRef();

        logger.debug("Add entrry: " + inContentName);

        if (dictionaryService.isSubClass(typeContent, ContentModel.TYPE_CONTENT)) {
            logger.debug("Entry: " + inContentName + " is a content");

            calculatePath = calculatePath + inContentName;

            logger.debug("calculatePath : " + calculatePath);

            ZipEntry e = new ZipEntry(calculatePath);

            zipOutputStream.putNextEntry(e);
            ContentReader inFileReader = contentService.getReader(inContentNodeRef, ContentModel.PROP_CONTENT);

            if (inFileReader != null) {

                InputStream in = inFileReader.getContentInputStream();

                final int initSize = 1024;

                byte buffer[] = new byte[initSize];
                while (true) {
                    int readBytes = in.read(buffer, 0, buffer.length);
                    if (readBytes <= 0) {
                        break;
                    }

                    zipOutputStream.write(buffer, 0, readBytes);
                }

                in.close();
                zipOutputStream.closeEntry();
            } else {
                logger.warn("Error during read content of file " + inContentName);
            }

        } else if (dictionaryService.isSubClass(typeContent, ContentModel.TYPE_FOLDER)) {
            logger.debug("Entry: " + inContentName + " is a content");

            calculatePath = calculatePath + inContentName + "/";

            logger.debug("calculatePath : " + calculatePath);

            List<FileInfo> files = fileFolderService.list(inContentNodeRef);

            if (files.size() == 0) {
                ZipEntry e = new ZipEntry(calculatePath);
                zipOutputStream.putNextEntry(e);

            } else {
                for (FileInfo file : files) {
                    addEntry(file, zipOutputStream, calculatePath);
                }
            }

        }
    } catch (Exception e) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                "Erreur exportation Zip : " + e.getMessage(), e);
    }

}

From source file:org.esupportail.portlet.filemanager.services.ServersAccessService.java

private void addChildrensTozip(ZipOutputStream out, byte[] zippingBuffer, String dir, String folder,
        SharedUserPortletParameters userParameters) throws IOException {
    JsTreeFile tFile = get(dir, userParameters, false, false);
    if ("file".equals(tFile.getType())) {
        DownloadFile dFile = getFile(dir, userParameters);

        //GIP Recia : In some cases (ie, file has NTFS security permissions set), the dFile may be Null.
        //So we must check for null in order to prevent a general catastrophe
        if (dFile == null) {
            log.warn("Download file is null!  " + dir);
            return;
        }/*from   w  w w  .j a va2s . c o m*/
        String fileName = unAccent(folder.concat(dFile.getBaseName()));

        //With java 7, encoding should be added to support special characters in the file names
        //http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499
        out.putNextEntry(new ZipEntry(fileName));

        // MBD: this is a problem for large files, because IOUtils.toByteArray() copy all the file in memory
        //out.write(IOUtils.toByteArray(dFile.getInputStream()));
        int count;
        final InputStream dFileInputStream = dFile.getInputStream();
        while ((count = dFileInputStream.read(zippingBuffer, 0, ZIP_BUFFER_SIZE)) != -1) {
            out.write(zippingBuffer, 0, count);
        }

        out.closeEntry();
    } else {
        folder = unAccent(folder.concat(tFile.getTitle()).concat("/"));
        //Added for GIP Recia : This creates an empty file with the same name as the directory but it allows
        //for zipping empty directories
        out.putNextEntry(new ZipEntry(folder));
        out.closeEntry();
        List<JsTreeFile> childrens = this.getChildren(dir, userParameters);
        for (JsTreeFile child : childrens) {
            this.addChildrensTozip(out, zippingBuffer, child.getPath(), folder, userParameters);
        }
    }
}

From source file:com.esd.ps.WorkerController.java

/**
 * //from  www .j av a2s.  co  m
 * 
 * @param zipFile
 * @param list
 * @return
 */
public String wrongPath(File zipFile, List<taskWithBLOBs> list) {
    logger.debug("list2:{}", list);
    try {
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
        byte[] bufs = new byte[1024 * 10];
        for (Iterator<taskWithBLOBs> iterator = list.iterator(); iterator.hasNext();) {
            taskWithBLOBs taskWithBLOBs = (taskWithBLOBs) iterator.next();
            String fileName = taskWithBLOBs.getTaskName() == null ? "Task.wav" : taskWithBLOBs.getTaskName();
            // ZIP,
            ZipEntry zipEntry = new ZipEntry(fileName);
            zos.putNextEntry(zipEntry);
            byte[] data = taskWithBLOBs.getTaskWav();
            InputStream is = new ByteArrayInputStream(data);
            // ?
            BufferedInputStream bis = new BufferedInputStream(is, 1024);
            int read;
            while ((read = bis.read(bufs)) > 0) {
                zos.write(bufs, 0, read);//
            }
            // zos.closeEntry();
            bis.close();
            is.close();
            // task
        }
        zos.close();// ,??0kb
        fos.flush();
        fos.close();

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

        e.printStackTrace();
    }
    return "";
}