Example usage for java.util.zip GZIPOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Writes remaining compressed data to the output stream and closes the underlying stream.

Usage

From source file:com.google.api.ads.adwords.awreporting.processors.onmemory.ReportProcessorOnMemoryTest.java

private byte[] getReporDatafromCsv(ReportDefinitionReportType reportType) throws Exception {
    byte[] reportData = reportDataMap.get(reportType);
    if (reportData == null) {
        FileInputStream fis = new FileInputStream(getReportDataFileName(reportType));
        ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
        GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
        FileUtil.copy(fis, gzipOut);/*w ww  .j  av a  2 s  .c om*/
        gzipOut.flush();
        gzipOut.close();
        reportData = baos.toByteArray();
        reportDataMap.put(reportType, reportData);
        baos.flush();
        baos.close();
    }
    return reportData;
}

From source file:NGzipCompressingEntity.java

public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException {
    if (baos == null) {
        baos = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(baos);
        InputStream in = wrappedEntity.getContent();
        byte[] tmp = new byte[2048];
        int l;//from  w w  w .  j  av a 2s . c  om
        while ((l = in.read(tmp)) != -1) {
            gzip.write(tmp, 0, l);
        }
        gzip.close();

        buffer = ByteBuffer.wrap(baos.toByteArray());
    }

    encoder.write(buffer);
    if (!buffer.hasRemaining())
        encoder.complete();
}

From source file:org.apache.nutch.webapp.CacheManager.java

/**
 * Put Search object in cache//from  ww w .j a  va 2s .  co  m
 * 
 * @param id key
 * @param search the search to cache
 */
public void putSearch(String id, Search search) {
    try {
        long time = System.currentTimeMillis();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        GZIPOutputStream gzos = new GZIPOutputStream(bos);
        DataOutputStream oos = new DataOutputStream(gzos);
        search.write(oos);
        oos.flush();
        oos.close();
        gzos.close();
        long delta = System.currentTimeMillis() - time;
        ByteBufferWrapper wrap = new ByteBufferWrapper(bos.toByteArray());
        if (LOG.isDebugEnabled()) {
            LOG.debug("Compressing cache entry took: " + delta + "ms.");
            LOG.debug("size: " + wrap.getContents().length + " bytes");
        }
        cache.putInCache(id, wrap);
    } catch (IOException e) {
        LOG.info("cannot store object in cache: " + e);
    }
}

From source file:org.jsnap.http.base.HttpServlet.java

