Example usage for java.util.zip GZIPOutputStream finish

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Document

Finishes writing compressed data to the output stream without closing the underlying stream.

Usage

From source file:org.vfny.geoserver.wcs.responses.coverage.AscCoverageResponseDelegate.java

public void encode(OutputStream output) throws ServiceException, IOException {
    if (sourceCoverage == null) {
        throw new IllegalStateException(new StringBuffer("It seems prepare() has not been called")
                .append(" or has not succeed").toString());
    }//from   w  w  w.ja va  2 s  . c om

    GZIPOutputStream gzipOut = null;
    if (compressOutput) {
        gzipOut = new GZIPOutputStream(output);
        output = gzipOut;
    }

    ArcGridWriter writer = null;
    try {
        writer = new ArcGridWriter(output);
        writer.write(sourceCoverage, null);

        if (gzipOut != null) {
            gzipOut.finish();
            gzipOut.flush();
        }

    } finally {
        try {
            if (writer != null)
                writer.dispose();
        } catch (Throwable e) {
            // eating exception
        }
        if (gzipOut != null)
            IOUtils.closeQuietly(gzipOut);

        this.sourceCoverage.dispose(false);
        this.sourceCoverage = null;
    }
}

From source file:org.eclipse.swordfish.plugins.compression.CompressorImpl.java

