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:middleware.NewServerSocket.java

private boolean zipAllFiles() {

    File zipFile = new File(zipFileName);
    int index = 0;
    while (zipFile.exists()) {
        if (!zipFile.delete()) {
            ++index;/*from   www .  j  a  v  a2s .  c  o m*/
            zipFileName = "LogFiles_" + index + ".zip";
            zipFile = new File(zipFileName);
        }
    }

    try {

        FileOutputStream fos = new FileOutputStream(zipFileName);

        ZipOutputStream zos = new ZipOutputStream(fos);

        File[] files = dir.listFiles();

        for (int i = 0; i < files.length; i++) {

            // only sends the dstat log file.
            if (files[i].getName().contains("log_exp_1")) {
                FileInputStream fis = new FileInputStream(files[i]);

                // begin writing a new ZIP entry, positions the stream to the start of
                // the entry data
                zos.putNextEntry(new ZipEntry(files[i].getName()));

                int length;

                while ((length = fis.read(fileBuffer)) > 0) {
                    zos.write(fileBuffer, 0, length);
                }

                zos.closeEntry();

                // close the InputStream
                fis.close();
            }
        }

        // close the ZipOutputStream
        zos.close();

    } catch (IOException ioe) {
        return false;
    }

    return true;

}

From source file:gdt.data.entity.ArchiveHandler.java

/**
 * Compress the entities into the zip archive file. 
 * @param  entigrator entigrator instance
 * @param locator$ container of arguments in the string form. 
 * @return true if success false otherwise.
 *//*from  www . j av a 2  s.  c  o m*/
public boolean compressEntitiesToZip(Entigrator entigrator, String locator$) {
    try {
        Properties locator = Locator.toProperties(locator$);
        archiveType$ = locator.getProperty(ARCHIVE_TYPE);
        archiveFile$ = locator.getProperty(ARCHIVE_FILE);
        String entityList$ = locator.getProperty(EntityHandler.ENTITY_LIST);
        String[] sa = Locator.toArray(entityList$);
        String zipFile$ = archiveFile$;
        File zipFile = new File(zipFile$);
        if (!zipFile.exists())
            zipFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(zipFile$);
        ZipOutputStream zos = new ZipOutputStream(fos);
        ArrayList<File> fl = new ArrayList<File>();
        String entihome$ = entigrator.getEntihome();
        String entibase$ = entihome$ + "/" + Entigrator.ENTITY_BASE + "/data/";
        File entityBody;
        File entityHome;
        String iconsHome$ = entihome$ + "/" + Entigrator.ICONS + "/";
        String icon$;
        File icon;
        for (String aSa : sa) {
            entityBody = new File(entibase$ + aSa);
            fl.add(entityBody);
            entityHome = new File(entihome$ + "/" + aSa);
            if (entityHome.exists() && entityHome.isDirectory())
                getAllFiles(entityHome, fl);
            icon$ = entigrator.indx_getIcon(aSa);
            if (icon$ != null) {
                icon = new File(iconsHome$ + icon$);
                if (icon.exists())
                    fl.add(icon);
            }
        }
        for (File file : fl)
            if (!file.isDirectory())
                appendToZip(entihome$, file, zos);
        zos.close();
        fos.close();
        return true;
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
        return false;
    }
}

From source file:com.pari.pcb.zip.ZIPProcessor.java

