Example usage for java.util.zip ZipOutputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

protected void exportArticles(ZipOutputStream zos, String path) throws WPBIOException {
    try {// www . j  a v  a 2 s . c  o m
        List<WPBArticle> articles = dataStorage.getAllRecords(WPBArticle.class);
        for (WPBArticle article : articles) {
            String articleXmlPath = path + article.getExternalKey() + "/" + "metadata.xml";
            Map<String, Object> map = new HashMap<String, Object>();
            exporter.export(article, map);
            ZipEntry metadataZe = new ZipEntry(articleXmlPath);
            zos.putNextEntry(metadataZe);
            exportToXMLFormat(map, zos);
            zos.closeEntry();
            String articleSourcePath = path + article.getExternalKey() + "/" + "articleSource.txt";
            String pageSource = article.getHtmlSource() != null ? article.getHtmlSource() : "";
            ZipEntry pageSourceZe = new ZipEntry(articleSourcePath);
            zos.putNextEntry(pageSourceZe);
            zos.write(pageSource.getBytes("UTF-8"));
            zos.closeEntry();
        }
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("Cannot export articles to Zip", e);
    }
}

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

protected void exportPageModules(ZipOutputStream zos, String path) throws WPBIOException {
    try {/*from w w w. jav  a 2 s .  co  m*/
        List<WPBPageModule> modules = dataStorage.getAllRecords(WPBPageModule.class);
        for (WPBPageModule module : modules) {
            String moduleXmlPath = path + module.getExternalKey() + "/" + "metadata.xml";
            Map<String, Object> map = new HashMap<String, Object>();
            exporter.export(module, map);
            ZipEntry metadataZe = new ZipEntry(moduleXmlPath);
            zos.putNextEntry(metadataZe);
            exportToXMLFormat(map, zos);
            zos.closeEntry();
            String moduleSourcePath = path + module.getExternalKey() + "/" + "moduleSource.txt";
            String moduleSource = module.getHtmlSource() != null ? module.getHtmlSource() : "";
            ZipEntry pageSourceZe = new ZipEntry(moduleSourcePath);
            zos.putNextEntry(pageSourceZe);
            zos.write(moduleSource.getBytes("UTF-8"));
            zos.closeEntry();
        }
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("Cannot export site web page modules to Zip", e);
    }
}

From source file:org.bdval.BDVModel.java

/**
 * Store the BDVModel properties to the specified output stream.
 *
 * @param stream         The stream to store the properties to
 * @param options        The options associated with this model
 * @param task//from  w w w.j  a va2 s. c o  m
 * @param splitPlan      The split plan assoicated with this model
 * @param writeModelMode
 * @throws IOException if there is a problem writing to the stream
 */
protected void saveProperties(final OutputStream stream, final DAVOptions options,
        final ClassificationTask task, final SplitPlan splitPlan, final WriteModel writeModelMode)
        throws IOException {
    final Properties modelProperties = new Properties();
    modelProperties.setDelimiterParsingDisabled(true);
    modelProperties.addProperty("trained.from.dataset", task.getExperimentDataFilename());
    modelProperties.addProperty("training.class0.label", task.getFirstConditionName());
    modelProperties.addProperty("training.class0.encoding", -1);
    modelProperties.addProperty("training.class1.label", task.getSecondConditionName());
    modelProperties.addProperty("training.class1.encoding", +1);
    modelProperties.addProperty("training.classifier.classname",
            (isConsensusModel() ? "< meaningless for consensus-of-models >"
                    : helper.classifier.getClass().getCanonicalName()));
    modelProperties.addProperty("training.classifier.parameters", options.classifierParametersAsString());
    modelProperties.addProperty("scaling.use.percentiles", options.percentileScaling);
    modelProperties.addProperty("scaling.scaler.classname", options.scalerClassName);
    modelProperties.addProperty("scaling.enabled", options.scaleFeatures);
    modelProperties.addProperty("feature-normalization.enabled", options.normalizeFeatures);
    if (splitPlan != null) {
        modelProperties.addProperty("trained.from.split.split-id", writeModelMode.getSplitId());
        modelProperties.addProperty("trained.from.split-type", writeModelMode.getSplitType());
        modelProperties.addProperty("trained.from.split-plan", writeModelMode.getSplitPlanFilename());
    }

    modelProperties.addProperty("scaling.implementation.classname", options.scalerClass.getCanonicalName());
    addProperties(modelProperties);

    modelProperties.addProperty("pathway.aggregation.method", options.pathwayAggregtionMethod);
    modelProperties.addProperty("pathway.option.pathways", options.pathwaysInfoFilename);
    modelProperties.addProperty("pathway.option.gene-to-probe", options.geneToProbeFilename);

    try {
        if (zipModel) {
            final ZipOutputStream zipStream = (ZipOutputStream) stream;
            zipStream.putNextEntry(new ZipEntry(FilenameUtils.getName(modelPropertiesFilename)));
            modelProperties.save(zipStream);
            zipStream.closeEntry();
        } else {
            modelProperties.save(stream);
        }
    } catch (ConfigurationException e) {
        throw new IOException("Cannot write model properties.", e);
    }
}

