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:jetbrains.exodus.util.CompressBackupUtilTest.java

@Test
public void testFileArchived() throws Exception {
    File src = new File(randName + ".txt");
    FileWriter fw = new FileWriter(src);
    fw.write("12345");
    fw.close();/*w ww .  j a v  a  2 s  .c  o  m*/
    CompressBackupUtil.tar(src, dest);
    Assert.assertTrue("No destination archive created", dest.exists());
    TarArchiveInputStream tai = new TarArchiveInputStream(
            new GZIPInputStream(new BufferedInputStream(new FileInputStream(dest))));
    ArchiveEntry entry = tai.getNextEntry();
    Assert.assertNotNull("No entry found in destination archive", entry);
    Assert.assertEquals("Entry has wrong size", 5, entry.getSize());
}

From source file:sample.undertow.SampleUndertowApplicationTests.java

@Test
public void testCompression() throws Exception {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Accept-Encoding", "gzip");
    HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
    RestTemplate restTemplate = new TestRestTemplate();
    ResponseEntity<byte[]> entity = restTemplate.exchange("http://localhost:" + this.port, HttpMethod.GET,
            requestEntity, byte[].class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody()));
    try {/*  w  w w  .  j a  va  2  s.co  m*/
        assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))).isEqualTo("Hello World");
    } finally {
        inflater.close();
    }
}

From source file:com.evilco.license.client.decoder.CompressedLicenseDecoder.java

/**
 * {@inheritDoc}/*from  w  w  w.j  av a 2  s .  com*/
 */
