Example usage for java.util.zip ZipOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java

@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
    ZipOutputStream zout = null;
    OutputStream out = null;/* ww w  .  j  av  a  2 s  . c  o m*/
    try {
        sCheckPermissions(resourceRequest);
        _log.info("Export All As Zip");

        Map<String, String> savedscripts = new TreeMap<String, String>();
        PortletPreferences prefs = resourceRequest.getPreferences();
        for (String prefName : prefs.getMap().keySet()) {
            if (prefName != null && prefName.startsWith("savedscript.")) {
                String scriptName = prefName.substring("savedscript.".length());
                String script = prefs.getValue(prefName, "");
                String lang = prefs.getValue("lang." + scriptName, getDefaultLanguage());
                savedscripts.put(scriptName + "." + lang, script);
            }
        }

        String filename = "liferay-scripts.zip";

        out = resourceResponse.getPortletOutputStream();
        zout = new ZipOutputStream(out);
        for (String key : savedscripts.keySet()) {
            String value = savedscripts.get(key);
            zout.putNextEntry(new ZipEntry(key));
            zout.write(value.getBytes("utf-8"));
        }
        resourceResponse.setContentType("application/zip");
        resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate");
        resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, "filename=" + filename);

    } catch (Exception e) {
        _log.error(e);
    } finally {
        try {
            if (zout != null) {
                zout.close();
            }
        } catch (Exception e) {
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
        }
    }
}

From source file:lu.fisch.moenagade.model.Project.java

