Example usage for java.util.zip GZIPInputStream read

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

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:Base64.java

/**
 * Decodes data from Base64 notation, automatically
 * detecting gzip-compressed data and decompressing it.
 *
 * @param s the string to decode//  w w w.j a  v  a  2 s  . c o m
 * @return the decoded data
 * @since 1.4
 */
public static byte[] decode(String s) {
    byte[] bytes;
    try {
        bytes = s.getBytes(PREFERRED_ENCODING);
    } // end try
    catch (java.io.UnsupportedEncodingException uee) {
        bytes = s.getBytes();
    } // end catch
    //</change>

    // Decode
    bytes = decode(bytes, 0, bytes.length);

    // Check to see if it's gzip-compressed
    // GZIP Magic Two-Byte Number: 0x8b1f (35615)
    if (bytes != null && bytes.length >= 4) {

        int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
        if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) {
            java.io.ByteArrayInputStream bais = null;
            java.util.zip.GZIPInputStream gzis = null;
            java.io.ByteArrayOutputStream baos = null;
            byte[] buffer = new byte[2048];
            int length = 0;

            try {
                baos = new java.io.ByteArrayOutputStream();
                bais = new java.io.ByteArrayInputStream(bytes);
                gzis = new java.util.zip.GZIPInputStream(bais);

                while ((length = gzis.read(buffer)) >= 0) {
                    baos.write(buffer, 0, length);
                } // end while: reading input

                // No error? Get new bytes.
                bytes = baos.toByteArray();

            } // end try
            catch (java.io.IOException e) {
                // Just return originally-decoded bytes
            } // end catch
            finally {
                try {
                    baos.close();
                } catch (Exception e) {
                }
                try {
                    gzis.close();
                } catch (Exception e) {
                }
                try {
                    bais.close();
                } catch (Exception e) {
                }
            } // end finally

        } // end if: gzipped
    } // end if: bytes.length >= 2

    return bytes;
}

From source file:com.github.tomakehurst.wiremock.StandaloneAcceptanceTest.java

/**
 * Decompress the binary gzipped content into a String.
 *
 * @param content the gzipped content to decompress
 * @return decompressed String./*from w  w  w .  j  av a2  s.  c  om*/
 */
private String decompress(byte[] content) {
    GZIPInputStream gin = null;
    try {
        gin = new GZIPInputStream(new ByteArrayInputStream(content));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buf = new byte[8192];

        int read = -1;
        while ((read = gin.read(buf)) != -1) {
            baos.write(buf, 0, read);
        }

        return new String(baos.toByteArray(), Charset.forName(UTF_8.name()));

    } catch (IOException e) {
        return null;
    } finally {
        if (gin != null)
            try {
                gin.close();
            } catch (IOException e) {

            }
    }
}

From source file:com.csipsimple.service.DownloadLibService.java

