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.dbi.jmmerge.MapController.java

@RequestMapping(value = "maps/{server}", produces = "application/zip")
public byte[] downloadMap(@PathVariable("server") String server, HttpServletResponse response)
        throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedOutputStream bufstream = new BufferedOutputStream(baos);
    ZipOutputStream zip = new ZipOutputStream(bufstream);

    addDirectoryContents(null, new File(storageDir, server), zip);

    zip.finish();
    zip.flush();//from   w w w.  j  a v  a 2s  . com
    IOUtils.closeQuietly(zip);
    IOUtils.closeQuietly(bufstream);
    IOUtils.closeQuietly(baos);

    response.setStatus(HttpServletResponse.SC_OK);
    response.addHeader("Content-Disposition", "attachment; filename=\"" + server + ".zip\"");
    return baos.toByteArray();
}

From source file:com.eviware.soapui.impl.wsdl.support.FileAttachment.java

public void setData(byte[] data) {
    try {/*  w w w .  j a v a 2s.  c o m*/
        // write attachment-data to tempfile
        ByteArrayOutputStream tempData = new ByteArrayOutputStream();
        ZipOutputStream out = new ZipOutputStream(tempData);
        out.putNextEntry(new ZipEntry(config.getName()));
        config.setSize(data.length);
        out.write(data);
        out.closeEntry();
        out.finish();
        out.close();
        config.setData(tempData.toByteArray());
    } catch (Exception e) {
        SoapUI.logError(e);
    }
}

From source file:org.geoserver.wfs.response.Ogr2OgrOutputFormat.java

/**
 * Writes out the data to an OGR known format (GML/shapefile) to disk and
 * then ogr2ogr each generated file into the destination format. Finally,
 * zips up all the resulting files.//from w ww  .  j a  v a  2s.c  o m
 */
@Override
protected void write(FeatureCollectionResponse featureCollection, OutputStream output, Operation getFeature)
        throws IOException, ServiceException {

    // figure out which output format we're going to generate
    GetFeatureType gft = (GetFeatureType) getFeature.getParameters()[0];
    OgrFormat format = formats.get(gft.getOutputFormat());
    if (format == null)
        throw new WFSException("Unknown output format " + gft.getOutputFormat());

    // create the first temp directory, used for dumping gs generated
    // content
    File tempGS = org.geoserver.data.util.IOUtils.createTempDirectory("ogrtmpin");
    File tempOGR = org.geoserver.data.util.IOUtils.createTempDirectory("ogrtmpout");

    // build the ogr wrapper used to run the ogr2ogr commands
    OGRWrapper wrapper = new OGRWrapper(ogrExecutable, gdalData);

    // actually export each feature collection
    try {
        Iterator outputFeatureCollections = featureCollection.getFeature().iterator();
        SimpleFeatureCollection curCollection;

        File outputFile = null;
        while (outputFeatureCollections.hasNext()) {
            curCollection = (SimpleFeatureCollection) outputFeatureCollections.next();

            // write out the gml
            File intermediate = writeToDisk(tempGS, curCollection);

            // convert with ogr2ogr
            final SimpleFeatureType schema = curCollection.getSchema();
            final CoordinateReferenceSystem crs = schema.getCoordinateReferenceSystem();
            outputFile = wrapper.convert(intermediate, tempOGR, schema.getTypeName(), format, crs);

            // wipe out the input dir contents
            IOUtils.emptyDirectory(tempGS);
        }

        // was is a single file output?
        if (format.singleFile && featureCollection.getFeature().size() == 1) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(outputFile);
                org.apache.commons.io.IOUtils.copy(fis, output);
            } finally {
                if (fis != null) {
                    fis.close();
                }
            }
        } else {
            // scan the output directory and zip it all
            ZipOutputStream zipOut = new ZipOutputStream(output);
            IOUtils.zipDirectory(tempOGR, zipOut, null);
            zipOut.finish();
        }

        // delete the input and output directories
        IOUtils.delete(tempGS);
        IOUtils.delete(tempOGR);
    } catch (Exception e) {
        throw new ServiceException("Exception occurred during output generation", e);
    }
}