@Override
public <T extends ILicense> T decode(@Nonnull String input, @Nonnull Class<T> licenseType)
        throws LicenseDecoderException {
    // define streams
    ByteArrayInputStream inputStream = null;
    GZIPInputStream gzipInputStream = null;
    DataInputStream dataInputStream = null;

    // read data
    try {
        // remove newlines
        input = CharMatcher.anyOf("\n\r").removeFrom(input);

        // decode data
        byte[] data = BaseEncoding.base64().decode(input);

        // create streams
        inputStream = new ByteArrayInputStream(data);
        gzipInputStream = new GZIPInputStream(inputStream);
        dataInputStream = new DataInputStream(gzipInputStream);

        // decode data
        return ((T) this.childDecoder.decode(dataInputStream, licenseType));
    } catch (IOException ex) {
        throw new LicenseDecoderException(ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(dataInputStream);
        IOUtils.closeQuietly(gzipInputStream);
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:nl.opengeogroep.filesetsync.server.stripes.FilesetGetActionBean.java

public Resolution get() throws Exception {

    Iterable<FileRecord> filesToStream;
    if (FILELIST_MIME_TYPE.equals(getContext().getRequest().getContentType())) {

        InputStream in = getContext().getRequest().getInputStream();
        if ("gzip".equals(getContext().getRequest().getHeader(HttpHeaders.CONTENT_ENCODING))) {
            in = new GZIPInputStream(in);
        }//from  w ww .  jav  a2  s .  co  m
        List<FileRecord> requestedFiles = Protocol.decodeFilelist(in);
        long totalSize = 0;
        int unacceptableFiles = 0;
        String canonicalFilesetPath = new File(getFileset().getPath()).getCanonicalPath();
        for (FileRecord fr : requestedFiles) {
            File localFile = new File(getLocalSubPath() + File.separator + fr.getName()).getCanonicalFile();

            if (!localFile.getCanonicalPath().startsWith(canonicalFilesetPath)) {
                unacceptableFiles++;
                log.warn("unacceptable file: not under fileset path: " + fr.getName());
                continue;
            } else if (!localFile.exists()
                    || !((localFile.isFile() && localFile.canRead()) || localFile.isDirectory())) {
                unacceptableFiles++;
                log.warn("unacceptable file: not existing, not a readable file or not a directory: "
                        + fr.getName());
                continue;
            }
            fr.setFile(localFile);
            if (localFile.isFile()) {
                totalSize += localFile.length();
            }
        }
        log.info(
                String.format("streaming %d files (total %.0f KB)%s", requestedFiles.size(), totalSize / 1024.0,
                        unacceptableFiles != 0
                                ? ", removed " + unacceptableFiles + " unacceptable requested files"
                                : ""));
        filesToStream = requestedFiles;
    } else {
        // check if path is single file
        final File f = new File(getLocalSubPath());
        if (f.isFile()) {
            return new StreamingResolution("application/octet-stream", new FileInputStream(f)) {
                @Override
                protected void applyHeaders(HttpServletResponse response) {
                    super.applyHeaders(response);
                    response.setContentLength((int) f.length());
                }
            };
        } else if (!f.isDirectory()) {
            return new ErrorMessageResolution("Error: path is not a file or directory");
        }

        log.info("recursively streaming " + getLocalSubPath());
        filesToStream = FileRecord.getFileRecordsInDir(getLocalSubPath(), null, new MutableInt());
    }

    return new MultiFileStreamingResolution(filesToStream);
}

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

public AlignmentTooManyHitsReader(final String basename) throws IOException {
    final String filename = basename + ".tmh";
    final File optionalFile = new File(filename);

    InputStream tmhStream = null;
    try {/*from  www.  ja  va 2s.  c o  m*/
        if (optionalFile.exists()) {
            try {
                tmhStream = new GZIPInputStream(new FileInputStream(optionalFile));
            } catch (IOException e) {
                // try not compressed for compatibility with 1.6-:
                LOG.trace("falling back to legacy 1.6- uncompressed TMH.");

                tmhStream = new FileInputStream(optionalFile);
            }

            // accept very large too many hits messages, since these may describe more than 60 million reads:
            final CodedInputStream codedInput = CodedInputStream.newInstance(tmhStream);
            codedInput.setSizeLimit(Integer.MAX_VALUE);

            final Alignments.AlignmentTooManyHits tmh = Alignments.AlignmentTooManyHits.parseFrom(codedInput);

            queryIndex2NumHits.defaultReturnValue(-1);
            queryIndex2Depth.defaultReturnValue(-1);
            final List<Alignments.AmbiguousLocation> hitsList = tmh.getHitsList();
            final Iterator<Alignments.AmbiguousLocation> iterator = hitsList.iterator();
            while (iterator.hasNext()) {
                Alignments.AmbiguousLocation hit = iterator.next();
                queryIndex2NumHits.put(hit.getQueryIndex(), hit.getAtLeastNumberOfHits());
                if (hit.hasLengthOfMatch()) {
                    queryIndex2Depth.put(hit.getQueryIndex(), hit.getLengthOfMatch());
                }

            }

            this.alignerThreshold = tmh.getAlignerThreshold();
        } else {

            // the file does not exist. Log this fact, and act as if no query had too many hits.
            LOG.info("basename " + optionalFile + " has no 'too many hits' information (" + basename
                    + ".tmh does not exist)." + " Assuming no queries have too many hits.");
        }
    } finally

    {
        if (tmhStream != null) {
            tmhStream.close();
        }
    }

}

From source file:com.dajodi.scandic.Util.java

public static InputStream ungzip(HttpResponse response) {
    try {//  w w w  .  ja va 2s  .  c o m
        InputStream instream = response.getEntity().getContent();
        Header contentEncoding = response.getFirstHeader("Content-Encoding");

        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
        }
        return instream;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }
}

From source file:com.ery.ertc.estorm.util.GZIPUtils.java

/**
 * Returns an gunzipped copy of the input array.
 * //from  ww w .  j  a v a2s . c o  m
 * @throws IOException
 *             if the input cannot be properly decompressed
 */
public static final byte[] unzip(byte[] in) throws IOException {
    // decompress using GZIPInputStream
    ByteArrayOutputStream outStream = new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);

    GZIPInputStream inStream = new GZIPInputStream(new ByteArrayInputStream(in));

    byte[] buf = new byte[BUF_SIZE];
    while (true) {
        int size = inStream.read(buf);
        if (size <= 0)
            break;
        outStream.write(buf, 0, size);
    }
    outStream.close();

    return outStream.toByteArray();
}

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

public static InputStream createCompressionInputStream(String alg, byte[] content) throws Exception {
    checkAlg(alg);/*  ww  w .j a v  a 2 s.  co  m*/
    ByteArrayInputStream bais = new ByteArrayInputStream(content);
    if (ALG_GZIP.equals(alg)) {
        return new GZIPInputStream(bais);
    } else if (ALG_DEFLATE.equals(alg)) {
        return new InflaterInputStream(bais);
    } else {
        return null;
    }
}

From source file:imdbplugin.ImdbParser.java

public void startParsing(final ProgressMonitor monitor) throws IOException {
    int ratingCount = 0;
    mDatabase.deleteDatabase();//from  w ww.j av a  2  s.  c  o  m

    monitor.setMaximum(getFileSize(mServer));

    mRunParser = true;

    BufferedInputStream akaFile = downloadFile(monitor, "aka-titles.list.gz");
    BufferedInputStream ratingsFile = downloadFile(monitor, "ratings.list.gz");

    ProgressInputStream progressInputStream = new ProgressInputStream(akaFile, monitor);

    if (mRunParser) {
        parseAkaTitles(new GZIPInputStream(progressInputStream), monitor);
    }
    mDatabase.close();
    if (mRunParser) {
        mDatabase.openForWriting();
        progressInputStream = new ProgressInputStream(ratingsFile, monitor,
                progressInputStream.getCurrentPosition());
        ratingCount = parseRatings(new GZIPInputStream(progressInputStream), monitor);
    }

    if (mRunParser) {
        optimizeDatabase(monitor);
        ImdbPlugin.getInstance().setCurrentDatabaseVersion(ratingCount);
    } else {
        // Cancel was pressed, all Files have to be deleted
        mDatabase.deleteDatabase();
    }
    mDatabase.openForReading();
}

From source file:aot.util.IOUtil.java

public static byte[] decompress(byte[] data, int offset, int length) {
    try (ByteArrayInputStream buffer = new ByteArrayInputStream(data)) {
        try (GZIPInputStream input = new GZIPInputStream(buffer)) {
            return null;
        }//from  ww w . j a va  2  s. co m
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}