Example usage for java.util.zip ZipOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

public static void editzip(InputStream stream, OutputStream outputStream, boolean close,
        EditArchiveCallback callback, String... matches) {
    ZipInputStream in = new ZipInputStream(stream);
    ZipOutputStream zout = new ZipOutputStream(outputStream);
    ZipEntry entry;/*from   w  ww . j  a v a 2s  .c o m*/
    try {
        Map<String, File> skipped = new HashMap<String, File>();
        matches = (String[]) ArrayUtils.add(matches, ".*");
        while ((entry = in.getNextEntry()) != null) {
            String name = entry.getName();
            if (!entry.isDirectory()) {
                if (name.contains("/") && !File.separator.equals("/"))
                    name = name.replaceAll("/", File.separator + File.separator);
                if (name.contains("\\") && !File.separator.equals("\\"))
                    name = name.replaceAll("\\\\", File.separator);

                String dir = name.replaceAll("^(.*?)(?:\\\\|/?)([~@\\$\\{\\}\\w\\-\\.\\+]+$)", "$1");
                String file = name.replaceAll("^(.*?)(?:\\\\|/?)([~@\\$\\{\\}\\w\\-\\.\\+]+$)", "$2");

                if (file.matches(matches[0])) {
                    zout.putNextEntry(new ZipEntry(name));
                    callback.edit(dir, file, in, zout);
                    zout.closeEntry();
                } else {
                    File path = FileUtils.getTempFile(SecurityHelper.generateRandomSequence(16));
                    OutputStream out = FileUtils.openOutputStream(path);
                    IOUtils.copy(in, out);
                    IOUtils.closeQuietly(out);
                    skipped.put(name, path);
                }
            }
        }

        for (int i = 1; i < matches.length; i++) {
            for (Iterator<Map.Entry<String, File>> iterator = skipped.entrySet().iterator(); iterator
                    .hasNext();) {
                Map.Entry<String, File> next = iterator.next();
                String name = next.getKey();
                File path = next.getValue();

                String dir = name.replaceAll("(.*?)(?:\\\\|/?)([~@\\$\\{\\}\\w\\-\\.\\+]+$)", "$1");
                String file = name.replaceAll("(.*?)(?:\\\\|/?)([~@\\$\\{\\}\\w\\-\\.\\+]+$)", "$2");

                if (file.matches(matches[i])) {
                    iterator.remove();
                    FileInputStream inputStream = FileUtils.openInputStream(path);
                    zout.putNextEntry(entry);
                    callback.edit(dir, file, inputStream, zout);
                    zout.closeEntry();
                    IOUtils.closeQuietly(inputStream);
                    FileUtils.forceDelete(path);
                }
            }
        }

        while (callback.add(zout)) {
            zout.closeEntry();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (close)
            IOUtils.closeQuietly(zout);
    }
}

From source file:com.googlecode.clearnlp.component.AbstractStatisticalComponent.java

protected void saveDefaultConfiguration(ZipOutputStream zout, String entryName) throws Exception {
    zout.putNextEntry(new ZipEntry(entryName));
    PrintStream fout = UTOutput.createPrintBufferedStream(zout);
    LOG.info("Saving configuration.\n");

    fout.println(s_models.length);//w ww. j  a v  a2s. com

    fout.flush();
    zout.closeEntry();
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java

public static MimeBodyPart zipAttachment(String zipFileName, Map mailOptions, File tempFolder) {
    logger.debug("IN");
    MimeBodyPart messageBodyPart = null;
    try {//from  w  w  w.  j  a  va  2  s .  c om

        String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : "";

        byte[] buffer = new byte[4096]; // Create a buffer for copying
        int bytesRead;

        // the zip
        String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipOutputStream out = new ZipOutputStream(bout);

        logger.debug("File zip to write: " + tempFolderPath + File.separator + "zippedFile.zip");

        //files to zip
        String[] entries = tempFolder.list();

        for (int i = 0; i < entries.length; i++) {
            //File f = new File(tempFolder, entries[i]);
            File f = new File(tempFolder + File.separator + entries[i]);
            if (f.isDirectory())
                continue;//Ignore directory
            logger.debug("insert file: " + f.getName());
            FileInputStream in = new FileInputStream(f); // Stream to read file
            ZipEntry entry = new ZipEntry(f.getName()); // Make a ZipEntry
            out.putNextEntry(entry); // Store entry
            while ((bytesRead = in.read(buffer)) != -1)
                out.write(buffer, 0, bytesRead);
            in.close();
        }
        out.close();

        messageBodyPart = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(zipFileName + nameSuffix + ".zip");

    } catch (Exception e) {
        logger.error("Error while creating the zip", e);
        return null;
    }

    logger.debug("OUT");

    return messageBodyPart;
}

From source file:be.fedict.eid.applet.service.signer.asic.ASiCSignatureOutputStream.java

@Override
public void close() throws IOException {
    super.close();

    byte[] signatureData = toByteArray();

    /*// w  w w .  j ava  2  s.c  om
     * Copy the original ZIP content.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile));
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) {
            ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
            zipOutputStream.putNextEntry(newZipEntry);
            LOG.debug("copying " + zipEntry.getName());
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();

    /*
     * Add the XML signature file to the ASiC package.
     */
    zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE);
    LOG.debug("writing " + zipEntry.getName());
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:com.joliciel.talismane.extensions.corpus.PosTaggerStatistics.java

@Override
public void onCompleteAnalysis() {
    try {//from   www.  j  av a 2  s  .co m
        if (writer != null) {
            PosTagSet posTagSet = talismaneSession.getPosTagSet();
            for (PosTag posTag : posTagSet.getTags()) {
                if (!posTagCounts.containsKey(posTag.getCode())) {
                    posTagCounts.put(posTag.getCode(), 0);
                }
            }

            double unknownLexiconPercent = 1;
            if (referenceWords != null) {
                int unknownLexiconCount = 0;
                for (String word : words) {
                    if (!referenceWords.contains(word))
                        unknownLexiconCount++;
                }
                unknownLexiconPercent = (double) unknownLexiconCount / (double) words.size();
            }
            double unknownLowercaseLexiconPercent = 1;
            if (referenceLowercaseWords != null) {
                int unknownLowercaseLexiconCount = 0;
                for (String lowercase : lowerCaseWords) {
                    if (!referenceLowercaseWords.contains(lowercase))
                        unknownLowercaseLexiconCount++;
                }
                unknownLowercaseLexiconPercent = (double) unknownLowercaseLexiconCount
                        / (double) lowerCaseWords.size();
            }

            writer.write(CSV.format("sentenceCount") + CSV.format(sentenceCount) + "\n");
            writer.write(CSV.format("sentenceLengthMean") + CSV.format(sentenceLengthStats.getMean()) + "\n");
            writer.write(CSV.format("sentenceLengthStdDev")
                    + CSV.format(sentenceLengthStats.getStandardDeviation()) + "\n");
            writer.write(CSV.format("lexiconSize") + CSV.format(words.size()) + "\n");
            writer.write(
                    CSV.format("lexiconUnknownInRefCorpus") + CSV.format(unknownLexiconPercent * 100.0) + "\n");
            writer.write(CSV.format("tokenCount") + CSV.format(tokenCount) + "\n");

            double unknownTokenPercent = ((double) unknownTokenCount / (double) tokenCount) * 100.0;
            writer.write(CSV.format("tokenUnknownInRefCorpus") + CSV.format(unknownTokenPercent) + "\n");

            double unknownInLexiconPercent = ((double) unknownInLexiconCount / (double) tokenCount) * 100.0;
            writer.write(CSV.format("tokenUnknownInRefLexicon") + CSV.format(unknownInLexiconPercent) + "\n");

            writer.write(CSV.format("lowercaseLexiconSize") + CSV.format(lowerCaseWords.size()) + "\n");
            writer.write(CSV.format("lowercaseLexiconUnknownInRefCorpus")
                    + CSV.format(unknownLowercaseLexiconPercent * 100.0) + "\n");
            writer.write(CSV.format("alphanumericCount") + CSV.format(alphanumericCount) + "\n");

            double unknownAlphanumericPercent = ((double) unknownAlphanumericCount / (double) alphanumericCount)
                    * 100.0;
            writer.write(CSV.format("alphaUnknownInRefCorpus") + CSV.format(unknownAlphanumericPercent) + "\n");

            double unknownAlphaInLexiconPercent = ((double) unknownAlphaInLexiconCount
                    / (double) alphanumericCount) * 100.0;
            writer.write(
                    CSV.format("alphaUnknownInRefLexicon") + CSV.format(unknownAlphaInLexiconPercent) + "\n");

            writer.write(CSV.format("openClassCount") + CSV.format(openClassCount) + "\n");

            double openClassUnknownPercent = ((double) openClassUnknownInRefCorpus / (double) openClassCount)
                    * 100.0;
            writer.write(
                    CSV.format("openClassUnknownInRefCorpus") + CSV.format(openClassUnknownPercent) + "\n");

            double openClassUnknownInLexiconPercent = ((double) openClassUnknownInLexicon
                    / (double) openClassCount) * 100.0;
            writer.write(CSV.format("openClassUnknownInRefLexicon")
                    + CSV.format(openClassUnknownInLexiconPercent) + "\n");

            writer.write(CSV.format("closedClassCount") + CSV.format(closedClassCount) + "\n");

            double closedClassUnknownPercent = ((double) closedClassUnknownInRefCorpus
                    / (double) closedClassCount) * 100.0;
            writer.write(
                    CSV.format("closedClassUnknownInRefCorpus") + CSV.format(closedClassUnknownPercent) + "\n");

            double closedClassUnknownInLexiconPercent = ((double) closedClassUnknownInLexicon
                    / (double) closedClassCount) * 100.0;
            writer.write(CSV.format("closedClassUnknownInRefLexicon")
                    + CSV.format(closedClassUnknownInLexiconPercent) + "\n");

            for (String posTag : posTagCounts.keySet()) {
                int count = posTagCounts.get(posTag);
                writer.write(CSV.format(posTag) + CSV.format(count)
                        + CSV.format(((double) count / (double) tokenCount) * 100.0) + "\n");
            }

            writer.flush();
            writer.close();
        }

        if (this.serializationFile != null) {
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(serializationFile, false));
            zos.putNextEntry(new ZipEntry("Contents.obj"));
            ObjectOutputStream oos = new ObjectOutputStream(zos);
            try {
                oos.writeObject(this);
            } finally {
                oos.flush();
            }
            zos.flush();
            zos.close();
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }

}

From source file:be.neutrinet.ispng.vpn.api.VPNClientConfig.java

@Post
public Representation getConfig(Map<String, String> data) {
    try {/* w  ww .j  a  va 2s  .co  m*/
        if (!getRequestAttributes().containsKey("client"))
            return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);

        Client client = Clients.dao.queryForId(getAttribute("client"));
        if (!Policy.get().canAccess(getSessionToken().get().getUser(), client)) {
            return clientError("FORBIDDEN", Status.CLIENT_ERROR_BAD_REQUEST);
        }

        ArrayList<String> config = new ArrayList<>();
        config.addAll(Arrays.asList(DEFAULTS));

        // create zip
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(baos);

        List<Certificate> userCert = Certificates.dao.queryForEq("client_id", client.id).stream()
                .filter(Certificate::valid).collect(Collectors.toList());

        if (!userCert.isEmpty()) {
            byte[] raw = userCert.get(0).getRaw();
            zip.putNextEntry(new ZipEntry("client.crt"));
            zip.write(raw);
            zip.putNextEntry(new ZipEntry("README"));
            zip.write(("!! You are using your own keypair. Please make sure to adjust the "
                    + "path to your private key in the config file or move the private key"
                    + " here and name it client.key").getBytes());
            config.add("cert client.crt");
            config.add("key client.key");
        } else if (client.user.certId != null && !client.user.certId.isEmpty()) {
            Representation res = addPKCS11config(data.get("platform").toLowerCase(), config, client.user);
            if (res != null)
                return res;
        }

        if (client.user.certId == null || client.user.certId.isEmpty()) {
            zip.putNextEntry(new ZipEntry("NO_KEYPAIR_DEFINED"));
            zip.write("Invalid state, no keypair has been defined.".getBytes());
        }

        return finalizeZip(config, zip, baos);
    } catch (Exception ex) {
        Logger.getLogger(getClass()).error("Failed to generate config file archive", ex);
    }

    return DEFAULT_ERROR;
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ?/*from   ww w .  ja va2  s .com*/
 * 
 * @param files 
 * @param out ?
 * @throws IOException
 * @throws Exception
 */
public static void zipDownLoad(Map<File, String> downQuene, HttpServletResponse response) throws IOException {

    ServletOutputStream out = response.getOutputStream();
    ZipOutputStream zipout = new ZipOutputStream(out);
    ZipEntry entry = null;
    zipout.setLevel(1);
    // zipout.setEncoding("GBK");
    if (downQuene != null && downQuene.size() > 0) {
        for (Entry<File, String> fileInfo : downQuene.entrySet()) {
            File file = fileInfo.getKey();
            try {
                String filename = new String(fileInfo.getValue().getBytes(), "GBK");
                entry = new ZipEntry(filename);
                entry.setSize(file.length());
                zipout.putNextEntry(entry);
            } catch (IOException e) {
                // Logger.getLogger(FileUtil.class).warn(":", e);
            }
            BufferedInputStream fr = new BufferedInputStream(new FileInputStream(fileInfo.getKey()));
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fr.read(buffer)) != -1)
                zipout.write(buffer, 0, len);
            fr.close();
        }
    }

    zipout.finish();
    zipout.flush();
    // out.flush();
}