From source file:org.bimserver.collada.OpenGLTransmissionFormatSerializer.java

private void zipTheDirectory(OutputStream outputStream, Path writeDirectory) throws IOException {
    // Create the archive.
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    // Copy the files into the ZIP file.
    for (Path f : PathUtils.list(writeDirectory)) {
        addToZipFile(f, zipOutputStream);
    }/*from w  w  w .  j a  v a2 s  .  co m*/
    // Push the data into the parent stream (gets returned to the server).
    zipOutputStream.finish();
    zipOutputStream.flush();
}

From source file:org.theospi.portfolio.presentation.export.PresentationExport.java

public void createZip(OutputStream out) throws IOException {
    File directory = new File(tempDirectory + webappName);

    CheckedOutputStream checksum = null;
    ZipOutputStream zos = null;
    try {//w  w w .jav a  2s . com
        checksum = new CheckedOutputStream(out, new Adler32());
        zos = new ZipOutputStream(new BufferedOutputStream(checksum));
        recurseDirectory("", directory, zos);

        zos.finish();
        zos.flush();
    } finally {
        if (zos != null) {
            try {
                zos.close();
            } catch (IOException e) {
            }
        }
        if (checksum != null) {
            try {
                checksum.close();
            } catch (IOException e) {
            }
        }
    }

}

From source file:b2s.idea.mavenize.JarCombiner.java

public void combineAllJarsIn(File folderOfJars, File output) {
    ZipOutputStream zipOut = null;
    try {/*from w w w.  j  a va  2 s.  c o  m*/
        JarContext context = new JarContext();
        zipOut = new ZipOutputStream(new FileOutputStream(output));
        for (File jarFile : folderOfJars.listFiles(new IntellijJarFileFilter())) {
            copyContentsOf(jarFile, zipOut, context);
            System.out.println(jarFile.getName());
        }

        addServiceEntries(zipOut, context);

        zipOut.finish();
    } catch (IOException e) {
        throw new RuntimeException("A problem occurred when combining the JARs", e);
    } finally {
        IOUtils.closeQuietly(zipOut);
    }
}

From source file:com.eviware.soapui.impl.wsdl.support.FileAttachment.java

public void cacheFileLocally(File file) throws FileNotFoundException, IOException {
    // write attachment-data to tempfile
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    ZipOutputStream out = new ZipOutputStream(data);
    out.putNextEntry(new ZipEntry(config.getName()));

    InputStream in = new FileInputStream(file);
    long sz = file.length();
    config.setSize(sz);/*from  w  ww .ja va2s  .com*/

    Tools.writeAll(out, in);

    in.close();
    out.closeEntry();
    out.finish();
    out.close();
    data.close();

    config.setData(data.toByteArray());
}

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

protected void attachOutput(ReportExecutionJob job, MimeMessageHelper messageHelper, ReportOutput output,
        boolean useZipFormat) throws MessagingException, JobExecutionException {
    String attachmentName;//from w ww  .  j  a  v a2 s.  co m
    DataContainer attachmentData;
    if (output.getChildren().isEmpty()) {
        attachmentName = output.getFilename();
        attachmentData = output.getData();
    } else if (useZipFormat) { // use zip format
        attachmentData = job.createDataContainer();
        boolean close = true;
        ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
        try {
            zipOutput(job, output, zipOut);
            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";
    } else { // NO ZIP FORMAT
        attachmentName = output.getFilename();
        try {
            attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
        } catch (UnsupportedEncodingException e) {
            throw new JSExceptionWrapper(e);
        }
        StringBuffer primaryPage = null;
        for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
            ReportOutput child = (ReportOutput) it.next();
            String childName = child.getFilename();

            // NOTE:  add the ".dat" extension to all image resources
            // email client will automatically append ".dat" extension to all the files with no extension
            // should do it in JasperReport side
            if (output.getFileType().equals(ContentResource.TYPE_HTML)) {
                if (primaryPage == null)
                    primaryPage = new StringBuffer(new String(output.getData().getData()));
                int fromIndex = 0;
                while ((fromIndex = primaryPage.indexOf("src=\"" + childName + "\"", fromIndex)) > 0) {
                    primaryPage.insert(fromIndex + 5 + childName.length(), ".dat");
                }
                childName = childName + ".dat";
            }

            try {
                childName = MimeUtility.encodeWord(childName, job.getCharacterEncoding(), null);
            } catch (UnsupportedEncodingException e) {
                throw new JSExceptionWrapper(e);
            }
            messageHelper.addAttachment(childName, new DataContainerResource(child.getData()));
        }
        if (primaryPage == null) {
            messageHelper.addAttachment(attachmentName, new DataContainerResource(output.getData()));
        } else {
            messageHelper.addAttachment(attachmentName,
                    new DataContainerResource(new MemoryDataContainer(primaryPage.toString().getBytes())));
        }
        return;
    }
    try {
        attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
    } catch (UnsupportedEncodingException e) {
        throw new JSExceptionWrapper(e);
    }
    messageHelper.addAttachment(attachmentName, new DataContainerResource(attachmentData));
}

