Example usage for java.util.zip GZIPInputStream GZIPInputStream

List of usage examples for java.util.zip GZIPInputStream GZIPInputStream

Introduction

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

Prototype

public GZIPInputStream(InputStream in) throws IOException 

Source Link

Document

Creates a new input stream with a default buffer size.

Usage

From source file:com.opengamma.web.analytics.json.Compressor.java

static void decompressStream(InputStream inputStream, OutputStream outputStream)
        throws IOException {
    @SuppressWarnings("resource")
    InputStream iStream = new GZIPInputStream(
            new Base64InputStream(new BufferedInputStream(inputStream), false, -1, null));
    OutputStream oStream = new BufferedOutputStream(outputStream);
    byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = iStream.read(buffer)) != -1) {
        oStream.write(buffer, 0, bytesRead);
    }/*from  w w w  .ja va  2s . co m*/
    oStream.flush();
}

From source file:sample.jetty.SampleJettyApplicationTests.java

@Test
public void testCompression() throws Exception {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Accept-Encoding", "gzip");
    HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

    ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity,
            byte[].class);

    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);

    GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody()));
    try {/*from w  ww .  j  a v a2 s . c  o  m*/
        //         assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))).isEqualTo("Hello World");
    } finally {
        inflater.close();
    }
}

From source file:uk.ac.ebi.eva.pipeline.io.readers.AnnotationFlatFileReaderTest.java

@Test
public void shouldReadAllLinesInVepOutput() throws Exception {
    ExecutionContext executionContext = MetaDataInstanceFactory.createStepExecution().getExecutionContext();

    //simulate VEP output file
    File file = JobTestUtils.makeGzipFile(VepOutputContent.vepOutputContent);

    AnnotationFlatFileReader annotationFlatFileReader = new AnnotationFlatFileReader(file);
    annotationFlatFileReader.setSaveState(false);
    annotationFlatFileReader.open(executionContext);

    VariantAnnotation variantAnnotation;
    int consequenceTypeCount = 0;
    int count = 0;
    while ((variantAnnotation = annotationFlatFileReader.read()) != null) {
        count++;//from  w  w  w .ja  va2s  . c  om
        if (variantAnnotation.getConsequenceTypes() != null
                && !variantAnnotation.getConsequenceTypes().isEmpty()) {
            consequenceTypeCount++;
        }
    }
    // all should have at least consequence type annotations
    assertEquals(count, consequenceTypeCount);

    // annotationFlatFileReader should get all the lines from the file
    long actualCount = JobTestUtils.getLines(new GZIPInputStream(new FileInputStream(file)));
    assertEquals(actualCount, count);
}

From source file:com.yoncabt.ebr.logger.fs.FileSystemReportLogger.java

@Override
public byte[] getReportData(String uuid) throws IOException {
    //burada sktrma zellii akken kpatlm olabilir diye kontrol yapyorum
    File saveDir = new File(EBRConf.INSTANCE.getValue(EBRParams.REPORT_LOGGER_FSLOGGER_PATH, "/tmp"));
    File reportFile = new File(saveDir, uuid + ".gz");
    if (reportFile.exists()) {
        try (FileInputStream fis = new FileInputStream(reportFile);
                GZIPInputStream gzis = new GZIPInputStream(fis);) {
            return IOUtils.toByteArray(gzis);
        }//w w  w  .  j a  v  a  2  s  .c  o m
    } else {
        reportFile = new File(saveDir, uuid);
        try (FileInputStream fis = new FileInputStream(reportFile)) {
            return IOUtils.toByteArray(fis);
        }
    }
}

From source file:it.unifi.rcl.chess.traceanalysis.Trace.java

public Trace(File file) {
    this();/* w ww .j a  va 2  s. co m*/
    name = file.getAbsolutePath();

    try {
        InputStream is = new FileInputStream(file);
        // check if the file is compressed with gzip
        boolean isZipped = Trace.checkGZIP(is);
        is.close();

        is = new FileInputStream(file);
        if (isZipped) {
            is = new GZIPInputStream(is);
        }

        loadFromStream(is);

        is.close();
    } catch (IOException e) {
        System.out.println(e);
    }
}

From source file:ezbake.deployer.utilities.Utilities.java

