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:it.eng.spagobi.tools.downloadFiles.service.DownloadZipAction.java

public void createZipFromFiles(Vector<File> files, String outputFileName, String folderName)
        throws IOException {
    logger.debug("IN");
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
    // Compress the files 
    for (Iterator iterator = files.iterator(); iterator.hasNext();) {
        File file = (File) iterator.next();

        FileInputStream in = new FileInputStream(file);

        String fileName = file.getName();
        // The name to Inssert: remove the parameter folder
        //         int lastIndex=folderName.length();
        //         String fileToInsert=fileName.substring(lastIndex+1);

        logger.debug("Adding to zip entry " + fileName);
        ZipEntry zipEntry = new ZipEntry(fileName);

        // Add ZIP entry to output stream. 
        out.putNextEntry(zipEntry);//from   w  ww.j a va  2s .co  m

        // Transfer bytes from the file to the ZIP file 
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry 
        out.closeEntry();
        in.close();
    }
    // Complete the ZIP file 
    out.close();
    logger.debug("OUT");
}

From source file:es.urjc.mctwp.bbeans.research.image.DownloadBean.java

private ZipOutputStream prepareZOS(String cntDesc) throws IOException {
    ZipOutputStream result = null;
    HttpServletResponse response = prepareResponse();

    //Get file name without parents and prepare header
    String fileName = cntDesc + FilenameUtils.EXTENSION_SEPARATOR_STR + contentType;
    configResponseHeader(response, contentType, fileName);
    result = new ZipOutputStream(response.getOutputStream());

    return result;
}

From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java

private void zipFolder(String srcFolder, String destZipFile) throws IOException {
    ZipOutputStream zip = null;//from   w  w  w.j ava2 s . co m
    FileOutputStream fileWriter = null;
    try {
        fileWriter = new FileOutputStream(destZipFile);
        zip = new ZipOutputStream(fileWriter);
        addFileToZip(srcFolder, zip);
    } finally {
        try {
            if (zip != null) {
                zip.flush();
                zip.close();
            }
        } catch (IOException e) {
            LOGGER.error("Error occured while closing the resources after zipping the folder.", e);
        }
    }
    LOGGER.info("Created zip folder {}", destZipFile);
}

From source file:S3DataManagerTest.java

@Test
public void testZipSourceOneDir() throws Exception {
    clearSourceDirectory();//from w w w. java  2s. c o m
    String buildSpecName = "Buildspec.yml";
    File buildSpec = new File("/tmp/source/" + buildSpecName);
    String buildSpecContents = "yo\n";
    FileUtils.write(buildSpec, buildSpecContents);
    File sourceDir = new File("/tmp/source/src");
    sourceDir.mkdir();
    String srcFileName = "/tmp/source/src/file.java";
    File srcFile = new File(srcFileName);
    String srcFileContents = "int i = 1;";
    FileUtils.write(srcFile, srcFileContents);

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/tmp/source.zip"));
    S3DataManager dataManager = createDefaultSource();
    dataManager.zipSource("/tmp/source/", out, "/tmp/source/");
    out.close();

    File zip = new File("/tmp/source.zip");
    assertTrue(zip.exists());

    File unzipFolder = new File("/tmp/folder/");
    unzipFolder.mkdir();
    ZipFile z = new ZipFile(zip.getPath());
    z.extractAll(unzipFolder.getPath());
    String[] fileList = unzipFolder.list();
    assertNotNull(fileList);
    Arrays.sort(fileList);

    assertTrue(fileList.length == 2);
    assertEquals(fileList[0], buildSpecName);
    File extractedBuildSpec = new File(unzipFolder.getPath() + "/" + buildSpecName);
    assertEquals(FileUtils.readFileToString(extractedBuildSpec), buildSpecContents);

    String s = fileList[1];
    assertEquals(fileList[1], "src");
    File extractedSrcFile = new File(unzipFolder.getPath() + "/src/file.java");
    assertTrue(extractedSrcFile.exists());
    assertEquals(FileUtils.readFileToString(extractedSrcFile), srcFileContents);
}