From source file:org.apache.sling.osgi.obr.OSGiBundleRepositoryServlet.java

private void dumpRepository(String[] bundleNames, HttpServletResponse resp) throws IOException {

    Set selectedBundles = this.getSelectedBundles(bundleNames);

    resp.setContentType("application/zip");
    ZipOutputStream jos = null;
    try {/*w  ww.  ja va  2 s.c  o  m*/
        jos = new ZipOutputStream(resp.getOutputStream());

        // spool the repository.xml
        ZipEntry entry = new ZipEntry("repository.xml");
        jos.putNextEntry(entry);
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(jos, "UTF-8"));
        this.printRepositoryXML(pw, "", selectedBundles);
        pw.flush();
        jos.closeEntry();

        for (Iterator ri = this.repository.getResourcesById(); ri.hasNext();) {
            Resource res = (Resource) ri.next();

            // spool the resource out if selected or global dump
            String resourceName = res.getResourceName();
            if (selectedBundles == null || selectedBundles.contains(resourceName)) {
                entry = new ZipEntry(resourceName);
                jos.putNextEntry(entry);
                res.spool(jos);
                jos.closeEntry();
            }
        }

    } finally {
        IOUtils.closeQuietly(jos);
    }
}

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

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

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

        outputFile.closeEntry();
    }
}

From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

private void writeZipEntry(String prefix, ZipOutputStream out, File file)
        throws IOException, FileNotFoundException {
    ZipEntry mySkinFile = new ZipEntry(prefix + file.getName());
    mySkinFile.setSize(file.length());//from w w  w  . j  av  a2s. c o  m
    mySkinFile.setTime(file.lastModified());
    out.putNextEntry(mySkinFile);

    byte[] buf = new byte[1024];
    InputStream in = new FileInputStream(file);
    try {
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    } finally {
        in.close();
    }
    // Complete the entry
    out.closeEntry();
}

From source file:com.clustercontrol.collect.util.ZipCompresser.java

/**
 * ?????1????/*from w w  w .  j  a  va2s .co  m*/
 * 
 * @param inputFileNameList ??
 * @param outputFileName ?
 * 
 * @return ???
 */