From source file:com.twinsoft.convertigo.engine.util.ZipUtils.java

private static int putEntries(ZipOutputStream zos, String sDir, String sRelativeDir,
        final List<File> excludedFiles) throws Exception {
    Engine.logEngine.trace("==========================================================");
    Engine.logEngine.trace("sDir=" + sDir);
    Engine.logEngine.trace("sRelativeDir=" + sRelativeDir);
    Engine.logEngine.trace("excludedFiles=" + excludedFiles);

    File dir = new File(sDir);
    String[] files = dir.list(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            File file = new File(dir, name);
            return (!excludedFiles.contains(file));
        }/*from   w ww  . j  a v a  2s.  c  o  m*/
    });

    Engine.logEngine.trace("files=" + files);

    int nbe = 0;
    for (String file : files) {
        String sDirEntry = sDir + "/" + file;
        String sRelativeDirEntry = sRelativeDir != null ? (sRelativeDir + "/" + file) : file;

        File f = new File(sDirEntry);
        if (!f.isDirectory()) {
            Engine.logEngine.trace("+ " + sDirEntry);
            InputStream fi = new FileInputStream(f);

            try {
                ZipEntry entry = new ZipEntry(sRelativeDirEntry);
                entry.setTime(f.lastModified());
                zos.putNextEntry(entry);
                IOUtils.copy(fi, zos);
                nbe++;
            } finally {
                fi.close();
            }
        } else {
            nbe += putEntries(zos, sDirEntry, sRelativeDirEntry, excludedFiles);
        }
    }
    return nbe;
}