From source file:com.ephesoft.gxt.admin.server.ExportBatchClassDownloadServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    BatchClassService batchClassService = this.getSingleBeanOfType(BatchClassService.class);
    BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    BatchClass batchClass = batchClassService.getLoadedBatchClassByIdentifier(req.getParameter(IDENTIFIER));
    String exportLearning = req.getParameter(EXPORT_LEARNING);
    if (batchClass == null) {
        log.error("Incorrect batch class identifier specified.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Incorrect batch class identifier specified.");
    } else {//from   www.  jav a2  s  . c  o  m
        // Marking exported batch class as 'Advance' as this batch has some advance feature like new FPR.rsp file.
        batchClass.setAdvancedBatchClass(Boolean.TRUE);
        Calendar cal = Calendar.getInstance();
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyy");
        String formattedDate = formatter.format(new Date());
        String zipFileName = batchClass.getIdentifier() + "_" + formattedDate + "_"
                + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.SECOND);

        String tempFolderLocation = exportSerailizationFolderPath + File.separator + zipFileName;
        File copiedFolder = new File(tempFolderLocation);

        if (copiedFolder.exists()) {
            copiedFolder.delete();
        }

        copiedFolder.mkdirs();

        BatchClassUtil.copyModules(batchClass);
        BatchClassUtil.copyDocumentTypes(batchClass);
        BatchClassUtil.copyConnections(batchClass);
        BatchClassUtil.copyScannerConfig(batchClass);
        BatchClassUtil.exportEmailConfiguration(batchClass);
        BatchClassUtil.exportUserGroups(batchClass);
        BatchClassUtil.exportBatchClassField(batchClass);
        BatchClassUtil.exportCMISConfiguration(batchClass);
        // BatchClassUtil.decryptAllPasswords(batchClass);

        File serializedExportFile = new File(
                tempFolderLocation + File.separator + batchClass.getIdentifier() + SERIALIZATION_EXT);
        try {
            SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile));

            File originalFolder = new File(
                    batchSchemaService.getBaseSampleFDLock() + File.separator + batchClass.getIdentifier());

            if (originalFolder.isDirectory()) {

                String[] folderList = originalFolder.list();
                Arrays.sort(folderList);

                for (int i = 0; i < folderList.length; i++) {
                    if (folderList[i].endsWith(SERIALIZATION_EXT)) {
                        // skip previous ser file since new is created.
                    } else if (FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getTestKVExtractionFolderName())
                            || FilenameUtils.getName(folderList[i])
                                    .equalsIgnoreCase(batchSchemaService.getTestTableFolderName())
                            || FilenameUtils.getName(folderList[i]).equalsIgnoreCase(
                                    batchSchemaService.getFileboundPluginMappingFolderName())) {
                        // Skip this folder
                        continue;
                    } else if (FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                            && Boolean.parseBoolean(exportLearning)) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    } else if (FilenameUtils.getName(folderList[i]).equalsIgnoreCase(
                            batchSchemaService.getSearchSampleName()) && Boolean.parseBoolean(exportLearning)) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    } else if (!(FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                            || FilenameUtils.getName(folderList[i])
                                    .equalsIgnoreCase(batchSchemaService.getSearchSampleName()))) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    }
                }
            }

        } catch (FileNotFoundException e) {
            // Unable to read serializable file
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.");

        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.Please try again");
        }
        resp.setContentType("application/x-zip\r\n");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
        ServletOutputStream out = null;
        ZipOutputStream zout = null;
        try {
            out = resp.getOutputStream();
            zout = new ZipOutputStream(out);
            FileUtils.zipDirectory(tempFolderLocation, zout, zipFileName);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the zip file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        } finally {
            // clean up code
            if (zout != null) {
                zout.close();
            }
            if (out != null) {
                out.flush();
            }
            FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
        }
    }
}

From source file:com.t3.persistence.PackedFile.java

public void save() throws IOException {
    CodeTimer saveTimer;/*from w ww. j a va2 s  .  co m*/

    if (!dirty) {
        return;
    }
    saveTimer = new CodeTimer("PackedFile.save");
    saveTimer.setEnabled(log.isDebugEnabled());

    // Create the new file
    File newFile = new File(tmpDir.getAbsolutePath() + "/" + new GUID() + ".pak");

    try (ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)))) {
        zout.setLevel(1); // fast compression
        saveTimer.start("contentFile");
        if (hasFile(CONTENT_FILE)) {
            zout.putNextEntry(new ZipEntry(CONTENT_FILE));
            try (InputStream is = getFileAsInputStream(CONTENT_FILE)) { // When copying, always use an InputStream
                IOUtils.copy(is, zout);
            }
            zout.closeEntry();
        }
        saveTimer.stop("contentFile");

        saveTimer.start("propertyFile");
        if (getPropertyMap().isEmpty()) {
            removeFile(PROPERTY_FILE);
        } else {
            zout.putNextEntry(new ZipEntry(PROPERTY_FILE));
            Persister.newInstance().toXML(getPropertyMap(), zout);
            zout.closeEntry();
        }
        saveTimer.stop("propertyFile");

        // Now put each file
        saveTimer.start("addFiles");
        addedFileSet.remove(CONTENT_FILE);
        for (String path : addedFileSet) {
            zout.putNextEntry(new ZipEntry(path));
            try (InputStream is = getFileAsInputStream(path)) { // When copying, always use an InputStream
                IOUtils.copy(is, zout);
            }
            zout.closeEntry();
        }
        saveTimer.stop("addFiles");

        // Copy the rest of the zip entries over
        saveTimer.start("copyFiles");
        if (file.exists()) {
            Enumeration<? extends ZipEntry> entries = zFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory() && !addedFileSet.contains(entry.getName())
                        && !removedFileSet.contains(entry.getName()) && !CONTENT_FILE.equals(entry.getName())
                        && !PROPERTY_FILE.equals(entry.getName())) {
                    zout.putNextEntry(entry);
                    try (InputStream is = getFileAsInputStream(entry.getName())) { // When copying, always use an InputStream
                        IOUtils.copy(is, zout);
                    }
                    zout.closeEntry();
                } else if (entry.isDirectory()) {
                    zout.putNextEntry(entry);
                    zout.closeEntry();
                }
            }
        }
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        zFile = null;
        saveTimer.stop("copyFiles");

        saveTimer.start("close");
        zout.close();
        saveTimer.stop("close");

        // Backup the original
        saveTimer.start("backup");
        File backupFile = new File(tmpDir.getAbsolutePath() + "/" + new GUID() + ".mv");
        if (file.exists()) {
            backupFile.delete(); // Always delete the old backup file first; renameTo() is very platform-dependent
            if (!file.renameTo(backupFile)) {
                FileUtil.copyFile(file, backupFile);
                file.delete();
            }
        }
        saveTimer.stop("backup");

        saveTimer.start("finalize");
        // Finalize
        if (!newFile.renameTo(file))
            FileUtil.copyFile(newFile, file);

        if (backupFile.exists())
            backupFile.delete();
        saveTimer.stop("finalize");

        dirty = false;
    } finally {
        saveTimer.start("cleanup");
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        if (newFile.exists())
            newFile.delete();
        saveTimer.stop("cleanup");

        if (log.isDebugEnabled())
            log.debug(saveTimer);
        saveTimer = null;
    }
}

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