protected void doService(org.apache.http.HttpRequest request, org.apache.http.HttpResponse response)
        throws HttpException, IOException {
    // Client might keep the executing thread blocked for very long unless this header is added.
    response.addHeader(new Header(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
    // Create a wrapped request object.
    String uri, data;//from   w  w  w.  ja  v a 2s  .  com
    String method = request.getRequestLine().getMethod();
    if (method.equals(HttpGet.METHOD_NAME)) {
        BasicHttpRequest get = (BasicHttpRequest) request;
        data = get.getRequestLine().getUri();
        int ix = data.indexOf('?');
        uri = (ix < 0 ? data : data.substring(0, ix));
        data = (ix < 0 ? "" : data.substring(ix + 1));
    } else if (method.equals(HttpPost.METHOD_NAME)) {
        BasicHttpEntityEnclosingRequest post = (BasicHttpEntityEnclosingRequest) request;
        HttpEntity postedEntity = post.getEntity();
        uri = post.getRequestLine().getUri();
        data = EntityUtils.toString(postedEntity);
    } else {
        response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
        response.setHeader(new Header(HTTP.CONTENT_LEN, "0"));
        return;
    }
    String cookieLine = "";
    if (request.containsHeader(COOKIE)) {
        Header[] cookies = request.getHeaders(COOKIE);
        for (Header cookie : cookies) {
            if (cookieLine.length() > 0)
                cookieLine += "; ";
            cookieLine += cookie.getValue();
        }
    }
    HttpRequest req = new HttpRequest(uri, underlying, data, cookieLine);
    // Create a wrapped response object.
    ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
    HttpResponse resp = new HttpResponse(out);
    // Do implementation specific processing.
    doServiceImpl(req, resp);
    out.flush(); // It's good practice to do this.
    // Do the actual writing to the actual response object.
    if (resp.redirectTo != null) {
        // Redirection is requested.
        resp.statusCode = HttpStatus.SC_MOVED_TEMPORARILY;
        response.setStatusCode(resp.statusCode);
        Header redirection = new Header(LOCATION, resp.redirectTo);
        response.setHeader(redirection);
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, redirection.toString());
    } else {
        // There will be a response entity.
        response.setStatusCode(resp.statusCode);
        HttpEntity entity;
        Header contentTypeHeader;
        boolean text = resp.contentType.startsWith(Formatter.TEXT);
        if (text) { // text/* ...
            entity = new StringEntity(out.toString(resp.characterSet), resp.characterSet);
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE,
                    resp.contentType + HTTP.CHARSET_PARAM + resp.characterSet);
        } else { // application/octet-stream, image/* ...
            entity = new ByteArrayEntity(out.toByteArray());
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE, resp.contentType);
        }
        boolean acceptsGzip = clientAcceptsGzip(request);
        long contentLength = entity.getContentLength();
        // If client accepts gzipped content, the implementing object requested that response
        // gets gzipped and size of the response exceeds implementing object's size threshold
        // response entity will be gzipped.
        boolean gzipped = false;
        if (acceptsGzip && resp.zipSize > 0 && contentLength >= resp.zipSize) {
            ByteArrayOutputStream zipped = new ByteArrayOutputStream(BUFFER_SIZE);
            GZIPOutputStream gzos = new GZIPOutputStream(zipped);
            entity.writeTo(gzos);
            gzos.close();
            entity = new ByteArrayEntity(zipped.toByteArray());
            contentLength = zipped.size();
            gzipped = true;
        }
        // This is where true writes are made.
        Header contentLengthHeader = new Header(HTTP.CONTENT_LEN, Long.toString(contentLength));
        Header contentEncodingHeader = null;
        response.setHeader(contentTypeHeader);
        response.setHeader(contentLengthHeader);
        if (gzipped) {
            contentEncodingHeader = new Header(CONTENT_ENCODING, Formatter.GZIP);
            response.setHeader(contentEncodingHeader);
        }
        response.setEntity(entity);
        // Log critical headers.
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentTypeHeader.toString());
        if (gzipped)
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentEncodingHeader.toString());
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentLengthHeader.toString());
    }
    // Log cookies.
    for (Cookie cookie : resp.cookies) {
        if (cookie.valid()) {
            Header h = new Header(SET_COOKIE, cookie.toString());
            response.addHeader(h);
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, h.toString());
        }
    }
}

From source file:edu.cornell.med.icb.goby.alignments.UpgradeTo1_9_6.java

private void upgradeHeaderVersion(String basename) throws IOException {
    InputStream headerStream;//  w  w  w.j  a va 2 s .c  om
    try {
        headerStream = new GZIPInputStream(new RepositionableInputStream(basename + ".header"));
    } catch (IOException e) {
        // try not compressed for compatibility with 1.4-:
        LOG.trace("falling back to legacy 1.4- uncompressed header.");

        headerStream = new FileInputStream(basename + ".header");
    }
    // accept very large header messages, since these may contain query identifiers:
    final CodedInputStream codedInput = CodedInputStream.newInstance(headerStream);
    codedInput.setSizeLimit(Integer.MAX_VALUE);
    final Alignments.AlignmentHeader header = Alignments.AlignmentHeader.parseFrom(codedInput);

    Alignments.AlignmentHeader.Builder upgradedHeader = Alignments.AlignmentHeader.newBuilder(header);
    upgradedHeader.setVersion(VersionUtils.getImplementationVersion(UpgradeTo1_9_6.class));
    FileUtils.moveFile(new File(basename + ".header"),
            new File(makeBackFilename(basename + ".header", ".bak")));
    GZIPOutputStream headerOutput = new GZIPOutputStream(new FileOutputStream(basename + ".header"));
    try {
        upgradedHeader.build().writeTo(headerOutput);
    } finally {
        headerOutput.close();
    }
}

From source file:org.apache.felix.karaf.webconsole.gogo.GogoPlugin.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String encoding = request.getHeader("Accept-Encoding");
    boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
    SessionTerminal st = (SessionTerminal) request.getSession(true).getAttribute("terminal");
    if (st == null || st.isClosed()) {
        st = new SessionTerminal();
        request.getSession().setAttribute("terminal", st);
    }//from w  ww.  j a v a 2  s  .c om
    String str = request.getParameter("k");
    String f = request.getParameter("f");
    String dump = st.handle(str, f != null && f.length() > 0);
    if (dump != null) {
        if (supportsGzip) {
            response.setHeader("Content-Encoding", "gzip");
            response.setHeader("Content-Type", "text/html");
            try {
                GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
                gzos.write(dump.getBytes());
                gzos.close();
            } catch (IOException ie) {
                // handle the error here
                ie.printStackTrace();
            }
        } else {
            response.getOutputStream().write(dump.getBytes());
        }
    }
}

