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:io.lightlink.excel.StreamingExcelTransformer.java

public void doExport(InputStream template, OutputStream out, ExcelStreamVisitor visitor) throws IOException {
    try {/*from   www .jav a 2  s  .  c  o  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);
    }
}

From source file:be.fedict.eid.applet.service.signer.odf.AbstractODFSignatureService.java

private void outputSignedOpenDocument(byte[] signatureData) throws IOException {
    LOG.debug("output signed open document");
    OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream();
    if (null == signedOdfOutputStream) {
        throw new NullPointerException("signedOpenDocumentOutputStream is null");
    }//from   www .j a v a 2s. c o  m
    /*
     * Copy the original ODF content to the signed ODF package.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream());
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();
    /*
     * Add the ODF XML signature file to the signed ODF package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:ch.randelshofer.cubetwister.PreferencesTemplatesPanel.java

private void exportInternalTemplate(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportInternalTemplate
    if (exportFileChooser == null) {
        exportFileChooser = new JFileChooser();
        exportFileChooser.setFileFilter(new ExtensionFileFilter("zip", "Zip Archive"));
        exportFileChooser.setSelectedFile(
                new File(userPrefs.get("cubetwister.exportedHTMLTemplate", "CubeTwister HTML-Template.zip")));
        exportFileChooser.setApproveButtonText(labels.getString("filechooser.export"));
    }/*ww w  .  ja va  2  s  .  co  m*/
    if (JFileChooser.APPROVE_OPTION == exportFileChooser.showSaveDialog(this)) {
        userPrefs.put("cubetwister.exportedHTMLTemplate", exportFileChooser.getSelectedFile().getPath());
        final File target = exportFileChooser.getSelectedFile();
        new BackgroundTask() {

            @Override
            public void construct() throws IOException {
                if (!target.getParentFile().exists()) {
                    target.getParentFile().mkdirs();
                }
                InputStream in = null;
                OutputStream out = null;
                try {
                    in = getClass().getResourceAsStream("/htmltemplates.tar.bz");
                    out = new FileOutputStream(target);
                    exportTarBZasZip(in, out);
                } finally {
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                    }
                }
            }

            private void exportTarBZasZip(InputStream in, OutputStream out) throws IOException {
                ZipOutputStream zout = new ZipOutputStream(out);
                TarInputStream tin = new TarInputStream(new BZip2CompressorInputStream(in));

                for (TarArchiveEntry inEntry = tin.getNextEntry(); inEntry != null;) {
                    ZipEntry outEntry = new ZipEntry(inEntry.getName());
                    zout.putNextEntry(outEntry);
                    if (!inEntry.isDirectory()) {
                        Files.copyStream(tin, zout);
                    }
                    zout.closeEntry();
                }
                zout.finish();
            }
        }.start();
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.util.ArchiveCompressorZipImpl.java

/**
 * Compress the given files into an archive with the given name, plus the file extension.  Put the compressed
 * archive into the given directory./*from  ww w .j  av  a  2  s.  c  om*/
 *
 * @param files                the files to include in the archive
 * @param archiveName          the name of the archive, minus extension
 * @param destinationDirectory the location to put the new compressed archive
 * @param compress              flag to compress the archive
 * @return the File representing the created compressed archive
 * @throws IOException if it needs to
 */
public File createArchive(final List<File> files, final String archiveName, final File destinationDirectory,
        final Boolean compress) throws IOException {
    final File archiveFile = new File(destinationDirectory, archiveName + ZIP_EXTENSION);

    ZipOutputStream out = null;
    FileInputStream in = null;

    try {
        //noinspection IOResourceOpenedButNotSafelyClosed
        out = new ZipOutputStream(new FileOutputStream(archiveFile));
        final byte[] buf = new byte[1024];
        for (final File file : files) {
            try {
                //noinspection IOResourceOpenedButNotSafelyClosed
                in = new FileInputStream(file);
                out.putNextEntry(new ZipEntry(archiveName + File.separator + file.getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } finally {
        IOUtils.closeQuietly(out);
    }
    return archiveFile;
}

From source file:jeffaschenk.tomcat.instance.generator.builders.TomcatInstanceBuilderHelper.java

/**
 * Zip File into Archive/*  w w w .  j  a v  a  2s  . c o m*/
 *
 * @param GENERATION_LOGGER Reference
 * @param zipFilePath       Zip file Destination.
 * @param fileFolder        Folder to be zipped Up ...
 * @throws IOException
 */
protected static boolean zipFile(GenerationLogger GENERATION_LOGGER, String zipFilePath, String fileFolder)
        throws IOException {
    /**
     * First get All Nodes with Folder
     */
    List<String> fileList = new ArrayList<>();
    generateFileListForCompression(new File(fileFolder), fileList);
    File sourceFolder = new File(fileFolder);
    byte[] buffer = new byte[8192];
    try {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);

        GENERATION_LOGGER.info("Compressing Instance Generation to Zip: " + zipFilePath);
        /**
         * Loop Over Files
         */
        for (String filename : fileList) {
            String zipEntryName = filename.substring(sourceFolder.getParent().length() + 1, filename.length());
            ZipEntry ze = new ZipEntry(zipEntryName);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(filename);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
            GENERATION_LOGGER.debug("File Added to Archive: " + zipEntryName);
        }
        /**
         * Close
         */
        zos.closeEntry();
        zos.close();
        return true;
    } catch (IOException ex) {
        GENERATION_LOGGER.error(ex.getMessage());
        ex.printStackTrace();
        return false;
    }
}

From source file:com.mgmtp.jfunk.common.util.ExtendedFile.java

private void zip(String prefix, final File file, final ZipOutputStream zipOut) throws IOException {
    if (file.isDirectory()) {
        prefix = prefix + file.getName() + '/';
        for (File child : file.listFiles()) {
            zip(prefix, child, zipOut);// www .j av a2 s.  c  o  m
        }
    } else {
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            zipOut.putNextEntry(new ZipEntry(prefix + file.getName()));
            IOUtils.copy(in, zipOut);
        } finally {
            IOUtils.closeQuietly(in);
            zipOut.flush();
            zipOut.closeEntry();
        }
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.AsicContainerClientRequestProcessor.java

private void writeContainers(List<MessageRecord> requests, String queryId, AsicContainerNameGenerator nameGen,
        ZipOutputStream zos, String type) throws Exception {

    for (MessageRecord record : requests) {
        String filename = nameGen.getArchiveFilename(queryId, type);
        zos.putNextEntry(new ZipEntry(filename));
        zos.write(record.toAsicContainer().getBytes());
        zos.closeEntry();/*from   ww  w  .  j av a  2 s.co m*/
    }
}

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

@Override
public void onCompleteParse() {
    try {/*from   w  w  w . ja  v a2s.co m*/
        if (writer != null) {
            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("tokenLexiconSize") + CSV.format(words.size()) + "\n");
            writer.write(CSV.format("tokenLexiconUnknown") + 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("tokenUnknown") + CSV.format(unknownTokenPercent) + "\n");

            writer.write(CSV.format("lowercaseLexiconSize") + CSV.format(lowerCaseWords.size()) + "\n");
            writer.write(CSV.format("lowercaseLexiconUnknown")
                    + 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("alphanumericUnknown") + CSV.format(unknownAlphanumericPercent) + "\n");

            writer.write(CSV.format("syntaxDepthMean") + CSV.format(syntaxDepthStats.getMean()) + "\n");
            writer.write(CSV.format("syntaxDepthStdDev") + CSV.format(syntaxDepthStats.getStandardDeviation())
                    + "\n");
            writer.write(CSV.format("maxSyntaxDepthMean") + CSV.format(maxSyntaxDepthStats.getMean()) + "\n");
            writer.write(CSV.format("maxSyntaxDepthStdDev")
                    + CSV.format(maxSyntaxDepthStats.getStandardDeviation()) + "\n");
            writer.write(
                    CSV.format("sentAvgSyntaxDepthMean") + CSV.format(avgSyntaxDepthStats.getMean()) + "\n");
            writer.write(CSV.format("sentAvgSyntaxDepthStdDev")
                    + CSV.format(avgSyntaxDepthStats.getStandardDeviation()) + "\n");
            writer.write(CSV.format("syntaxDistanceMean") + CSV.format(syntaxDistanceStats.getMean()) + "\n");
            writer.write(CSV.format("syntaxDistanceStdDev")
                    + CSV.format(syntaxDistanceStats.getStandardDeviation()) + "\n");

            double nonProjectivePercent = ((double) nonProjectiveCount / (double) totalDepCount) * 100.0;
            writer.write(CSV.format("nonProjectiveCount") + CSV.format(nonProjectiveCount) + "\n");
            writer.write(CSV.format("nonProjectivePercent") + CSV.format(nonProjectivePercent) + "\n");
            writer.write(CSV.format("PosTagCounts") + "\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.write(CSV.format("DepLabelCounts") + "\n");
            for (String depLabel : depLabelCounts.keySet()) {
                int count = depLabelCounts.get(depLabel);
                writer.write(CSV.format(depLabel) + CSV.format(count)
                        + CSV.format(((double) count / (double) totalDepCount) * 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:com.jd.survey.web.reports.ReportController.java

/**
 * Exports survey data to a comma delimited values file
 * @param surveyDefinitionId//  ww  w .  ja va  2  s  .  com
 * @param principal
 * @param response
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "csv", produces = "text/html")
public void surveyCSVExport(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {

        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            response.sendRedirect("../accessDenied");
            //throw new AccessDeniedException("Unauthorized access attempt");
        }

        String columnName;
        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        List<Map<String, Object>> surveys = reportDAO.getSurveyData(surveyDefinitionId);

        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append(
                "\"id\",\"Survey Name\",\"User Login\",\"Submission Date\",\"Creation Date\",\"Last Update Date\",");
        for (SurveyDefinitionPage page : surveyDefinition.getPages()) {
            for (Question question : page.getQuestions()) {
                if (question.getType().getIsMatrix()) {
                    for (QuestionRowLabel questionRowLabel : question.getRowLabels()) {
                        for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) {
                            stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "r"
                                    + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder()
                                    + "\",");
                        }
                    }
                    continue;
                }

                if (question.getType().getIsMultipleValue()) {
                    for (QuestionOption questionOption : question.getOptions()) {
                        stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "o"
                                + questionOption.getOrder() + "\",");

                    }
                    continue;
                }
                stringBuilder.append("\"p" + page.getOrder() + "q" + question.getOrder() + "\",");
            }
        }

        stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma
        stringBuilder.append("\n");

        for (Map<String, Object> record : surveys) {
            stringBuilder.append(record.get("survey_id") == null ? ""
                    : "\"" + record.get("survey_id").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("type_name") == null ? ""
                    : "\"" + record.get("type_name").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("login") == null ? ""
                    : "\"" + record.get("login").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("submission_date") == null ? ""
                    : "\"" + record.get("creation_date").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("creation_date") == null ? ""
                    : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("last_update_date") == null ? ""
                    : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\",");

            for (SurveyDefinitionPage page : surveyDefinition.getPages()) {
                for (Question question : page.getQuestions()) {
                    if (question.getType().getIsMatrix()) {
                        for (QuestionRowLabel questionRowLabel : question.getRowLabels()) {
                            for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) {
                                columnName = "p" + page.getOrder() + "q" + question.getOrder() + "r"
                                        + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder();
                                stringBuilder.append(record.get(columnName) == null ? ","
                                        : "\"" + record.get(columnName).toString().replace("\"", "\"\"")
                                                + "\",");
                            }
                        }
                        continue;
                    }
                    if (question.getType().getIsMultipleValue()) {
                        for (QuestionOption questionOption : question.getOptions()) {
                            columnName = "p" + page.getOrder() + "q" + question.getOrder() + "o"
                                    + questionOption.getOrder();
                            stringBuilder.append(record.get(columnName) == null ? ","
                                    : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\",");
                        }
                        continue;
                    }
                    columnName = "p" + page.getOrder() + "q" + question.getOrder();
                    stringBuilder.append(record.get(columnName) == null ? ","
                            : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\",");

                }
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma
            stringBuilder.append("\n");
        }

        //Zip file manipulations Code
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipEntry zipentry;
        ZipOutputStream zipfile = new ZipOutputStream(bos);
        zipentry = new ZipEntry("survey" + surveyDefinition.getId() + ".csv");
        zipfile.putNextEntry(zipentry);
        zipfile.write(stringBuilder.toString().getBytes("UTF-8"));
        zipfile.close();

        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=survey" + surveyDefinition.getId() + ".zip");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.write(bos.toByteArray());
        servletOutputStream.flush();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:com.bibisco.manager.ProjectManager.java

public static void zipIt(String zipFile) {

    mLog.debug("Start zipIt(String)");

    ContextManager lContextManager = ContextManager.getInstance();

    String lStrDBDirectoryPath = lContextManager.getDbDirectoryPath();
    String lStrDbProjectDirectory = getDBProjectDirectory(lContextManager.getIdProject());
    List<String> lFileList = getDirectoryFileList(new File(lStrDbProjectDirectory));

    try {//from ww w . jav  a 2 s  .  c o m
        File lFile = new File(zipFile);

        lFile.createNewFile();
        FileOutputStream lFileOutputStream = new FileOutputStream(lFile);
        ZipOutputStream lZipOutputStream = new ZipOutputStream(lFileOutputStream);

        byte[] buffer = new byte[1024];
        for (String lStrFile : lFileList) {

            ZipEntry lZipEntry = new ZipEntry(
                    lStrFile.substring(lStrDBDirectoryPath.length(), lStrFile.length()));
            lZipOutputStream.putNextEntry(lZipEntry);

            FileInputStream lFileInputStream = new FileInputStream(lStrFile);

            int lIntLen;
            while ((lIntLen = lFileInputStream.read(buffer)) > 0) {
                lZipOutputStream.write(buffer, 0, lIntLen);
            }

            lFileInputStream.close();
        }

        lZipOutputStream.closeEntry();
        lZipOutputStream.close();

        mLog.debug("Folder successfully compressed");
    } catch (IOException e) {
        mLog.error(e);
        throw new BibiscoException(e, BibiscoException.IO_EXCEPTION);
    }

    mLog.debug("End zipIt(String)");
}