private boolean installRemoteLib(RemoteLibInfo lib) {
    String fileName = lib.getFileName();
    File filePath = lib.getFilePath();

    File tmp_gz = new File(filePath, fileName + ".gz");
    File dest = new File(filePath, fileName);

    try {//from   w ww.  j a  v  a  2  s  .  c  o m
        if (dest.exists()) {
            dest.delete();
        }
        RandomAccessFile out = new RandomAccessFile(dest, "rw");
        out.seek(0);
        GZIPInputStream zis = new GZIPInputStream(new FileInputStream(tmp_gz));
        int len;
        byte[] buf = new byte[BUFFER];
        while ((len = zis.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        zis.close();
        out.close();
        Log.d(THIS_FILE, "Ungzip is in : " + dest.getAbsolutePath());
        tmp_gz.delete();
        //Update preferences fields with current stack values
        Editor editor = prefs.edit();
        editor.putString(CURRENT_STACK_ID, lib.getId());
        editor.putString(CURRENT_STACK_VERSION, lib.getVersion());
        editor.putString(CURRENT_STACK_URI, lib.getDownloadUri().toString());
        editor.commit();
        return true;
    } catch (IOException e) {
        Log.e(THIS_FILE, "We failed to install it ", e);
    }
    return false;
}

From source file:Base64.java

/**
 * Decodes data from Base64 notation, automatically
 * detecting gzip-compressed data and decompressing it.
 *
 * @param s the string to decode//from   www  .j  av  a  2 s.c o m
 * @return the decoded data
 * @since 1.4
 */
public static byte[] decode(String s) {
    byte[] bytes;
    try {
        bytes = s.getBytes(PREFERRED_ENCODING);
    } // end try
    catch (java.io.UnsupportedEncodingException uee) {
        bytes = s.getBytes();
    } // end catch
      //</change>

    // Decode
    bytes = decode(bytes, 0, bytes.length);

    // Check to see if it's gzip-compressed
    // GZIP Magic Two-Byte Number: 0x8b1f (35615)
    if (bytes != null && bytes.length >= 4) {

        int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
        if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) {
            java.io.ByteArrayInputStream bais = null;
            java.util.zip.GZIPInputStream gzis = null;
            java.io.ByteArrayOutputStream baos = null;
            byte[] buffer = new byte[2048];
            int length = 0;

            try {
                baos = new java.io.ByteArrayOutputStream();
                bais = new java.io.ByteArrayInputStream(bytes);
                gzis = new java.util.zip.GZIPInputStream(bais);

                while ((length = gzis.read(buffer)) >= 0) {
                    baos.write(buffer, 0, length);
                } // end while: reading input

                // No error? Get new bytes.
                bytes = baos.toByteArray();

            } // end try
            catch (java.io.IOException e) {
                // Just return originally-decoded bytes
            } // end catch
            finally {
                try {
                    baos.close();
                } catch (Exception e) {
                }
                try {
                    gzis.close();
                } catch (Exception e) {
                }
                try {
                    bais.close();
                } catch (Exception e) {
                }
            } // end finally

        } // end if: gzipped
    } // end if: bytes.length >= 2

    return bytes;
}

From source file:com.ning.http.client.async.MultipartUploadTest.java

/**
 * Test that the files were sent, based on the response from the servlet
 *
 * @param expectedContents//from  w  w w.  j a v a2  s  .  c  om
 * @param sourceFiles
 * @param r
 * @param deflate
 */
private void testSentFile(List<String> expectedContents, List<File> sourceFiles, Response r,
        List<Boolean> deflate) {
    String content = null;
    try {
        content = r.getResponseBody();
        assertNotNull("===>" + content);
        System.out.println(content);
    } catch (IOException e) {
        fail("Unable to obtain content");
    }

    String[] contentArray = content.split("\\|\\|");
    // TODO: this fail on win32
    assertEquals(2, contentArray.length);

    String tmpFiles = contentArray[1];
    assertNotNull(tmpFiles);
    assertTrue(tmpFiles.trim().length() > 2);
    tmpFiles = tmpFiles.substring(1, tmpFiles.length() - 1);

    String[] responseFiles = tmpFiles.split(",");
    assertNotNull(responseFiles);
    assertEquals(sourceFiles.size(), responseFiles.length);

    System.out.println(Arrays.toString(responseFiles));
    //assertTrue("File should exist: " + tmpFile.getAbsolutePath(),tmpFile.exists());

    int i = 0;
    for (File sourceFile : sourceFiles) {

        FileInputStream instream = null;
        File tmp = null;
        try {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] sourceBytes = null;
            try {
                instream = new FileInputStream(sourceFile);
                byte[] buf = new byte[8092];
                int len = 0;
                while ((len = instream.read(buf)) > 0) {
                    baos.write(buf, 0, len);
                }
                System.out.println("================");
                System.out.println("Length of file: " + baos.toByteArray().length);
                System.out.println("Contents: " + Arrays.toString(baos.toByteArray()));
                System.out.println("================");
                System.out.flush();
                sourceBytes = baos.toByteArray();
            } finally {
                IOUtils.closeQuietly(instream);
            }

            tmp = new File(responseFiles[i].trim());
            System.out.println("==============================");
            System.out.println(tmp.getAbsolutePath());
            System.out.println("==============================");
            System.out.flush();
            assertTrue(tmp.exists());

            instream = new FileInputStream(tmp);
            ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
            byte[] buf = new byte[8092];
            int len = 0;
            while ((len = instream.read(buf)) > 0) {
                baos2.write(buf, 0, len);
            }
            IOUtils.closeQuietly(instream);

            assertEquals(sourceBytes, baos2.toByteArray());

            if (!deflate.get(i)) {

                String helloString = new String(baos2.toByteArray());
                assertEquals(expectedContents.get(i), helloString);
            } else {
                instream = new FileInputStream(tmp);

                GZIPInputStream deflater = new GZIPInputStream(instream);
                ByteArrayOutputStream baos3 = new ByteArrayOutputStream();
                byte[] buf3 = new byte[8092];
                int len3 = 0;
                while ((len3 = deflater.read(buf3)) > 0) {
                    baos3.write(buf3, 0, len3);
                }

                String helloString = new String(baos3.toByteArray());

                assertEquals(expectedContents.get(i), helloString);

            }
        } catch (Exception e) {
            e.printStackTrace();
            fail("Download Exception");
        } finally {
            if (tmp != null)
                FileUtils.deleteQuietly(tmp);
            IOUtils.closeQuietly(instream);
            i++;
        }
    }
}

