Example usage for java.util.zip GZIPInputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:org.onebusaway.util.FileUtility.java

/**
 * Ungzip an input file into an output file.
 * <p>//  w  w  w  .  jav a  2  s  .c om
 * The output file is created in the output folder, having the same name as
 * the input file, minus the '.gz' extension.
 * 
 * @param inputFile the input .gz file
 * @param outputDir the output directory file.
 * @throws IOException
 * @throws FileNotFoundException
 * 
 * @return The {@File} with the ungzipped content.
 */
public File unGzip(final File inputFile, final File outputDir) throws FileNotFoundException, IOException {

    _log.info(String.format("Ungzipping %s to dir %s.", inputFile.getAbsolutePath(),
            outputDir.getAbsolutePath()));

    final File outputFile = new File(outputDir,
            inputFile.getName().substring(0, inputFile.getName().length() - 3));

    final GZIPInputStream in = new GZIPInputStream(new FileInputStream(inputFile));
    final FileOutputStream out = new FileOutputStream(outputFile);

    IOUtils.copy(in, out);

    in.close();
    out.close();

    return outputFile;
}

From source file:org.mule.util.compression.GZipCompression.java

/**
 * Used for uncompressing a byte array into a uncompressed byte array using GZIP
 * //from  w  ww. j a v  a2s .  c o m
 * @param bytes An array of bytes to uncompress
 * @return an uncompressed byte array
 * @throws java.io.IOException if it fails to read from a GZIPInputStream
 * @see java.util.zip.GZIPInputStream
 */
public byte[] uncompressByteArray(byte[] bytes) throws IOException {
    // TODO add strict behaviour as option
    if (!isCompressed(bytes)) {
        /*
         * if (strict) { // throw a specific exception here to allow users of
         * this method to // diffientiate between general IOExceptions and an
         * invalid format logger.warn("Data is not of type GZIP compressed." + "
         * The data may not have been compressed in the first place."); throw new
         * CompressionException("Not in GZIP format"); }
         */

        // nothing to uncompress
        if (logger.isDebugEnabled()) {
            logger.debug("Data already uncompressed; doing nothing");
        }
        return bytes;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Uncompressing message of size: " + bytes.length);
    }

    ByteArrayInputStream bais = null;
    GZIPInputStream gzis = null;
    ByteArrayOutputStream baos = null;

    try {
        bais = new ByteArrayInputStream(bytes);
        gzis = new GZIPInputStream(bais);
        baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);

        IOUtils.copy(gzis, baos);
        gzis.close();
        bais.close();

        byte[] uncompressedByteArray = baos.toByteArray();
        baos.close();

        if (logger.isDebugEnabled()) {
            logger.debug("Uncompressed message to size: " + uncompressedByteArray.length);
        }

        return uncompressedByteArray;
    } catch (IOException ioex) {
        throw ioex;
    } finally {
        IOUtils.closeQuietly(gzis);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(baos);
    }
}

From source file:org.pentaho.di.www.SlaveServerJobStatus.java

public SlaveServerJobStatus(Node jobStatusNode) throws KettleException {
    this();//from www .  ja v  a  2 s  .  c o m
    jobName = XMLHandler.getTagValue(jobStatusNode, "jobname");
    id = XMLHandler.getTagValue(jobStatusNode, "id");
    statusDescription = XMLHandler.getTagValue(jobStatusNode, "status_desc");
    errorDescription = XMLHandler.getTagValue(jobStatusNode, "error_desc");

    firstLoggingLineNr = Const.toInt(XMLHandler.getTagValue(jobStatusNode, "first_log_line_nr"), 0);
    lastLoggingLineNr = Const.toInt(XMLHandler.getTagValue(jobStatusNode, "last_log_line_nr"), 0);

    String loggingString64 = XMLHandler.getTagValue(jobStatusNode, "logging_string");

    // This is a Base64 encoded GZIP compressed stream of data.
    //
    try {
        byte[] bytes = new byte[] {};
        if (loggingString64 != null)
            bytes = Base64.decodeBase64(loggingString64.getBytes());
        if (bytes.length > 0) {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            GZIPInputStream gzip = new GZIPInputStream(bais);
            int c;
            StringBuffer buffer = new StringBuffer();
            while ((c = gzip.read()) != -1)
                buffer.append((char) c);
            gzip.close();
            loggingString = buffer.toString();
        } else {
            loggingString = "";
        }
    } catch (IOException e) {
        loggingString = "Unable to decode logging from remote server : " + e.toString() + Const.CR
                + Const.getStackTracker(e) + Const.CR;
    }

    // get the result object, if there is any...
    //
    Node resultNode = XMLHandler.getSubNode(jobStatusNode, Result.XML_TAG);
    if (resultNode != null) {
        try {
            result = new Result(resultNode);
        } catch (KettleException e) {
            loggingString += "Unable to serialize result object as XML" + Const.CR + Const.getStackTracker(e)
                    + Const.CR;
        }
    }
}

