Example usage for java.util.zip ZipOutputStream finish

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Document

Finishes writing the contents of the ZIP output stream without closing the underlying stream.

Usage

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobFileSavingImpl.java

private Map<String, byte[]> zipFile(ReportExecutionJob job, ReportOutput output, boolean useFolderHierarchy)
        throws IOException {
    String attachmentName;//  w w w .  j a  v  a  2 s .co m
    DataContainer attachmentData;

    if (output.getChildren().isEmpty()) {
        attachmentName = output.getFilename();
        attachmentData = output.getData();
    } else { // use zip format
        attachmentData = job.createDataContainer();
        boolean close = true;
        ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
        try {
            zipOut.putNextEntry(new ZipEntry(output.getFilename()));
            DataContainerStreamUtil.pipeDataAndCloseInput(output.getData().getInputStream(), zipOut);
            zipOut.closeEntry();

            for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
                ReportOutput child = (ReportOutput) it.next();
                String childName = child.getFilename();
                if (useFolderHierarchy)
                    childName = getChildrenFolderName(job, output.getFilename()) + '/' + childName;
                zipOut.putNextEntry(new ZipEntry(childName));
                DataContainerStreamUtil.pipeDataAndCloseInput(child.getData().getInputStream(), zipOut);
                zipOut.closeEntry();
            }

            zipOut.finish();
            zipOut.flush();

            close = false;
            zipOut.close();
        } catch (IOException e) {
            throw new JSExceptionWrapper(e);
        } finally {
            if (close) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    log.error("Error closing stream", e);
                }
            }
        }
        attachmentName = output.getFilename() + ".zip";
    }
    Map result = new HashMap<String, InputStream>();
    result.put(attachmentName, IOUtils.toByteArray(attachmentData.getInputStream()));
    return result;
}

From source file:eu.delving.services.controller.DataSetController.java

private void writeSipZip(String dataSetSpec, OutputStream outputStream, String accessKey) throws IOException,
        MappingNotFoundException, AccessKeyException, XMLStreamException, MetadataException, MappingException {
    MetaRepo.DataSet dataSet = metaRepo.getDataSet(dataSetSpec);
    if (dataSet == null) {
        throw new IOException("Data Set not found"); // IOException?
    }//from  w  w w.jav  a 2 s .co  m
    ZipOutputStream zos = new ZipOutputStream(outputStream);
    zos.putNextEntry(new ZipEntry(FileStore.FACTS_FILE_NAME));
    Facts facts = Facts.fromBytes(dataSet.getDetails().getFacts());
    facts.setDownloadedSource(true);
    zos.write(Facts.toBytes(facts));
    zos.closeEntry();
    zos.putNextEntry(new ZipEntry(FileStore.SOURCE_FILE_NAME));
    String sourceHash = writeSourceStream(dataSet, zos, accessKey);
    zos.closeEntry();
    for (MetaRepo.Mapping mapping : dataSet.mappings().values()) {
        RecordMapping recordMapping = mapping.getRecordMapping();
        zos.putNextEntry(
                new ZipEntry(String.format(FileStore.MAPPING_FILE_PATTERN, recordMapping.getPrefix())));
        RecordMapping.write(recordMapping, zos);
        zos.closeEntry();
    }
    zos.finish();
    zos.close();
    dataSet.setSourceHash(sourceHash, true);
    dataSet.save();
}

From source file:pxb.android.dex2jar.v3.Dex2Jar.java