From source file:com.hazelcast.stabilizer.Utils.java

public static byte[] zip(List<File> roots) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Deque<File> queue = new LinkedList<File>();
    ZipOutputStream zout = new ZipOutputStream(out);

    Set<String> names = new HashSet<String>();

    try {// www  .j ava  2  s. c om
        for (File root : roots) {
            URI base = root.isDirectory() ? root.toURI() : root.getParentFile().toURI();
            queue.push(root);
            while (!queue.isEmpty()) {
                File file = queue.pop();
                if (file.getName().equals(".DS_Store")) {
                    continue;
                }

                //                    log.finest("Zipping: " + file.getAbsolutePath());

                if (file.isDirectory()) {
                    String name = base.relativize(file.toURI()).getPath();
                    name = name.endsWith("/") ? name : name + "/";

                    if (names.add(name)) {
                        zout.putNextEntry(new ZipEntry(name));
                    }

                    for (File kid : file.listFiles()) {
                        queue.push(kid);
                    }
                } else {
                    String name = base.relativize(file.toURI()).getPath();
                    zout.putNextEntry(new ZipEntry(name));
                    copy(file, zout);
                    zout.closeEntry();
                }
            }
        }
    } finally {
        zout.close();
    }

    return out.toByteArray();
}

From source file:de.brendamour.jpasskit.signing.PKInMemorySigningUtil.java

private byte[] createZippedPassAndReturnAsByteArray(final Map<String, ByteBuffer> files)
        throws PKSigningException {
    ByteArrayOutputStream byteArrayOutputStreamForZippedPass = null;
    ZipOutputStream zipOutputStream = null;
    byteArrayOutputStreamForZippedPass = new ByteArrayOutputStream();
    zipOutputStream = new ZipOutputStream(byteArrayOutputStreamForZippedPass);
    for (Entry<String, ByteBuffer> passResourceFile : files.entrySet()) {
        ZipEntry entry = new ZipEntry(getRelativePathOfZipEntry(passResourceFile.getKey(), ""));
        try {// www.  j  av a 2s  .  co  m
            zipOutputStream.putNextEntry(entry);
            IOUtils.copy(new ByteArrayInputStream(passResourceFile.getValue().array()), zipOutputStream);
        } catch (IOException e) {
            IOUtils.closeQuietly(zipOutputStream);
            throw new PKSigningException("Error when zipping file", e);
        }
    }
    IOUtils.closeQuietly(zipOutputStream);
    return byteArrayOutputStreamForZippedPass.toByteArray();
}