From source file:org.onebusaway.webapp.actions.admin.bundles.SyncBundleAction.java

private void unzipBundle(String tmpDir, String bundleFileName) throws IOException {
    byte[] buffer = new byte[1024];

    GZIPInputStream zipIn = new GZIPInputStream(new FileInputStream(tmpDir + File.separator + bundleFileName));
    FileOutputStream out = new FileOutputStream(tmpDir + File.separator + "unzippedBundle");

    int len;/*  ww  w .j a v a2 s .co  m*/
    while ((len = zipIn.read(buffer)) > 0) {
        out.write(buffer, 0, len);
    }

    zipIn.close();
    out.close();

    // Now to untar the unzipped file
    File tarFile = new File(tmpDir + File.separator + "unzippedBundle");
    File untarredFile = new File(tmpDir + File.separator + "untarredBundle");
    //File untarredFile = new File(tmpDir);
    try {
        List<File> fileList = (new FileUtility()).unTar(tarFile, untarredFile);
    } catch (ArchiveException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return;
}

From source file:android.tether.system.WebserviceTask.java

public boolean downloadBluetoothModule(String downloadFileUrl, String destinationFilename) {
    if (android.os.Environment.getExternalStorageState()
            .equals(android.os.Environment.MEDIA_MOUNTED) == false) {
        return false;
    }/*from w  w w  .  j  a va2 s .c  o  m*/
    File bluetoothDir = new File(BLUETOOTH_FILEPATH);
    if (bluetoothDir.exists() == false) {
        bluetoothDir.mkdirs();
    }
    if (this.downloadFile(downloadFileUrl, "", destinationFilename) == true) {
        try {
            FileOutputStream out = new FileOutputStream(new File(destinationFilename.replace(".gz", "")));
            FileInputStream fis = new FileInputStream(destinationFilename);
            GZIPInputStream gzin = new GZIPInputStream(new BufferedInputStream(fis));
            int count;
            byte buf[] = new byte[8192];
            while ((count = gzin.read(buf, 0, 8192)) != -1) {
                //System.out.write(x);
                out.write(buf, 0, count);
            }
            out.flush();
            out.close();
            gzin.close();
            File inputFile = new File(destinationFilename);
            inputFile.delete();
        } catch (IOException e) {
            return false;
        }
        return true;
    } else
        return false;
}

From source file:com.panet.imeta.www.SlaveServerTransStatus.java

public SlaveServerTransStatus(Node transStatusNode) {
    this();//from w w w .  j  a  va  2s. c o m
    transName = XMLHandler.getTagValue(transStatusNode, "transname");
    statusDescription = XMLHandler.getTagValue(transStatusNode, "status_desc");
    errorDescription = XMLHandler.getTagValue(transStatusNode, "error_desc");
    paused = "Y".equalsIgnoreCase(XMLHandler.getTagValue(transStatusNode, "paused"));

    Node statusListNode = XMLHandler.getSubNode(transStatusNode, "stepstatuslist");
    int nr = XMLHandler.countNodes(statusListNode, StepStatus.XML_TAG);
    for (int i = 0; i < nr; i++) {
        Node stepStatusNode = XMLHandler.getSubNodeByNr(statusListNode, StepStatus.XML_TAG, i);
        StepStatus stepStatus = new StepStatus(stepStatusNode);
        stepStatusList.add(stepStatus);
    }

    String loggingString64 = XMLHandler.getTagValue(transStatusNode, "logging_string");
    // This is a Base64 encoded GZIP compressed stream of data.
    try {
        byte[] bytes = new byte[] {};
        if (loggingString64 != null)
            bytes = Base64.decodeBase64(loggingString64.getBytes());
        if (bytes.length > 0) {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            GZIPInputStream gzip = new GZIPInputStream(bais);
            int c;
            StringBuffer buffer = new StringBuffer();
            while ((c = gzip.read()) != -1)
                buffer.append((char) c);
            gzip.close();
            loggingString = buffer.toString();
        } else {
            loggingString = "";
        }
    } catch (IOException e) {
        loggingString = "Unable to decode logging from remote server : " + e.toString() + Const.CR
                + Const.getStackTracker(e);
    }

    // get the result object, if there is any...
    //
    Node resultNode = XMLHandler.getSubNode(transStatusNode, Result.XML_TAG);
    if (resultNode != null) {
        try {
            result = new Result(resultNode);
        } catch (IOException e) {
            loggingString += "Unable to serialize result object as XML" + Const.CR + Const.getStackTracker(e)
                    + Const.CR;
        }
    }
}

From source file:com.android.tradefed.util.FileUtil.java

public static void extractGzip(File tarGzipFile, File destDir, String destName)
        throws FileNotFoundException, IOException, ArchiveException {
    GZIPInputStream zipIn = null;
    BufferedOutputStream buffOut = null;
    try {/*from  w w  w .  ja va2s . com*/
        File destUnzipFile = new File(destDir.getAbsolutePath(), destName);
        zipIn = new GZIPInputStream(new FileInputStream(tarGzipFile));
        buffOut = new BufferedOutputStream(new FileOutputStream(destUnzipFile));
        int b = 0;
        byte[] buf = new byte[8192];
        while ((b = zipIn.read(buf)) != -1) {
            buffOut.write(buf, 0, b);
        }
    } finally {
        if (zipIn != null)
            zipIn.close();
        if (buffOut != null)
            buffOut.close();
    }
}

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

/**
 * Decompress given GZIP Stream. Separated from {@link eu.domibus.ebms3.common.CompressionService#compress(java.io.InputStream, java.util.zip.GZIPOutputStream)}
 * just for a better overview even though they share the same logic (except finish() ).
 *
 * @param sourceStream Stream of compressed data
 * @param targetStream Stream of uncompressed data
 * @throws IOException//from   w ww  .  j  ava2s  .c o  m
 */
private void decompress(final GZIPInputStream sourceStream, final OutputStream 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.close();

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

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.ArchiveCompressorTarGzImplFastTest.java

@Test
public void testCompress() throws IOException {

    TarInputStream tin = null;//from  w w  w.  j  av a2s. c om

    try {
        String testDir = SAMPLE_DIR + "qclive/compression/tarGz/";
        File file1 = new File(testDir + "file1.txt");
        File file2 = new File(testDir + "file2.txt");
        File file3 = new File(testDir + "file3.txt");
        List<File> files = new ArrayList<File>();
        files.add(file1);
        files.add(file2);
        files.add(file3);
        // pass in a list of files and verify that a tar.gz file is made
        ArchiveCompressor compressor = new ArchiveCompressorTarGzImpl();
        String archiveName = "test";
        File createdFile = compressor.createArchive(files, archiveName, new File(testDir), true);
        File testFile = new File(testDir + File.separator + archiveName + compressor.getExtension());
        assertEquals(testFile.getCanonicalPath(), createdFile.getCanonicalPath());
        assertTrue(testFile.exists());
        // look at tar entries and make sure expected files are there, with just
        // archive name as the path
        GZIPInputStream gzipStream = new GZIPInputStream(new FileInputStream(testFile));
        //noinspection IOResourceOpenedButNotSafelyClosed
        tin = new TarInputStream(gzipStream);
        List<String> tarEntryNames = new ArrayList<String>();
        TarEntry tarEntry;
        while ((tarEntry = tin.getNextEntry()) != null) {
            tarEntryNames.add(tarEntry.getName());
        }
        tin.close();
        gzipStream.close();
        assertTrue(tarEntryNames.contains(archiveName + File.separator + "file1.txt"));
        assertTrue(tarEntryNames.contains(archiveName + File.separator + "file2.txt"));
        assertTrue(tarEntryNames.contains(archiveName + File.separator + "file2.txt"));
        testFile.deleteOnExit();
    } finally {
        IOUtils.closeQuietly(tin);
    }
}

From source file:open.dolphin.infomodel.JsonConverter.java

public Object fromGzippedJson(InputStream is, Class clazz) {

    GZIPInputStream gis = null;
    try {/* w w w  .  j  a  v  a  2  s  .  c om*/
        gis = new GZIPInputStream(is);
        Object obj = fromJson(gis, clazz);
        return obj;
    } catch (IOException ex) {
        processException(ex);
    } finally {
        try {
            if (gis != null) {
                gis.close();
            }
        } catch (IOException ex) {
        }
    }
    return null;
}