public static void appendFilesInTarArchive(OutputStream output, byte[] currentArchive,
        Iterable<ArtifactDataEntry> filesToAdd) throws DeploymentException {
    ArchiveStreamFactory asf = new ArchiveStreamFactory();

    try (GZIPOutputStream gzs = new GZIPOutputStream(output)) {
        try (ArchiveOutputStream aos = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, gzs)) {
            try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(currentArchive))) {
                try (TarArchiveInputStream tarInputStream = new TarArchiveInputStream(gzip)) {
                    TarArchiveEntry tarEntry = null;

                    while ((tarEntry = tarInputStream.getNextTarEntry()) != null) {
                        aos.putArchiveEntry(tarEntry);
                        IOUtils.copy(tarInputStream, aos);
                        aos.closeArchiveEntry();
                    }//from w  w  w.  ja  va  2 s  .c om
                }
            }

            for (ArtifactDataEntry entry : filesToAdd) {
                aos.putArchiveEntry(entry.getEntry());
                IOUtils.write(entry.getData(), aos);
                aos.closeArchiveEntry();
            }
        }
    } catch (ArchiveException e) {
        log.error(e.getMessage(), e);
        throw new DeploymentException(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new DeploymentException(e.getMessage());
    }
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingHttpClient(String URL, JSONObject jsonObjSend) {

    try {//from   ww w  .j av a  2s.co  m
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 60 * 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 60 * 1000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        //httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        //httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        Log.d(TAG, "httpPostReuest = " + httpPostRequest.toString());
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        Log.d(TAG, "catch block");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    Log.d(TAG, "SendHttpPostUsingHttpClient returning null");
    return null;
}

From source file:edu.stanford.muse.index.NER.java

public static void readLocationsFreebase() throws IOException {
    InputStream is = new GZIPInputStream(NER.class.getClassLoader().getResourceAsStream("locations.gz"));
    LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is, "UTF-8"));
    while (true) {
        String line = lnr.readLine();
        if (line == null)
            break;
        StringTokenizer st = new StringTokenizer(line, "\t");
        if (st.countTokens() == 3) {
            String locationName = st.nextToken();
            String canonicalName = locationName.toLowerCase();
            String lat = st.nextToken();
            String longi = st.nextToken();
            locations.put(canonicalName, new LocationInfo(locationName, lat, longi));
        }/*from w ww  .j a  va2  s  . co  m*/
    }
    lnr.close();
}

From source file:net.solarnetwork.util.test.JavaBeanXmlSerializerTest.java

@Test
public void testParseSimpleEncoded() throws IOException {
    JavaBeanXmlSerializer helper = new JavaBeanXmlSerializer();
    InputStream in = new GZIPInputStream(new Base64InputStream(getClass().getResourceAsStream("test1.b64")));
    Map<String, Object> result = helper.parseXml(in);
    assertNotNull(result);//w  ww . j  a  v  a  2  s .  co m
    assertEquals(4, result.size());
    assertEquals("23466f06", result.get("confirmationKey"));
    assertEquals("2011-09-16T05:07:32.579Z", result.get("expiration"));
    assertEquals("123123", result.get("nodeId"));
    assertEquals("foo@localhost", result.get("username"));
}

From source file:edu.illinois.cs.cogcomp.core.datastructures.Lexicon.java

public Lexicon(InputStream in, boolean loadStrings) throws IOException {
    GZIPInputStream zipin = new GZIPInputStream(in);

    BufferedReader reader = new BufferedReader(new InputStreamReader(zipin));

    String line;//from w  w  w .  j a  va2  s  .c om

    long start = System.currentTimeMillis();
    line = reader.readLine().trim();

    if (!line.equals(lexManagerVersion))
        throw new IOException("Invalid file. Looking for a lexicon " + "written by lexicon manger version "
                + lexManagerVersion);

    nextFeatureId = readInt(reader);

    int n = readInt(reader);

    feature2Id = new TIntIntHashMap(n + 1);

    for (int i = 0; i < n; i++) {
        int featureHash = readInt(reader);
        int featureId = readInt(reader);

        feature2Id.put(featureHash, featureId);

    }

    log.info("Found {} features", feature2Id.size());

    if (loadStrings) {
        featureNames = new ArrayList<>();
        int nStrings = readInt(reader);
        for (int i = 0; i < nStrings; i++) {
            featureNames.add(reader.readLine().trim());
        }
    } else {
        featureNames = null;
    }

    reader.close();

    long end = System.currentTimeMillis();

    log.info("Loading lexicon took {} ms", (end - start));

    featureCounts = new TIntIntHashMap();
}