public static void zipDirectory(String directoryName, String outFileName) throws IOException {

    FileOutputStream fos = null;//from  w  w w.  ja  v a2  s .  c  o  m
    ZipOutputStream zout = null;
    File inDir = null;
    try {
        inDir = new File(directoryName);
        if (!inDir.isDirectory()) {
            return;
        }
        fos = new FileOutputStream(new File(outFileName));
        zout = new ZipOutputStream(fos);
        File files[] = inDir.listFiles();
        for (File f : files) {
            writeToZip(f, f.getName(), zout);
        }
        zout.close();
        fos.close();
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            if (zout != null) {
                zout.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.cordys.coe.ac.emailio.archive.FileArchiver.java

/**
 * This method starts the actual archiving of the passed on context containers.
 *
 * @param   lccContainers  The containers to archive.
 * @param   spqmManager    The QueryManager to use.
 *
 * @throws  ArchiverException  In case of any exceptions.
 *
 * @see     com.cordys.coe.ac.emailio.archive.IArchiver#doArchive(java.util.List, com.cordys.coe.ac.emailio.objects.IStorageProviderQueryManager)
 *///from  w  w w  .j  av a2 s  .  c  o m
@Override
public void doArchive(List<ContextContainer> lccContainers, IStorageProviderQueryManager spqmManager)
        throws ArchiverException {
    File fArchive = getArchiveFolder();

    for (ContextContainer ccContainer : lccContainers) {
        int iWrapperXML = 0;
        ZipOutputStream zosZip = null;
        File fZipFile = null;
        List<EmailMessage> lEmails = null;

        try {
            lEmails = spqmManager.getEmailMessagesByContextID(ccContainer.getID());

            // Create the ZipFile
            fZipFile = new File(fArchive, ccContainer.getID().replaceAll("[^a-zA-Z0-9]", "") + ".zip");
            zosZip = new ZipOutputStream(new FileOutputStream(fZipFile, false));
            zosZip.setLevel(m_iZipLevel);

            // Now we have both the container and the emails. We will create an XML
            // to hold all data.
            int iObjectData = ccContainer._getObjectData();

            // Create the zip entry for it.
            ZipEntry zeContainer = new ZipEntry("container.xml");
            zosZip.putNextEntry(zeContainer);

            String sXML = Node.writeToString(iObjectData, true);
            zosZip.write(sXML.getBytes());
            zosZip.closeEntry();

            // Add the email messages to the zip file.
            int iCount = 0;

            for (EmailMessage emMessage : lEmails) {
                iObjectData = emMessage._getObjectData();

                ZipEntry zeEmail = new ZipEntry("email_" + iCount++ + ".xml");
                zosZip.putNextEntry(zeEmail);

                sXML = Node.writeToString(iObjectData, true);
                zosZip.write(sXML.getBytes());
                zosZip.closeEntry();
            }

            // Now all files are written into a single Zip file, so we can close it.
        } catch (Exception e) {
            throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ARCHIVING_CONTAINER_0,
                    ccContainer.getID());
        } finally {
            if (iWrapperXML != 0) {
                Node.delete(iWrapperXML);
            }

            if (zosZip != null) {
                try {
                    zosZip.close();
                } catch (IOException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Error closing zip file " + fZipFile.getAbsolutePath(), e);
                    }
                }
            }
        }

        // If we get here the zipfile was successfully created. So now we need to remove the
        // mails and the container from the current storage provider.
        try {
            spqmManager.removeContextContainer(ccContainer);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Archived the container with id " + ccContainer.getID());
            }
        } catch (StorageProviderException e) {
            throw new ArchiverException(e,
                    ArchiverExceptionMessages.ARE_ERROR_REMOVING_CONTEXT_CONTAINER_0_FROM_THE_STORAGE,
                    ccContainer.getID());
        }
    }

    // Now all containers have been archived, we will create a single zip file.
    try {
        File fFinalArchive = new File(fArchive.getParentFile(), fArchive.getName() + ".zip");

        if (LOG.isDebugEnabled()) {
            LOG.debug("Archiving folder " + fArchive.getCanonicalPath() + " into file "
                    + fFinalArchive.getCanonicalPath());
        }

        new ZipUtil().compress(fArchive, fFinalArchive.getAbsolutePath());
    } catch (Exception e) {
        throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ZIPPING_ALL_ARCHIVE_FILES);
    }
}

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

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().debug("Skipping step");
        return;/*from  w w w  .jav  a2  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:de.innovationgate.wga.model.WGADesignConfigurationModel.java

private ZipOutputStream createZIP(File zipFile, boolean obfuscate, String javaSourceFolder)
        throws FileNotFoundException, PersistentKeyException, GeneralSecurityException, IOException {
    if (!zipFile.exists()) {
        zipFile.createNewFile();//from  w  w w.j a v a  2  s  . c  o m
    }

    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
    zipOutputStream.setLevel(0);

    DirZipper zipper = new DirZipper();
    zipper.setInputStreamProvider(new PluginISProvider(_designDirectory, obfuscate));
    zipper.addFilePatternToIgnore("^\\..*$");

    // Zip all folders and files that belong into an exported plugin
    List<File> filesToZip = new ArrayList<File>();
    filesToZip.add(new File(_designDirectory, DesignDirectory.FOLDERNAME_TML));
    filesToZip.add(new File(_designDirectory, DesignDirectory.FOLDERNAME_SCRIPT));
    filesToZip.add(new File(_designDirectory, DesignDirectory.FOLDERNAME_FILES));
    filesToZip.add(new File(_designDirectory, DesignDirectory.SYNCINFO_FILE));
    filesToZip.add(new File(_designDirectory, DesignDirectory.DESIGN_DEFINITION_FILE));
    Iterator<File> files = filesToZip.iterator();
    while (files.hasNext()) {
        File file = (File) files.next();
        if (file.exists()) {
            if (file.isDirectory()) {
                zipper.zipDirectory(file, zipOutputStream, file.getName() + "/");
            } else {
                zipper.zipFile(file, zipOutputStream);
            }

        }
    }

    // If the design directory has a java classes folder we put those into a jar and zip them to "files/system"
    File javaClassesDir = new File(_designDirectory, DesignDirectory.FOLDERNAME_JAVA);
    if (javaClassesDir.exists() && javaClassesDir.isDirectory()) {
        TemporaryFile jar = new TemporaryFile("plugin-classes.jar", null, null);
        ZipOutputStream jarStream = new ZipOutputStream(new FileOutputStream(jar.getFile()));
        jarStream.setLevel(0);
        DirZipper jarZipper = new DirZipper();
        jarZipper.addFilePatternToIgnore("^\\..*$");
        jarZipper.zipDirectory(javaClassesDir, jarStream);

        jarStream.close();

        zipper.zipNormalFile(jar.getFile(), zipOutputStream, "files/system/");

        jar.delete();
    }

    // If we were given a java source folder we put its contents into plugin-sources.zip and put that into "files/system" (for OSS plugins)
    if (javaSourceFolder != null) {
        File javaSourceDir = new File(javaSourceFolder);
        TemporaryFile zip = new TemporaryFile("plugin-sources.zip", null, null);
        ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(zip.getFile()));
        zipStream.setLevel(0);
        DirZipper jarZipper = new DirZipper();
        jarZipper.addFilePatternToIgnore("^\\..*$");
        jarZipper.zipDirectory(javaSourceDir, zipStream);

        zipStream.close();

        zipper.zipNormalFile(zip.getFile(), zipOutputStream, "files/system/");

        zip.delete();
    }

    if (obfuscate) {
        ZipEntry anEntry = new ZipEntry(DesignDirectory.OBFUSCATE_FLAGFILE);
        zipOutputStream.putNextEntry(anEntry);
        zipOutputStream.write("Obfuscation flagfile".getBytes());
    }

    return zipOutputStream;
}

From source file:com.controlj.green.modstat.work.ModstatWork.java

@Override
public void run() {
    final ZipOutputStream zout;
    ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
    zout = new ZipOutputStream(out);

    try {//from w w  w.j  a v  a2  s .  c o  m

        connection.runReadAction(FieldAccessFactory.newFieldAccess(), new ReadAction() {

            public void execute(@NotNull SystemAccess access) throws Exception {
                Location root = access.getTree(SystemTree.Network).resolve(rootPath);

                Collection<ModuleStatus> aspects = root.find(ModuleStatus.class, Acceptors.acceptAll());

                synchronized (this) {
                    progressLimit = aspects.size();
                }

                for (ModuleStatus aspect : aspects) {
                    Location location = aspect.getLocation();
                    try {
                        if (!location.getAspect(Device.class).isOutOfService()) {
                            String path = getReferencePath(location);

                            //System.out.println("Gathering modstat from "+path);

                            ZipEntry entry = new ZipEntry(path + ".txt");
                            entry.setMethod(ZipEntry.DEFLATED);
                            zout.putNextEntry(entry);
                            IOUtils.copy(new StringReader(aspect.getReportText()), zout);
                            zout.closeEntry();

                            synchronized (this) {
                                progress++;
                                if (isInterrupted()) {
                                    error = new Exception("Gathering Modstats interrupted");
                                    return;
                                }
                            }
                        }
                    } catch (NoSuchAspectException e) { // skip and go to the next one
                    }
                }

            }
        });
    } catch (Exception e) {
        synchronized (this) {
            error = e;
        }
        return;
    } finally {
        try {
            zout.close();
        } catch (IOException e) {
        } // we tried our best
    }
    if (!hasError()) {
        cache = out.toByteArray();
    }
}

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

public void exportDesign(File file, Properties buildProperties)
        throws FileNotFoundException, PersistentKeyException, GeneralSecurityException, IOException {
    ZipOutputStream stream = createZIP(file, false, null);
    ZipEntry buildPropertiesEntry = new ZipEntry("files/system/build.properties");
    stream.putNextEntry(buildPropertiesEntry);
    ByteArrayOutputStream propertiesContent = new ByteArrayOutputStream();
    buildProperties.store(propertiesContent, null);
    stream.write(propertiesContent.toByteArray());
    stream.close();
}

From source file:net.solarnetwork.node.backup.FileSystemBackupService.java

@Override
public Backup performBackup(final Iterable<BackupResource> resources) {
    if (resources == null) {
        return null;
    }/*from  ww w.  j  a  v a 2s.c  o m*/
    final Iterator<BackupResource> itr = resources.iterator();
    if (!itr.hasNext()) {
        log.debug("No resources provided, nothing to backup");
        return null;
    }
    BackupStatus status = setStatusIf(RunningBackup, Configured);
    if (status != RunningBackup) {
        return null;
    }
    final Calendar now = new GregorianCalendar();
    now.set(Calendar.MILLISECOND, 0);
    final String archiveName = String.format(ARCHIVE_NAME_FORMAT, now);
    final File archiveFile = new File(backupDir, archiveName);
    final String archiveKey = getArchiveKey(archiveName);
    log.info("Starting backup to archive {}", archiveName);
    log.trace("Backup archive: {}", archiveFile.getAbsolutePath());
    Backup backup = null;
    ZipOutputStream zos = null;
    try {
        zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile)));
        while (itr.hasNext()) {
            BackupResource r = itr.next();
            log.debug("Backup up resource {} to archive {}", r.getBackupPath(), archiveName);
            zos.putNextEntry(new ZipEntry(r.getBackupPath()));
            FileCopyUtils.copy(r.getInputStream(), new FilterOutputStream(zos) {

                @Override
                public void close() throws IOException {
                    // FileCopyUtils closes the stream, which we don't want
                }

            });
        }
        zos.flush();
        zos.finish();
        log.info("Backup complete to archive {}", archiveName);
        backup = new SimpleBackup(now.getTime(), archiveKey, archiveFile.length(), true);

        // clean out older backups
        File[] backupFiles = getAvailableBackupFiles();
        if (backupFiles != null && backupFiles.length > additionalBackupCount + 1) {
            // delete older files
            for (int i = additionalBackupCount + 1; i < backupFiles.length; i++) {
                log.info("Deleting old backup archive {}", backupFiles[i].getName());
                if (!backupFiles[i].delete()) {
                    log.warn("Unable to delete backup archive {}", backupFiles[i].getAbsolutePath());
                }
            }
        }
    } catch (IOException e) {
        log.error("IO error creating backup: {}", e.getMessage());
        setStatus(Error);
    } catch (RuntimeException e) {
        log.error("Error creating backup: {}", e.getMessage());
        setStatus(Error);
    } finally {
        if (zos != null) {
            try {
                zos.close();
            } catch (IOException e) {
                // ignore this
            }
        }
        status = setStatusIf(Configured, RunningBackup);
        if (status != Configured) {
            // clean up if we encountered an error
            if (archiveFile.exists()) {
                archiveFile.delete();
            }
        }
    }
    return backup;
}