public Source asCompressedSource(Source src, int sizeThreshold) {
    try {/*w  w  w .ja v a2s . co  m*/
        if (!isExceedSizeThreshold(src, sizeThreshold)) {
            return null;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream zipped = new GZIPOutputStream(baos);
        Result result = new StreamResult(zipped);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(src, result);
        zipped.finish();
        byte[] compressedBytes = baos.toByteArray();
        String encoded = new String(new Base64().encode(compressedBytes));
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element wrapper = doc.createElementNS(CompressionConstants.COMPRESSION_NS,
                CompressionConstants.COMPRESSION_ELEMENT_PREFIX + ":"
                        + CompressionConstants.COMPRESSED_ELEMENT);
        wrapper.setAttributeNS("http://www.w3.org/2000/xmlns/",
                "xmlns:" + CompressionConstants.COMPRESSION_ELEMENT_PREFIX,
                CompressionConstants.COMPRESSION_NS);
        wrapper.appendChild(doc.createTextNode(encoded));
        doc.appendChild(wrapper);
        return new DOMSource(doc);
    } catch (Exception e) {
        LOG.error("Couldn't compress source", e);
        throw new SwordfishException("Couldn't compress source", e);
    }
}

From source file:org.nuxeo.ecm.platform.categorization.categorizer.tfidf.TfIdfCategorizer.java

/**
 * Save a compressed binary representation of the trained model.
 *
 * @param out the output stream to write to
 *//* ww w .j  a v  a  2s . c o  m*/
public void saveToStream(OutputStream out) throws IOException {
    if (updateDisabled) {
        throw new IllegalStateException("model in disabled update mode cannot be saved");
    }
    invalidateCache();
    GZIPOutputStream gzOut = new GZIPOutputStream(out);
    ObjectOutputStream objOut = new ObjectOutputStream(gzOut);
    objOut.writeObject(this);
    gzOut.finish();
}

From source file:eu.domibus.ebms3.common.CompressionService.java

/**
 * Compress given Stream via GZIP [RFC1952].
 *
 * @param sourceStream Stream of uncompressed data
 * @param targetStream Stream of compressed data
 * @throws IOException//  w w w. j a v  a 2  s . co  m
 */
private void compress(final InputStream sourceStream, final GZIPOutputStream targetStream) throws IOException {
    final byte[] buffer = new byte[1024];

    try {
        int i;
        while ((i = sourceStream.read(buffer)) > 0) {
            targetStream.write(buffer, 0, i);
        }

        sourceStream.close();

        targetStream.finish();
        targetStream.close();

    } catch (IOException e) {
        CompressionService.LOG.error(
                "I/O exception during gzip compression. method: compress(Inputstream, GZIPOutputStream)", e);
        throw e;
    }
}

From source file:builder.smartfrog.SmartFrogAction.java

public void compressLog() {
    File logFile = getLogFile();//from  ww  w.ja  v a2  s . c  o  m
    File compressedLog = new File(logFile.getParentFile(), logFile.getName() + ".gz");
    GZIPOutputStream gzos = null;
    FileInputStream ist = null;
    try {
        gzos = new GZIPOutputStream(new FileOutputStream(compressedLog));
        ist = new FileInputStream(logFile);
        IOUtils.copy(ist, gzos);
        gzos.finish();
    } catch (IOException e) {
        Logger.getLogger(SmartFrogBuildListener.class.getName()).log(Level.WARNING,
                "was not able to compress log file " + logFile.getAbsolutePath(), e);
        if (ist != null)
            IOUtils.closeQuietly(ist);
        if (gzos != null)
            IOUtils.closeQuietly(gzos);
        return;
    }
    logFile.delete();
}

From source file:com.kloudtek.buildmagic.tools.createinstaller.deb.CreateDebTask.java

private void prepare() throws IOException {
    // validate parameters
    if (name == null || name.trim().length() == 0) {
        throw new BuildException("name attribute is missing or invalid");
    }/*from   w  w  w  . ja  v  a 2  s .c om*/
    if (version == null || version.trim().length() == 0) {
        throw new BuildException("version attribute is missing or invalid");
    }
    if (arch == null || arch.trim().length() == 0) {
        throw new BuildException("arch attribute is missing or invalid");
    }
    if (maintName == null || maintName.trim().length() == 0) {
        throw new BuildException("maintName attribute is missing");
    }
    if (maintEmail == null || maintEmail.trim().length() == 0) {
        throw new BuildException("maintEmail attribute is missing");
    }
    if (priority != null && !PRIORITIES.contains(priority.toLowerCase())) {
        log("Priority '" + priority + "' isn't recognized as a valid value", Project.MSG_WARN);
    }
    if (control != null) {
        for (final TemplateEntry entry : control.getTemplateEntries()) {
            if (entry.getPackageName() == null) {
                entry.setPackageName(name);
            }
            templateEntries.add(entry);
        }
    }
    // generate copyright file
    if (copyrights.isEmpty()) {
        if (license == null) {
            throw new BuildException("No license has been specified");
        }
        if (licenseFile == null) {
            licenseFile = new File("license.txt");
        }
        copyrights.add(new Copyright(license, licenseFile));
    }
    copyrights.validate();
    copyright = dataBufferManager.createBuffer();
    copyrights.write(copyright, this);
    // generate changelog
    changelog = new Changelog(name);
    Changelog.Entry entry = changelog.createEntry();
    changelog.setDistributions("main"); // TODO
    entry.setMaintName(maintName);
    entry.setMaintEmail(maintEmail);
    entry.setChanges("Released");
    entry.setVersion(version);
    entry.setDate(new Date());
    changelog.validate();
    changelogData = changelog.export(Changelog.Type.DEBIAN);
    ByteArrayOutputStream changelogBuf = new ByteArrayOutputStream();
    GZIPOutputStream changelogGzipBuf = new GZIPOutputStream(changelogBuf);
    changelogGzipBuf.write(changelogData.getBytes());
    changelogGzipBuf.finish();
    changelogGzipBuf.close();
    changelogDataGzipped = changelogBuf.toByteArray();
}

From source file:org.loadosophia.client.LoadosophiaAPIClient.java

private File gzipFile(File src) throws IOException {
    // Never try to make it stream-like on the fly, because content-length
    // still required
    // Create the GZIP output stream
    String outFilename = src.getAbsolutePath() + ".gz";
    notifier.notifyAbout("Gzipping " + src.getAbsolutePath());
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFilename));

    // Open the input file
    FileInputStream in = new FileInputStream(src);

    // Transfer bytes from the input file to the GZIP output stream
    byte[] buf = new byte[1024];
    int len;//  w  w w  . j  av  a2s.  c o  m
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();

    // Complete the GZIP file
    out.finish();
    out.close();

    src.delete();

    return new File(outFilename);
}

From source file:com.hypersocket.netty.HttpRequestDispatcherHandler.java