From source file:fr.gouv.finances.cp.xemelios.importers.batch.BatchRealImporter.java

private ImportContent files(final String extension, final String titreEtat) {
    ImportContent ic = new ImportContent();
    Vector<File> ret = new Vector<File>();
    ret.addAll(files);/*ww w.j av  a  2  s . c  o  m*/
    // on regarde si l'un des fichiers a importer est un zip
    for (int i = 0; i < ret.size(); i++) {
        if (ret.get(i).getName().toLowerCase().endsWith(".zip")) {
            if (ret.get(i).exists()) {
                ZipFile zf = null;
                try {
                    zf = new ZipFile(ret.get(i));
                    for (Enumeration<? extends ZipEntry> enumer = zf.entries(); enumer.hasMoreElements();) {
                        ZipEntry ze = enumer.nextElement();
                        if (!ze.isDirectory()) {
                            String fileName = ze.getName();
                            String entryName = fileName.toLowerCase();
                            fileName = fileName.replace(File.pathSeparatorChar, '_')
                                    .replace(File.separatorChar, '_').replace(':', '|').replace('\'', '_')
                                    .replace('/', '_');
                            logger.debug(entryName);
                            if (PJRef.isPJ(ze)) {
                                PJRef pj = new PJRef(ze);
                                File tmpFile = pj.writeTmpFile(FileUtils.getTempDir(), zf);
                                ic.pjs.add(pj);
                                filesToDrop.add(tmpFile);
                            } else if ((entryName.endsWith(extension.toLowerCase())
                                    || entryName.endsWith(".xml")) && !fileName.startsWith("_")) {
                                // on decompresse le fichier dans le
                                // repertoire temporaire, comme ca il sera
                                // supprime en quittant
                                InputStream is = zf.getInputStream(ze);
                                BufferedInputStream bis = new BufferedInputStream(is);
                                File output = new File(FileUtils.getTempDir(), fileName);
                                BufferedOutputStream bos = new BufferedOutputStream(
                                        new FileOutputStream(output));
                                byte[] buffer = new byte[1024];
                                int read = bis.read(buffer);
                                while (read > 0) {
                                    bos.write(buffer, 0, read);
                                    read = bis.read(buffer);
                                }
                                bos.flush();
                                bos.close();
                                bis.close();
                                ic.filesToImport.add(output);
                                filesToDrop.add(output);
                            }
                        }
                    }
                    zf.close();
                } catch (ZipException zEx) {
                    System.out.println(
                            "Le fichier " + ret.get(i).getName() + " n'est pas une archive ZIP valide.");
                } catch (IOException ioEx) {
                    ioEx.printStackTrace();
                } finally {
                    if (zf != null) {
                        try {
                            zf.close();
                        } catch (Throwable t) {
                        }
                    }
                }
            }
        } else if (ret.get(i).getName().toLowerCase().endsWith(".gz")) {
            try {
                String fileName = ret.get(i).getName();
                fileName = fileName.substring(0, fileName.length() - 3);
                File output = new File(FileUtils.getTempDir(), fileName);
                GZIPInputStream gis = new GZIPInputStream(new FileInputStream(ret.get(i)));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output));
                byte[] buffer = new byte[1024];
                int read = gis.read(buffer);
                while (read > 0) {
                    bos.write(buffer, 0, read);
                    read = gis.read(buffer);
                }
                bos.flush();
                bos.close();
                gis.close();
                ic.filesToImport.add(output);
                filesToDrop.add(output);
            } catch (IOException ioEx) {
                // nothing to do
            }
        } else {
            ic.filesToImport.add(ret.get(i));
            // dans ce cas l, on ne le supprime pas
        }
    }
    return ic;
}

From source file:org.opensextant.xtext.collectors.ArchiveNavigator.java

/**
 *
 * @param theFile/*w w  w  .  j a  v a  2  s  .c  o  m*/
 * @param fname
 * @return TAR file path for result.
 * @throws IOException on I/O failure
 */