protected static synchronized void archive(ArrayList<String> inputFileNameList, String outputFileName)
        throws HinemosUnknown {
    m_log.debug("archive() output file = " + outputFileName);

    byte[] buf = new byte[128];
    BufferedInputStream in = null;
    ZipEntry entry = null;
    ZipOutputStream out = null;

    // ?
    if (outputFileName == null || "".equals(outputFileName)) {
        HinemosUnknown e = new HinemosUnknown("archive output fileName is null ");
        m_log.info("archive() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    }
    File zipFile = new File(outputFileName);
    if (zipFile.exists()) {
        if (zipFile.isFile() && zipFile.canWrite()) {
            m_log.debug("archive() output file = " + outputFileName
                    + " is exists & file & writable. initialize file(delete)");
            if (!zipFile.delete())
                m_log.debug("Fail to delete " + zipFile.getAbsolutePath());
        } else {
            HinemosUnknown e = new HinemosUnknown("archive output fileName is directory or not writable ");
            m_log.info("archive() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
            throw e;
        }
    }

    // ?
    try {
        // ????
        out = new ZipOutputStream(new FileOutputStream(outputFileName));

        for (String inputFileName : inputFileNameList) {
            m_log.debug("archive() input file name = " + inputFileName);

            // ????
            in = new BufferedInputStream(new FileInputStream(inputFileName));

            // ??
            String fileName = (new File(inputFileName)).getName();
            m_log.debug("archive() entry file name = " + fileName);
            entry = new ZipEntry(fileName);

            out.putNextEntry(entry);
            // ????
            int size;
            while ((size = in.read(buf, 0, buf.length)) != -1) {
                out.write(buf, 0, size);
            }
            // ??
            out.closeEntry();
            in.close();
        }
        // ? out.flush();
        out.close();

    } catch (IOException e) {
        m_log.warn("archive() archive error : " + outputFileName + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        throw new HinemosUnknown("archive error " + outputFileName, e);

    } finally {

        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.veniosg.dir.mvvm.model.storage.operation.CompressOperation.java

/**
 * Recursively compress a File.//from   www.java 2  s.  co  m
 *
 * @return How many files where compressed.
 */
private int compressCore(int notId, ZipOutputStream zipStream, File toCompress, String internalPath,
        int filesCompressed, final int fileCount, File zipFile) throws IOException {
    if (internalPath == null)
        internalPath = "";

    showCompressProgressNotification(filesCompressed, fileCount, notId, zipFile, toCompress, context);
    if (toCompress.isFile()) {
        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        FileInputStream in = new FileInputStream(toCompress);

        // Create internal zip file entry.
        ZipEntry entry;
        if (internalPath.length() > 0) {
            entry = new ZipEntry(internalPath + "/" + toCompress.getName());
        } else {
            entry = new ZipEntry(toCompress.getName());
        }
        entry.setTime(toCompress.lastModified());
        zipStream.putNextEntry(entry);

        // Compress
        while ((len = in.read(buf)) > 0) {
            zipStream.write(buf, 0, len);
        }

        filesCompressed++;
        zipStream.closeEntry();
        in.close();
    } else {
        if (toCompress.list().length == 0) {
            zipStream.putNextEntry(new ZipEntry(internalPath + "/" + toCompress.getName() + "/"));
            zipStream.closeEntry();
        } else {
            for (File child : toCompress.listFiles()) {
                filesCompressed = compressCore(notId, zipStream, child,
                        internalPath + "/" + toCompress.getName(), filesCompressed, fileCount, zipFile);
            }
        }
    }

    return filesCompressed;
}

From source file:com.mweagle.tereus.commands.evaluation.common.LambdaUtils.java

protected void createStableZip(ZipOutputStream zipOS, Path parentDirectory, Path archiveRoot, MessageDigest md)
        throws IOException {
    // Sort & zip files
    final List<Path> childDirectories = new ArrayList<>();
    final List<Path> childFiles = new ArrayList<>();
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(parentDirectory);
    for (Path eachChild : dirStream) {
        if (Files.isDirectory(eachChild)) {
            childDirectories.add(eachChild);
        } else {//from   ww  w.  j  a v a 2 s . c  o m
            childFiles.add(eachChild);
        }
    }
    final int archiveRootLength = archiveRoot.toAbsolutePath().toString().length() + 1;
    childFiles.stream().sorted().forEach(eachPath -> {
        final String zeName = eachPath.toAbsolutePath().toString().substring(archiveRootLength);
        try {
            final ZipEntry ze = new ZipEntry(zeName);
            zipOS.putNextEntry(ze);
            Files.copy(eachPath, zipOS);
            md.update(Files.readAllBytes(eachPath));
            zipOS.closeEntry();
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    });

    childDirectories.stream().sorted().forEach(eachPath -> {
        try {
            createStableZip(zipOS, eachPath, archiveRoot, md);
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    });
}

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)
 */// ww w.j  a v a 2 s  .co 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);
    }
}