From source file:pl.betoncraft.betonquest.editor.model.PackageSet.java

/**
 * Saves the package to a .zip file.//from  w  w w  .  j  a v  a2 s .  c o m
 * 
 * @param zipFile
 */
public void saveToZip(File zip) {
    try {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zip));
        for (QuestPackage pack : packages) {
            String prefix = pack.getName().get().replace("-", File.separator) + File.separator;
            // save main.yml file
            ZipEntry main = new ZipEntry(prefix + "main.yml");
            out.putNextEntry(main);
            pack.printMainYAML(out);
            out.closeEntry();
            // save conversation files
            for (Conversation conv : pack.getConversations()) {
                ZipEntry conversation = new ZipEntry(
                        prefix + "conversations" + File.separator + conv.getId().get() + ".yml");
                out.putNextEntry(conversation);
                pack.printConversationYaml(out, conv);
                out.closeEntry();
            }
            // save events.yml file
            ZipEntry events = new ZipEntry(prefix + "events.yml");
            out.putNextEntry(events);
            pack.printEventsYaml(out);
            out.closeEntry();
            // save conditions.yml file
            ZipEntry conditions = new ZipEntry(prefix + "conditions.yml");
            out.putNextEntry(conditions);
            pack.printConditionsYaml(out);
            out.closeEntry();
            // save objectives.yml file
            ZipEntry objectives = new ZipEntry(prefix + "objectives.yml");
            out.putNextEntry(objectives);
            pack.printObjectivesYaml(out);
            out.closeEntry();
            // save items.yml file
            ZipEntry items = new ZipEntry(prefix + "items.yml");
            out.putNextEntry(items);
            pack.printItemsYaml(out);
            out.closeEntry();
            // save journal.yml file
            ZipEntry journal = new ZipEntry(prefix + "journal.yml");
            out.putNextEntry(journal);
            pack.printJournalYaml(out);
            out.closeEntry();
        }
        // done
        out.close();
    } catch (Exception e) {
        ExceptionController.display(e);
    }
}