private void createBackupOf(String folder) {
    // backup SRC directory
    File fDir = new File(directoryName + System.getProperty("file.separator") + folder);
    // check the versions directory
    String versionDir = directoryName + System.getProperty("file.separator") + "versions";
    File versionFile = new File(versionDir);
    if (!versionFile.exists())
        versionFile.mkdir();// ww w. j  a va2s  .  c  o m
    // get the new filename
    SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    String now = dateFormater.format(new Date());
    String zipFilename = folder + "-" + now + ".zip";
    zipFilename = directoryName + System.getProperty("file.separator") + "versions"
            + System.getProperty("file.separator") + zipFilename;
    try {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(new File(zipFilename)));
        addToZip(out, now + System.getProperty("file.separator"), fDir);
        out.close();

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

From source file:com.edgenius.core.util.ZipFileUtil.java

/**
 * Creates a ZIP file and places it in the current working directory. The zip file is compressed
 * at the default compression level of the Deflater.
 * // w ww.  j a  v a 2s . c om
 * @param listToZip. Key is file or directory, value is parent directory which will remove from given file/directory because 
 * compression only save relative directory.  For example, c:\geniuswiki\data\repository\somefile, if value is c:\geniuswiki, then only 
 * \data\repository\somefile will be saved.  It is very important, the value must be canonical path, ie, c:\my document\geniuswiki, 
 * CANNOT like this "c:\my doc~1\" 
 * 
 * 
 */
public static void createZipFile(String zipFileName, Map<File, String> listToZip, boolean withEmptyDir)
        throws ZipFileUtilException {
    ZipOutputStream zop = null;
    try {
        zop = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
        zop.setMethod(ZipOutputStream.DEFLATED);
        zop.setLevel(Deflater.DEFAULT_COMPRESSION);

        for (Entry<File, String> entry : listToZip.entrySet()) {
            File file = entry.getKey();
            if (!file.exists()) {
                log.warn("Unable to find file " + file + " to zip");
                continue;
            }
            if (file.isDirectory()) {
                Collection<File> list = FileUtils.listFiles(file, null, true);
                for (File src : list) {
                    addEntry(zop, src, createRelativeDir(src.getCanonicalPath(), entry.getValue()));
                }
                if (withEmptyDir) {
                    final List<File> emptyDirs = new ArrayList<File>();
                    if (file.list().length == 0) {
                        emptyDirs.add(file);
                    } else {
                        //I just don't know how quickly to find out all empty sub directories recursively. so use below hack:
                        FileUtils.listFiles(file, FileFilterUtils.falseFileFilter(), new IOFileFilter() {
                            //JDK1.6 @Override
                            public boolean accept(File f) {
                                if (!f.isDirectory())
                                    return false;

                                int size = f.listFiles().length;
                                if (size == 0) {
                                    emptyDirs.add(f);
                                }
                                return true;
                            }

                            //JDK1.6 @Override
                            public boolean accept(File arg0, String arg1) {
                                return true;
                            }
                        });
                    }
                    for (File src : emptyDirs) {
                        addEntry(zop, null, createRelativeDir(src.getCanonicalPath(), entry.getValue()));
                    }
                }
            } else {
                addEntry(zop, file, createRelativeDir(file.getCanonicalPath(), entry.getValue()));
            }

        }
    } catch (IOException e1) {
        throw new ZipFileUtilException(
                "An error has occurred while trying to zip the files. Error message is: ", e1);
    } finally {
        try {
            if (zop != null)
                zop.close();
        } catch (Exception e) {
        }
    }

}

From source file:io.sledge.core.impl.installer.SledgePackageConfigurer.java

private void createNewZipfileWithReplacedPlaceholders(InputStream packageStream, Path configurationPackagePath,
        Properties envProps) throws IOException {

    // For reading the original configuration package
    ZipInputStream configPackageZipStream = new ZipInputStream(new BufferedInputStream(packageStream),
            Charset.forName("UTF-8"));

    // For outputting the configured (placeholders replaced) version of the package as zip file
    File outZipFile = configurationPackagePath.toFile();
    ZipOutputStream outConfiguredZipStream = new ZipOutputStream(new FileOutputStream(outZipFile));

    ZipEntry zipEntry;/*from   www  .  j a v  a 2  s . c  o  m*/
    while ((zipEntry = configPackageZipStream.getNextEntry()) != null) {

        if (zipEntry.isDirectory()) {
            configPackageZipStream.closeEntry();
            continue;
        } else {
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            int length;
            byte[] buffer = new byte[2048];
            while ((length = configPackageZipStream.read(buffer, 0, buffer.length)) >= 0) {
                output.write(buffer, 0, length);
            }

            InputStream zipEntryInputStream = new BufferedInputStream(
                    new ByteArrayInputStream(output.toByteArray()));

            if (zipEntry.getName().endsWith("instance.properties")) {
                ByteArrayOutputStream envPropsOut = new ByteArrayOutputStream();
                envProps.store(envPropsOut, "Environment configurations");
                zipEntryInputStream = new BufferedInputStream(
                        new ByteArrayInputStream(envPropsOut.toByteArray()));

            } else if (isTextFile(zipEntry.getName(), zipEntryInputStream)) {
                String configuredContent = StrSubstitutor.replace(output, envProps);
                zipEntryInputStream = new BufferedInputStream(
                        new ByteArrayInputStream(configuredContent.getBytes()));
            }

            // Add to output zip file
            addToZipFile(zipEntry.getName(), zipEntryInputStream, outConfiguredZipStream);

            zipEntryInputStream.close();
            configPackageZipStream.closeEntry();
        }
    }

    outConfiguredZipStream.close();
    configPackageZipStream.close();
}

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

public void attach() {

    selectedDir = cb.getVfsUrl();//from   w  ww . j a v  a  2s. 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:com.dotmarketing.portlets.cmsmaintenance.action.ViewCMSMaintenanceAction.java

/**
 * Will zip up all files in the tmp directory and send the result to the
 * given OutputStream//from   w w  w  .jav a 2s. c o m
 *
 * @param out
 *            OutputStream to write the zip files to
 * @throws IOException
 * @author Will
 */
private void zipTempDirectoryToStream(OutputStream out) throws IOException {
    byte b[] = new byte[512];
    ZipOutputStream zout = new ZipOutputStream(out);
    ZipUtil.zipDirectory(backupTempFilePath, zout);
    //      File f = new File(backupTempFilePath);
    //      String[] s = f.list();
    //      for (int i = 0; i < s.length; i++) {
    //         if(s[i].equals(".svn")){
    //            continue;
    //         }
    //         f = new File(backupTempFilePath + File.separator + "" + s[i]);
    //         InputStream in;
    //         if(f.isDirectory()){
    //            in = new BufferedInputStream(new ByteArrayInputStream(f.));
    //         }else{
    //            in = new BufferedInputStream(new FileInputStream(f));
    //         }
    //         ZipEntry e = new ZipEntry(s[i].replace(File.separatorChar, '/'));
    //         zout.putNextEntry(e);
    //         int len = 0;
    //         while ((len = in.read(b)) != -1) {
    //            zout.write(b, 0, len);
    //         }
    //         zout.closeEntry();
    //         in.close();
    //      }
    zout.close();
    out.close();
}

From source file:com.funambol.framework.tools.FileArchiverTest.java

public void testAddDirectory_WithFilter() throws Throwable {

    String sourceDirname = MULTILEVELTREE + File.separator + "first";
    String destFilename = BASE_TARGET_DIR + "addedDir.zip";

    File destFile = new File(destFilename);
    if (destFile.exists()) {
        assertTrue("Unable to delete destination file", destFile.delete());
    }//  w w w . j  ava 2  s .c o  m

    // recursively = true, includeRoot = true
    FileArchiver instance = new FileArchiver(sourceDirname, destFilename, true, true);

    // add only directories
    instance.setFilter(DirectoryFileFilter.DIRECTORY);

    FileOutputStream outputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {

        outputStream = new FileOutputStream(destFile, false);
        zipOutputStream = new ZipOutputStream(outputStream);

        PrivateAccessor.invoke(instance, "addDirectory",
                new Class[] { ZipOutputStream.class, String.class, File.class },
                new Object[] { zipOutputStream, "", new File(sourceDirname) });

        assertCounters(instance, 2, 0, 0, 3);
        assertDestFile(destFile, true);
    } finally {

        if (zipOutputStream != null) {
            zipOutputStream.flush();
        }
        if (outputStream != null) {
            outputStream.flush();
        }
    }

    try {
        sourceDirname = ONELEVELTREE;

        PrivateAccessor.setField(instance, "sourceFile", new File(sourceDirname));

        PrivateAccessor.invoke(instance, "addDirectory",
                new Class[] { ZipOutputStream.class, String.class, File.class },
                new Object[] { zipOutputStream, "", new File(sourceDirname) });

        assertCounters(instance, 3, 0, 0, 5);
        assertDestFile(destFile, true);

    } finally {
        if (zipOutputStream != null) {
            zipOutputStream.flush();
            zipOutputStream.close();
        }
        if (outputStream != null) {
            outputStream.flush();
            outputStream.close();
        }
    }

    List<String> expContent = new ArrayList<String>();
    expContent.add("first/");
    expContent.add("first/second/");
    expContent.add("oneleveltree/");
    assertDestFileContent(destFile, expContent);
}

From source file:de.innovationgate.wga.model.WGADesignConfigurationModel.java

public void exportPlugin(File pluginFile, int buildnumber, boolean obfuscate, boolean increaseBuild,
        String javaSourceFolder) throws IOException, PersistentKeyException, GeneralSecurityException,
        IllegalAccessException, InvocationTargetException {
    // Update build number
    if (_pluginBuild != buildnumber) {
        setPluginBuild(buildnumber);//  ww  w .  j a  va2 s  .c om
        saveChanges();
    }

    ZipOutputStream stream = createZIP(pluginFile, obfuscate, javaSourceFolder);
    stream.close();

    // Increment build version
    if (increaseBuild) {
        setPluginBuild(getPluginBuild() + 1);
        saveChanges();
    }

}

From source file:com.funambol.framework.tools.FileArchiverTest.java

public void testAddDirectory() throws Throwable {

    String sourceDirname = MULTILEVELTREE + File.separator + "first";
    String destFilename = BASE_TARGET_DIR + "addedDir.zip";

    File destFile = new File(destFilename);
    if (destFile.exists()) {
        assertTrue("Unable to delete destination file", destFile.delete());
    }/*from  w  w w .  j  a v  a2 s .co m*/

    // recursively = true, includeRoot = true
    FileArchiver instance = new FileArchiver(sourceDirname, destFilename, true, true);

    FileOutputStream outputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {

        outputStream = new FileOutputStream(destFile, false);
        zipOutputStream = new ZipOutputStream(outputStream);

        PrivateAccessor.invoke(instance, "addDirectory",
                new Class[] { ZipOutputStream.class, String.class, File.class },
                new Object[] { zipOutputStream, "", new File(sourceDirname) });

        assertCounters(instance, 2, 3, 0, 0);
        assertDestFile(destFile, true);

    } finally {

        if (zipOutputStream != null) {
            zipOutputStream.flush();
        }
        if (outputStream != null) {
            outputStream.flush();
        }
    }

    try {
        sourceDirname = ONELEVELTREE;

        PrivateAccessor.setField(instance, "sourceFile", new File(sourceDirname));

        PrivateAccessor.invoke(instance, "addDirectory",
                new Class[] { ZipOutputStream.class, String.class, File.class },
                new Object[] { zipOutputStream, "", new File(sourceDirname) });

        assertCounters(instance, 3, 5, 0, 0);
        assertDestFile(destFile, true);

    } finally {
        if (zipOutputStream != null) {
            zipOutputStream.flush();
            zipOutputStream.close();
        }
        if (outputStream != null) {
            outputStream.flush();
            outputStream.close();
        }
    }

    List<String> expContent = new ArrayList<String>();
    expContent.add("first/");
    expContent.add("first/firstlog.zip");
    expContent.add("first/second/");
    expContent.add("first/second/secondlog.txt");
    expContent.add("first/second/secondlog.zip");
    expContent.add("oneleveltree/");
    expContent.add("oneleveltree/synclog.txt");
    expContent.add("oneleveltree/synclog.zip");
    assertDestFileContent(destFile, expContent);
}

From source file:io.lightlink.excel.StreamingExcelTransformer.java

public void doExport(InputStream template, OutputStream out, ExcelStreamVisitor visitor) throws IOException {
    try {//from w  ww.j  a  v  a  2s  .  co  m
        ZipInputStream zipIn = new ZipInputStream(template);
        ZipOutputStream zipOut = new ZipOutputStream(out);

        ZipEntry entry;

        Map<String, byte[]> sheets = new HashMap<String, byte[]>();

        while ((entry = zipIn.getNextEntry()) != null) {

            String name = entry.getName();

            if (name.startsWith("xl/sharedStrings.xml")) {

                byte[] bytes = IOUtils.toByteArray(zipIn);
                zipOut.putNextEntry(new ZipEntry(name));
                zipOut.write(bytes);

                sharedStrings = processSharedStrings(bytes);

            } else if (name.startsWith("xl/worksheets/sheet")) {
                byte[] bytes = IOUtils.toByteArray(zipIn);
                sheets.put(name, bytes);
            } else if (name.equals("xl/calcChain.xml")) {
                // skip this file, let excel recreate it
            } else if (name.equals("xl/workbook.xml")) {
                zipOut.putNextEntry(new ZipEntry(name));

                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();
                Writer writer = new OutputStreamWriter(zipOut, "UTF-8");

                byte[] bytes = IOUtils.toByteArray(zipIn);
                saxParser.parse(new ByteArrayInputStream(bytes), new WorkbookTemplateHandler(writer));

                writer.flush();
            } else {
                zipOut.putNextEntry(new ZipEntry(name));
                IOUtils.copy(zipIn, zipOut);
            }

        }

        for (Map.Entry<String, byte[]> sheetEntry : sheets.entrySet()) {
            String name = sheetEntry.getKey();

            byte[] bytes = sheetEntry.getValue();
            zipOut.putNextEntry(new ZipEntry(name));
            processSheet(bytes, zipOut, visitor);
        }

        zipIn.close();
        template.close();

        zipOut.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.toString(), e);
    }
}