private InputStream processContent(HttpRequestServletWrapper servletRequest,
        HttpResponseServletWrapper servletResponse, String acceptEncodings) {

    InputStream writer = (InputStream) servletRequest.getAttribute(CONTENT_INPUTSTREAM);

    if (writer != null) {
        if (log.isDebugEnabled()) {
            log.debug("Response for " + servletRequest.getRequestURI() + " will be chunked");
        }//from www . j a v a 2s .com
        servletResponse.setChunked(true);
        servletResponse.removeHeader(HttpHeaders.CONTENT_LENGTH);
        servletResponse.setHeader(HttpHeaders.TRANSFER_ENCODING, "chunked");
        return writer;
    }

    if (servletResponse.getContent().readableBytes() > 0) {

        ChannelBuffer buffer = servletResponse.getContent();
        boolean doGzip = false;

        if (servletResponse.getNettyResponse().getHeader("Content-Encoding") == null) {
            if (acceptEncodings != null) {
                doGzip = acceptEncodings.indexOf("gzip") > -1;
            }

            if (doGzip) {
                try {
                    ByteArrayOutputStream gzipped = new ByteArrayOutputStream();
                    GZIPOutputStream gzip = new GZIPOutputStream(gzipped);
                    gzip.write(buffer.array(), 0, buffer.readableBytes());
                    gzip.finish();
                    buffer = ChannelBuffers.wrappedBuffer(gzipped.toByteArray());
                    servletResponse.setHeader("Content-Encoding", "gzip");
                } catch (IOException e) {
                    log.error("Failed to gzip response", e);
                }
            }
        }

        servletResponse.getNettyResponse().setContent(buffer);
        servletResponse.setHeader("Content-Length", String.valueOf(buffer.readableBytes()));
    } else {
        servletResponse.setHeader("Content-Length", "0");
    }

    return null;
}

From source file:com.chenshu.compress.CompressOldTest.java

@Benchmark
public int jdkGzip2Compress() {
    ByteArrayInputStream bin = null;
    ByteArrayOutputStream bout = null;
    GZIPOutputStream gzout = null;
    try {/*from www . ja  v  a2s .co  m*/
        bin = new ByteArrayInputStream(data);
        bout = new ByteArrayOutputStream(data.length);
        gzout = new GZIPOutputStream(bout) {
            {
                def.setLevel(level);
            }
        };
        int count;
        byte ret[] = new byte[1024];
        while ((count = bin.read(ret, 0, 1024)) != -1) {
            gzout.write(ret, 0, count);
        }
        gzout.finish();
        gzout.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (gzout != null) {
            try {
                gzout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bout != null) {
            try {
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    byte[] bs = bout.toByteArray();
    return bs.length;
}

From source file:ezbake.deployer.cli.commands.SSLCertsCommand.java

@Override
public void call() throws IOException, TException {
    String[] args = globalParameters.unparsedArgs;
    minExpectedArgs(2, args, this);
    String securityId = args[0];//  w w  w . ja v  a2  s.  c o m
    String filePath = args[1];

    List<ArtifactDataEntry> certs = new ArrayList<>();
    EzSecurityRegistration.Client client = null;
    ThriftClientPool pool = poolSupplier.get();
    try {
        client = pool.getClient(EzSecurityRegistrationConstants.SERVICE_NAME,
                EzSecurityRegistration.Client.class);

        AppCerts s = client.getAppCerts(
                getSecurityToken(pool.getSecurityId(EzSecurityRegistrationConstants.SERVICE_NAME)), securityId);
        for (AppCerts._Fields fields : AppCerts._Fields.values()) {
            Object o = s.getFieldValue(fields);
            if (o instanceof byte[]) {
                String fieldName = fields.getFieldName().replace("_", ".");
                TarArchiveEntry tae = new TarArchiveEntry(
                        new File(new File(SSL_CONFIG_DIRECTORY, securityId), fieldName));
                certs.add(new ArtifactDataEntry(tae, (byte[]) o));
            }
        }

        ArchiveStreamFactory asf = new ArchiveStreamFactory();
        FileOutputStream fos = new FileOutputStream(filePath);
        GZIPOutputStream gzs = new GZIPOutputStream(fos);
        try (TarArchiveOutputStream aos = (TarArchiveOutputStream) asf
                .createArchiveOutputStream(ArchiveStreamFactory.TAR, gzs)) {
            aos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

            for (ArtifactDataEntry entry : certs) {
                aos.putArchiveEntry(entry.getEntry());
                IOUtils.write(entry.getData(), aos);
                aos.closeArchiveEntry();
            }
            aos.finish();
            gzs.finish();
        } catch (ArchiveException ex) {
            throw new DeploymentException(ex.getMessage());
        } finally {
            IOUtils.closeQuietly(fos);
        }
    } finally {
        pool.returnToPool(client);
    }
}