private File gunzipAsTAR(File theFile, String fname) throws IOException {

    GZIPInputStream gzipInputStream = null;
    OutputStream out = null;

    try {
        gzipInputStream = new GZIPInputStream(new FileInputStream(theFile));
        // TODO:  more testing on this particular case:  gunzip *.gz *.tgz *.tar.gz -- a mix of tar and gunzip
        String outFilename = getWorkingDir() + '/' + fname + ".tar";
        File outFile = new File(outFilename);
        out = new BufferedOutputStream(new FileOutputStream(outFilename));

        byte[] buf = new byte[1024];
        int len;
        while ((len = gzipInputStream.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        return outFile;
    } finally {
        gzipInputStream.close();
        if (out != null) {
            out.close();
        }
    }
}

From source file:agilejson.Base64.java

/**
 * Decodes data from Base64 notation, automatically detecting gzip-compressed
 * data and decompressing it.//www .jav a  2s.co m
 * 
 * @param s the string to decode
 * @param options
 * @see Base64#URL_SAFE
 * @see Base64#ORDERED
 * @return the decoded data
 * @since 1.4
 */
public static byte[] decode(String s, int options) {
    byte[] bytes = null;
    try {
        bytes = s.getBytes(PREFERRED_ENCODING);

    } catch (UnsupportedEncodingException uee) {
        bytes = s.getBytes();
    } // end catch

    // Decode

    bytes = decode(bytes, 0, bytes.length, options);

    // Check to see if it's gzip-compressed
    // GZIP Magic Two-Byte Number: 0x8b1f (35615)

    if (bytes != null && bytes.length >= 4) {
        int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
        if (GZIPInputStream.GZIP_MAGIC == head) {
            GZIPInputStream gzis = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                gzis = new GZIPInputStream(new ByteArrayInputStream(bytes));

                byte[] buffer = new byte[2048];
                for (int length = 0; (length = gzis.read(buffer)) >= 0;) {
                    baos.write(buffer, 0, length);
                } // end while: reading input

                // No error? Get new bytes.
                bytes = baos.toByteArray();

            } catch (IOException e) {
                // Just return originally-decoded bytes

            } finally {
                try {
                    baos.close();
                } catch (Exception e) {
                    LOG.error("error closing ByteArrayOutputStream", e);
                }
                if (gzis != null) {
                    try {
                        gzis.close();
                    } catch (Exception e) {
                        LOG.error("error closing GZIPInputStream", e);
                    }
                }
            } // end finally
        } // end if: gzipped
    } // end if: bytes.length >= 2

    return bytes;
}

From source file:org.apache.hadoop.hbase.util.Base64.java

/**
 * Decodes data from Base64 notation, automatically detecting gzip-compressed
 * data and decompressing it.//from w ww  .  jav  a 2 s.  c  o  m
 *
 * @param s the string to decode
 * @param options options for decode
 * @see Base64#URL_SAFE
 * @see Base64#ORDERED
 * @return the decoded data
 * @since 1.4
 */
public static byte[] decode(String s, int options) {
    byte[] bytes;
    try {
        bytes = s.getBytes(PREFERRED_ENCODING);

    } catch (UnsupportedEncodingException uee) {
        bytes = s.getBytes();
    } // end catch

    // Decode

    bytes = decode(bytes, 0, bytes.length, options);

    // Check to see if it's gzip-compressed
    // GZIP Magic Two-Byte Number: 0x8b1f (35615)

    if (bytes != null && bytes.length >= 4) {
        int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
        if (GZIPInputStream.GZIP_MAGIC == head) {
            GZIPInputStream gzis = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                gzis = new GZIPInputStream(new ByteArrayInputStream(bytes));

                byte[] buffer = new byte[2048];
                for (int length; (length = gzis.read(buffer)) >= 0;) {
                    baos.write(buffer, 0, length);
                } // end while: reading input

                // No error? Get new bytes.
                bytes = baos.toByteArray();

            } catch (IOException e) {
                // Just return originally-decoded bytes

            } finally {
                try {
                    baos.close();
                } catch (Exception e) {
                    LOG.error("error closing ByteArrayOutputStream", e);
                }
                if (gzis != null) {
                    try {
                        gzis.close();
                    } catch (Exception e) {
                        LOG.error("error closing GZIPInputStream", e);
                    }
                }
            } // end finally
        } // end if: gzipped
    } // end if: bytes.length >= 2

    return bytes;
}

From source file:org.opensextant.util.TextUtils.java

/**
 *
 * @param gzData//  ww  w.j av a 2s  . c o m
 *            byte array containing gzipped buffer
 * @param charset
 *            character set decoding for text
 * @return buffer of uncompressed, decoded string
 * @throws IOException
 *             on error with decompression or text encoding
 */
public static String uncompress(byte[] gzData, String charset) throws IOException {
    GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(gzData));
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    byte[] buf = new byte[ONEKB];
    int len;
    while ((len = gzipInputStream.read(buf)) > 0) {
        out.write(buf, 0, len);
    }

    gzipInputStream.close();
    out.close();

    return new String(out.toByteArray(), charset);
}