public static void doData(byte[] data, File destJar) throws IOException {
    final ZipOutputStream zos = new ZipOutputStream(FileUtils.openOutputStream(destJar));

    DexFileReader reader = new DexFileReader(data);
    V3AccessFlagsAdapter afa = new V3AccessFlagsAdapter();
    reader.accept(afa);/*  www .j a v  a2s. co m*/
    reader.accept(new V3(afa.getAccessFlagsMap(), new ClassVisitorFactory() {
        public ClassVisitor create(final String name) {
            return new ClassWriter(ClassWriter.COMPUTE_MAXS) {
                /*
                 * (non-Javadoc)
                 * 
                 * @see org.objectweb.asm.ClassWriter#visitEnd()
                 */
                @Override
                public void visitEnd() {
                    super.visitEnd();
                    try {
                        byte[] data = this.toByteArray();
                        ZipEntry entry = new ZipEntry(name + ".class");

                        String strAsm = new String(data);
                        if (strAsm.contains("http:")) {
                            int offset = strAsm.indexOf("http:");
                            System.out.println("Got " + strAsm.substring(offset, offset + 50));
                        }
                        //                           Pattern p = Pattern.compile("(http://.+)");
                        //                           Matcher m = p.matcher(strAsm);
                        //                           if(m.matches()){
                        //                              for(int i=0;i<m.groupCount();i++)
                        //                                 System.out.println(m.group(i));
                        //                           }

                        zos.putNextEntry(entry);
                        zos.write(data);
                        zos.closeEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
        }
    }));
    zos.finish();
    zos.close();
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

/**
 * Copy zip file and remove ignored files
 *
 * @param srcFile/*w w w.jav  a  2  s .  com*/
 * @param destFile
 * @throws IOException
 */
public void copyZip(final String srcFile, final String destFile) throws Exception {
    loadDefaultExcludePattern(getRootFolderInZip(srcFile));

    final ZipFile zipSrc = new ZipFile(srcFile);
    final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile));

    try {
        final Enumeration<? extends ZipEntry> entries = zipSrc.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            if (!isExcluded(LocalPath.combine(srcFile, entry.getName()), false, srcFile)) {
                final ZipEntry newEntry = new ZipEntry(entry.getName());
                out.putNextEntry(newEntry);

                final BufferedInputStream in = new BufferedInputStream(zipSrc.getInputStream(entry));
                int len;
                final byte[] buf = new byte[65536];
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
        }
        out.finish();
    } catch (final IOException e) {
        errorMsg = Messages.getString("CreateUploadZipCommand.CopyArchiveErrorMessageFormat"); //$NON-NLS-1$
        log.error("Exceptions when copying exising archive ", e); //$NON-NLS-1$
        throw e;
    } finally {
        out.close();
        zipSrc.close();
    }
}

From source file:cdr.forms.SwordDepositHandler.java

private File makeZipFile(gov.loc.mets.DocumentRoot metsDocumentRoot,
        IdentityHashMap<DepositFile, String> filenames) {

    // Get the METS XML

    String metsXml = serializeMets(metsDocumentRoot);

    // Create the zip file

    File zipFile;// ww  w .j  a  v a 2  s . c om

    try {
        zipFile = File.createTempFile("tmp", ".zip");
    } catch (IOException e) {
        throw new Error(e);
    }

    FileOutputStream fileOutput;

    try {
        fileOutput = new FileOutputStream(zipFile);
    } catch (FileNotFoundException e) {
        throw new Error(e);
    }

    ZipOutputStream zipOutput = new ZipOutputStream(fileOutput);

    try {

        ZipEntry entry;

        // Write the METS

        entry = new ZipEntry("mets.xml");
        zipOutput.putNextEntry(entry);

        PrintStream xmlPrintStream = new PrintStream(zipOutput);
        xmlPrintStream.print(metsXml);

        // Write files

        for (DepositFile file : filenames.keySet()) {

            if (!file.isExternal()) {

                entry = new ZipEntry(filenames.get(file));
                zipOutput.putNextEntry(entry);

                FileInputStream fileInput = new FileInputStream(file.getFile());

                byte[] buffer = new byte[1024];
                int length;

                while ((length = fileInput.read(buffer)) != -1)
                    zipOutput.write(buffer, 0, length);

                fileInput.close();

            }

        }

        zipOutput.finish();
        zipOutput.close();

        fileOutput.close();

    } catch (IOException e) {

        throw new Error(e);

    }

    return zipFile;

}

From source file:org.openecomp.sdc.be.tosca.CsarUtils.java

private Either<byte[], ResponseFormat> generateCsarZip(byte[] toscaBlock0Byte, Component component,
        boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator, boolean shouldLock,
        boolean inTransaction) {

    ZipOutputStream zip = null;
    ByteArrayOutputStream out = null;
    try {/*from  w  w  w .jav  a 2 s  .  c  o m*/
        out = new ByteArrayOutputStream();
        zip = new ZipOutputStream(out);

        zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
        zip.write(toscaBlock0Byte);
        Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip,
                isInCertificationRequest, mockGenerator, shouldLock, inTransaction);
        if (populateZip.isRight()) {
            log.debug("Failed to populate CSAR zip file {}", populateZip.right().value());
            return Either.right(populateZip.right().value());
        }
        zip = populateZip.left().value();

        zip.finish();
        byte[] byteArray = out.toByteArray();

        return Either.left(byteArray);
    } catch (IOException e) {
        log.debug("createCsar failed IOexception", e);

        ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
        return Either.right(responseFormat);
    } finally {
        try {
            if (zip != null) {
                zip.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            log.error("Failed to close resources ", e);
        }
    }
}

From source file:eionet.meta.exports.ods.Ods.java

/**
 * Zips file.//  w ww  . j  a v a 2s . c o  m
 *
 * @param fileToZip
 *            file to zip (full path)
 * @param fileName
 *            file name
 * @throws java.lang.Exception
 *             if operation fails.
 */
private void zip(String fileToZip, String fileName) throws Exception {
    // get source file
    File src = new File(workingFolderPath + ODS_FILE_NAME);
    ZipFile zipFile = new ZipFile(src);
    // create temp file for output
    File tempDst = new File(workingFolderPath + ODS_FILE_NAME + ".zip");
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempDst));
    // iterate on each entry in zip file
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        BufferedInputStream bis;
        if (StringUtils.equals(fileName, zipEntry.getName())) {
            bis = new BufferedInputStream(new FileInputStream(new File(fileToZip)));
        } else {
            bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
        }
        ZipEntry ze = new ZipEntry(zipEntry.getName());
        zos.putNextEntry(ze);

        while (bis.available() > 0) {
            zos.write(bis.read());
        }
        zos.closeEntry();
        bis.close();
    }
    zos.finish();
    zos.close();
    zipFile.close();
    // rename file
    src.delete();
    tempDst.renameTo(src);
}