@Around("execution(* brut.androlib.Androlib.buildUnknownFiles(..))" + "&& args(appDir, outFile, meta)")
public void buildUnknownFiles_around(File appDir, File outFile, Map<String, Object> meta) throws Throwable {
    if (meta.containsKey("unknownFiles")) {
        LogHelper.info("Copying unknown files/dir...");

        Map<String, String> files = (Map<String, String>) meta.get("unknownFiles");
        File tempFile = File.createTempFile("buildUnknownFiles", "tmp", outFile.getParentFile());
        tempFile.delete();/*from w w w.  jav a 2 s  .  c om*/
        boolean renamed = outFile.renameTo(tempFile);
        if (!renamed) {
            throw new AndrolibException("Unable to rename temporary file");
        }

        try (ZipFile inputFile = new ZipFile(tempFile);
                FileOutputStream fos = new FileOutputStream(outFile);
                ZipOutputStream actualOutput = new ZipOutputStream(fos)) {
            copyExistingFiles(inputFile, actualOutput, files);
            copyUnknownFiles(appDir, actualOutput, files);
        } catch (IOException ex) {
            throw new AndrolibException(ex);
        } finally {
            // Remove our temporary file.
            tempFile.delete();
        }
    }
}

From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java

/**
 * /*from  w w  w  . j a v a 2  s  .  co m*/
 * @param path
 */
public void createZipFile(String path) {
    File dir = new File(path);
    String[] list = dir.list();
    String name = path.substring(path.lastIndexOf("/"), path.length());
    String _path;

    if (!dir.canRead() || !dir.canWrite())
        return;

    int len = list.length;

    if (path.charAt(path.length() - 1) != '/')
        _path = path + "/";
    else
        _path = path;

    try {
        ZipOutputStream zip_out = new ZipOutputStream(
                new BufferedOutputStream(new FileOutputStream(_path + name + ".zip"), BUFFER));

        for (int i = 0; i < len; i++)
            zip_folder(new File(_path + list[i]), zip_out);

        zip_out.close();

    } catch (FileNotFoundException e) {
        Log.e("File not found", e.getMessage());

    } catch (IOException e) {
        Log.e("IOException", e.getMessage());
    }
}

From source file:de.fu_berlin.inf.dpp.netbeans.feedback.ErrorLogManager.java

/**
 * Convenience wrapper method to upload an error log file to the server. To
 * save time and storage space, the log is compressed to a zip archive with
 * the given zipName./*from   w  w w.j  av a2 s . c  om*/
 * 
 * @param zipName
 *            a name for the zip archive, e.g. with added user ID to make it
 *            unique, zipName must be at least 3 characters long!
 * @throws IOException
 *             if an I/O error occurs
 */
private static void uploadErrorLog(String zipName, File file, IProgressMonitor monitor) throws IOException {

    if (ERROR_LOG_UPLOAD_URL == null) {
        log.warn("error log upload url is not configured, cannot upload error log file");
        return;
    }

    File archive = new File(System.getProperty("java.io.tmpdir"), zipName + ".zip");

    ZipOutputStream out = null;
    FileInputStream in = null;

    byte[] buffer = new byte[8192];

    try {

        in = new FileInputStream(file);

        out = new ZipOutputStream(new FileOutputStream(archive));

        out.putNextEntry(new ZipEntry(file.getName()));

        int read;

        while ((read = in.read(buffer)) > 0)
            out.write(buffer, 0, read);

        out.finish();
        out.close();

        FileSubmitter.uploadFile(archive, ERROR_LOG_UPLOAD_URL, monitor);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
        archive.delete();
    }
}

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

public void attach() {

    selectedDir = cb.getVfsUrl();//  w ww .j ava2  s. com
    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();
    }

}