From source file:org.clickframes.testframes.TestRunner.java

static File aggregrateTestResults(File outputDirectory, String filterName) throws IOException {
    // firefox/pages_accountConfirmation_linkSets_global_suite_result.html
    // and so on/*from   ww w  .  j a  v a  2 s.c o  m*/
    File tmpFile = File.createTempFile("selenium-testresults", ".zip");
    ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(tmpFile));

    File resultsDirBase = new File(outputDirectory, "selenium" + File.separator
            + ClickframeUtils.convertSlashToPathSeparator(filterName) + File.separator + "results");

    // get the newest directory
    File resultsDir = getNewestDir(resultsDirBase);

    // firefox/
    // firefox/firefox/pages_accountConfirmation_linkSets_global_suite_result.html
    for (File browserOrIndexFile : resultsDir.listFiles()) {
        if (browserOrIndexFile.isDirectory()) {
            for (File testResultFile : (Collection<File>) FileUtils.listFiles(browserOrIndexFile,
                    new String[] { "html" }, false)) {
                zipStream.putNextEntry(
                        new ZipEntry(browserOrIndexFile.getName() + File.separator + testResultFile.getName()));
                IOUtils.copy(new FileInputStream(testResultFile), zipStream);
            }
        } else {
            if (browserOrIndexFile.getName().equals("testResults.xml")) {
                zipStream.putNextEntry(new ZipEntry(browserOrIndexFile.getName()));
                IOUtils.copy(new FileInputStream(browserOrIndexFile), zipStream);
            }
        }
    }

    zipStream.finish();

    File destination = new File(resultsDirBase, "testResults.zip");

    FileUtils.copyFile(tmpFile, destination);

    System.out.println(destination.getAbsolutePath());

    return destination;
}

From source file:hd3gtv.embddb.network.DataBlock.java

byte[] getBytes(Protocol protocol) throws IOException {
    checkIfNotEmpty();/*w  w w .  j a  v  a  2s  . c o m*/

    ByteArrayOutputStream byte_array_out_stream = new ByteArrayOutputStream(Protocol.BUFFER_SIZE);

    DataOutputStream dos = new DataOutputStream(byte_array_out_stream);
    dos.write(Protocol.APP_SOCKET_HEADER_TAG);
    dos.writeInt(Protocol.VERSION);

    /**
     * Start header name
     */
    dos.writeByte(0);
    byte[] request_name_data = request_name.getBytes(Protocol.UTF8);
    dos.writeInt(request_name_data.length);
    dos.write(request_name_data);

    /**
     * Start datas payload
     */
    dos.writeByte(1);

    /**
     * Get datas from zip
     */
    ZipOutputStream zos = new ZipOutputStream(dos);
    zos.setLevel(3);
    entries.forEach(entry -> {
        try {
            entry.toZip(zos);
        } catch (IOException e) {
            log.error("Can't add to zip", e);
        }
    });
    zos.flush();
    zos.finish();
    zos.close();

    dos.flush();
    dos.close();

    byte[] result = byte_array_out_stream.toByteArray();

    if (log.isTraceEnabled()) {
        log.trace("Make raw datas for " + request_name + Hexview.LINESEPARATOR + Hexview.tracelog(result));
    }

    return result;
}