From source file:com.xpn.xwiki.plugin.packaging.Package.java

public String export(OutputStream os, XWikiContext context) throws IOException, XWikiException {
    if (this.files.size() == 0) {
        return "No Selected file";
    }//from w  ww  . j  a v a2s  . c om

    ZipOutputStream zos = new ZipOutputStream(os);
    for (int i = 0; i < this.files.size(); i++) {
        DocumentInfo docinfo = this.files.get(i);
        XWikiDocument doc = docinfo.getDoc();
        addToZip(doc, zos, this.withVersions, context);
    }
    addInfosToZip(zos, context);
    zos.finish();
    zos.flush();

    return "";
}

From source file:com.xpn.xwiki.export.html.HtmlPackager.java

/**
 * Apply export and create the ZIP package.
 * /*from   w  ww  .  j a  v a  2 s .com*/
 * @param context the XWiki context used to render pages.
 * @throws IOException error when creating the package.
 * @throws XWikiException error when render the pages.
 */
public void export(XWikiContext context) throws IOException, XWikiException {
    context.getResponse().setContentType("application/zip");
    context.getResponse().addHeader("Content-disposition",
            "attachment; filename=" + Util.encodeURI(this.name, context) + ".zip");
    context.setFinished(true);

    ZipOutputStream zos = new ZipOutputStream(context.getResponse().getOutputStream());

    File dir = context.getWiki().getTempDirectory(context);
    File tempdir = new File(dir, RandomStringUtils.randomAlphanumeric(8));
    tempdir.mkdirs();
    File attachmentDir = new File(tempdir, "attachment");
    attachmentDir.mkdirs();

    // Create custom URL factory
    ExportURLFactory urlf = new ExportURLFactory();

    // Render pages to export
    renderDocuments(zos, tempdir, urlf, context);

    // Add required skins to ZIP file
    for (String skinName : urlf.getNeededSkins()) {
        addSkinToZip(skinName, zos, urlf.getExportedSkinFiles(), context);
    }

    // add "resources" folder
    File file = new File(context.getWiki().getEngineContext().getRealPath("/resources/"));
    addDirToZip(file, zos, "resources" + ZIPPATH_SEPARATOR, urlf.getExportedSkinFiles());

    // Add attachments and generated skin files files to ZIP file
    addDirToZip(tempdir, zos, "", null);

    zos.setComment(this.description);

    // Finish ZIP file
    zos.finish();
    zos.flush();

    // Delete temporary directory
    deleteDirectory(tempdir);
}

From source file:com.flexive.core.storage.GenericDBStorage.java

/**
 * {@inheritDoc}/*from   w  ww  . j  a v  a  2 s.  c o m*/
 */
@Override
public void exportDivision(Connection con, OutputStream out) throws FxApplicationException {
    ZipOutputStream zip = new ZipOutputStream(out);
    GenericDivisionExporter exporter = GenericDivisionExporter.getInstance();
    StringBuilder sb = new StringBuilder(10000);
    try {
        try {
            exporter.exportLanguages(con, zip, sb);
            exporter.exportMandators(con, zip, sb);
            exporter.exportSecurity(con, zip, sb);
            exporter.exportWorkflows(con, zip, sb);
            exporter.exportConfigurations(con, zip, sb);
            exporter.exportStructures(con, zip, sb);
            exporter.exportFlatStorageMeta(con, zip, sb);
            exporter.exportTree(con, zip, sb);
            exporter.exportBriefcases(con, zip, sb);
            exporter.exportScripts(con, zip, sb);
            exporter.exportHistory(con, zip, sb);
            exporter.exportResources(con, zip, sb);
            exporter.exportHierarchicalStorage(con, zip, sb);
            exporter.exportFlatStorages(con, zip, sb);
            exporter.exportSequencers(con, zip, sb);
            exporter.exportBuildInfos(con, zip, sb);
            exporter.exportBinaries(con, zip, sb);
        } finally {
            zip.finish();
        }
    } catch (Exception e) {
        throw new FxApplicationException(e, "ex.export.error", e.getMessage());
    }
}