From source file:org.runnerup.export.GoogleFitSynchronizer.java

private Status sendData(StringWriter w, String suffix, RequestMethod method) throws IOException {
    Status status = Status.ERROR;/*from w  w  w.  j  ava 2 s  .c  o m*/
    for (int attempts = 0; attempts < MAX_ATTEMPTS; attempts++) {
        HttpURLConnection connect = getHttpURLConnection(suffix, method);
        GZIPOutputStream gos = new GZIPOutputStream(connect.getOutputStream());
        gos.write(w.toString().getBytes());
        gos.flush();
        gos.close();

        int code = connect.getResponseCode();
        try {
            if (code == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                continue;
            } else if (code != HttpStatus.SC_OK) {
                Log.i(getName(), SyncHelper.parse(new GZIPInputStream(connect.getErrorStream())).toString());
                status = Status.ERROR;
                break;
            } else {
                Log.i(getName(), SyncHelper.parse(new GZIPInputStream(connect.getInputStream())).toString());
                status = Status.OK;
                break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            connect.disconnect();
        }
    }
    return status;
}

From source file:org.openmrs.module.odkconnector.serialization.serializer.openmrs.CohortSerializerTest.java

@Test
public void serialize_shouldSerializeCohortInformation() throws Exception {

    CohortService cohortService = Context.getCohortService();

    Cohort firstCohort = new Cohort();
    firstCohort.addMember(6);/*  ww w .j  a  va  2 s.  c  o m*/
    firstCohort.addMember(7);
    firstCohort.addMember(8);
    firstCohort.setName("First Cohort");
    firstCohort.setDescription("First cohort for testing the serializer");
    cohortService.saveCohort(firstCohort);

    Cohort secondCohort = new Cohort();
    secondCohort.addMember(6);
    secondCohort.addMember(7);
    secondCohort.addMember(8);
    secondCohort.setName("Second Cohort");
    secondCohort.setDescription("Second cohort for testing the serializer");
    cohortService.saveCohort(secondCohort);

    File file = File.createTempFile("CohortSerialization", "Example");
    GZIPOutputStream outputStream = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(file)));

    List<Cohort> cohorts = cohortService.getAllCohorts();
    Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, List.class);
    serializer.write(outputStream, cohorts);

    outputStream.close();

    GZIPInputStream inputStream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file)));
    DataInputStream dataInputStream = new DataInputStream(inputStream);

    Integer cohortCounts = dataInputStream.readInt();
    System.out.println("Number of cohorts: " + cohortCounts);

    for (int i = 0; i < cohortCounts; i++) {
        System.out.println("Cohort ID: " + dataInputStream.readInt());
        System.out.println("Cohort Name: " + dataInputStream.readUTF());
    }

    inputStream.close();
}

From source file:edu.cornell.med.icb.goby.alignments.UpgradeTo1_9_8_2.java

private void upgradeHeaderVersion(String basename) throws IOException {
    InputStream headerStream;/*from w  ww  . j  a  v  a  2 s  .  c o m*/
    try {
        headerStream = new GZIPInputStream(new FileInputStream(basename + ".header"));
    } catch (IOException e) {
        // try not compressed for compatibility with 1.4-:
        LOG.trace("falling back to legacy 1.4- uncompressed header.");

        headerStream = new FileInputStream(basename + ".header");
    }
    // accept very large header messages, since these may contain query identifiers:
    final CodedInputStream codedInput = CodedInputStream.newInstance(headerStream);
    codedInput.setSizeLimit(Integer.MAX_VALUE);
    final Alignments.AlignmentHeader header = Alignments.AlignmentHeader.parseFrom(codedInput);

    Alignments.AlignmentHeader.Builder upgradedHeader = Alignments.AlignmentHeader.newBuilder(header);
    upgradedHeader.setVersion(VersionUtils.getImplementationVersion(UpgradeTo1_9_8_2.class));
    FileUtils.moveFile(new File(basename + ".header"),
            new File(makeBackFilename(basename + ".header", ".bak")));
    GZIPOutputStream headerOutput = new GZIPOutputStream(new FileOutputStream(basename + ".header"));
    try {
        upgradedHeader.build().writeTo(headerOutput);
    } finally {
        headerOutput.close();
    }
}

From source file:com.github.jasonruckman.gzip.AbstractBenchmark.java

private void initializeJackson() {
    try {/*  w w  w. java2  s. c o  m*/
        ObjectMapper mapper = new ObjectMapper();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzos = new GZIPOutputStream(baos);
        mapper.writeValue(gzos, sampleData);
        gzos.close();
        serializedJacksonData = baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}