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:lucee.commons.io.compress.CompressUtil.java

private static void extractGZip(Resource source, Resource target) throws IOException {
    InputStream is = null;//w  ww .j  a v  a 2s  .c  om
    OutputStream os = null;
    try {
        is = new GZIPInputStream(IOUtil.toBufferedInputStream(source.getInputStream()));
        os = IOUtil.toBufferedOutputStream(target.getOutputStream());
        IOUtil.copy(is, os, false, false);
    } finally {
        IOUtil.closeEL(is, os);
    }
}

From source file:cc.creativecomputing.io.CCIOUtil.java

static public InputStream openStream(final String theFileName) {
    InputStream myResult = createStream(theFileName);

    if (myResult == null)
        throw new CCIOException("Could not open the given file:" + theFileName);
    String myExtension = fileExtension(theFileName);
    try {//from   w w  w  .j ava  2  s .c  o  m
        if (myExtension.equals("bz2")) {
            int first = myResult.read();
            int second = myResult.read();
            if (first != 'B' || second != 'Z')
                throw new RuntimeException("Didn't find BZ file signature in .bz2 file");
            return new CBZip2InputStream(myResult);
        }
        if (myExtension.equals("gz"))
            return new GZIPInputStream(myResult);

        return myResult;
    } catch (Exception e) {
        throw new RuntimeException("Could not open the given file:" + theFileName, e);
    }
}

From source file:net.solarnetwork.node.support.HttpClientSupport.java

/**
 * Get an InputStream from a URLConnection response, handling compression.
 * /*w  ww . j  a va2  s .c  om*/
 * <p>
 * This method handles decompressing the response if the encoding is set to
 * {@code gzip} or {@code deflate}.
 * </p>
 * 
 * @param conn
 *        the URLConnection
 * @return the InputStream
 * @throws IOException
 *         if any IO error occurs
 */
protected InputStream getInputStreamFromURLConnection(URLConnection conn) throws IOException {
    String enc = conn.getContentEncoding();
    String type = conn.getContentType();

    if (conn instanceof HttpURLConnection) {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        if (httpConn.getResponseCode() < 200 || httpConn.getResponseCode() > 299) {
            log.info("Non-200 HTTP response from {}: {}", conn.getURL(), httpConn.getResponseCode());
        }
    }

    log.trace("Got content type [{}] encoded as [{}]", type, enc);

    InputStream is = conn.getInputStream();
    if ("gzip".equalsIgnoreCase(enc)) {
        is = new GZIPInputStream(is);
    } else if ("deflate".equalsIgnoreCase("enc")) {
        is = new DeflaterInputStream(is);
    }
    return is;
}

From source file:com.lumata.lib.lupa.internal.ScraperImplIntegrationTest.java

private BufferedReader createReader() throws IOException {
    return new BufferedReader(new InputStreamReader(
            new GZIPInputStream(ScraperImplIntegrationTest.class.getResourceAsStream(URLS_FILE))));
}

From source file:de.huxhorn.lilith.jul.xml.JulImportCallable.java

public Long call() throws Exception {
    if (!inputFile.isFile()) {
        throw new IllegalArgumentException("'" + inputFile.getAbsolutePath() + "' is not a file!");
    }//from   w  w  w . j a v  a 2 s . com
    if (!inputFile.canRead()) {
        throw new IllegalArgumentException("'" + inputFile.getAbsolutePath() + "' is not a readable!");
    }
    long fileSize = inputFile.length();
    setNumberOfSteps(fileSize);
    FileInputStream fis = new FileInputStream(inputFile);
    CountingInputStream cis = new CountingInputStream(fis);

    String fileName = inputFile.getName().toLowerCase(Locale.US);
    XMLStreamReader xmlStreamReader;
    Reader reader;
    if (fileName.endsWith(".gz")) {
        reader = new InputStreamReader(new GZIPInputStream(cis), StandardCharsets.UTF_8);
    } else {
        reader = new InputStreamReader(cis, StandardCharsets.UTF_8);
    }

    xmlStreamReader = XML_INPUT_FACTORY.createXMLStreamReader(new ReplaceInvalidXmlCharacterReader(reader));
    for (;;) {
        try {
            LoggingEvent event = loggingEventReader.read(xmlStreamReader);
            setCurrentStep(cis.getByteCount());
            if (event == null) {
                break;
            }
            result++;
            EventWrapper<LoggingEvent> wrapper = new EventWrapper<>();
            wrapper.setEvent(event);
            SourceIdentifier sourceIdentifier = new SourceIdentifier(inputFile.getAbsolutePath());
            EventIdentifier eventId = new EventIdentifier(sourceIdentifier, result);
            wrapper.setEventIdentifier(eventId);
            buffer.add(wrapper);
        } catch (XMLStreamException ex) {
            if (logger.isWarnEnabled())
                logger.warn("Exception while importing...", ex);
        }
    }
    return result;
}

From source file:com.cloudera.knittingboar.utils.Utils.java

/**
 * Ungzip an input file into an output file.
 * <p>// w w  w. j ava  2 s .co m
 * 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.
 */
private static File unGzip(final File inputFile, final File outputDir)
        throws FileNotFoundException, IOException {

    System.out.println(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);

    for (int c = in.read(); c != -1; c = in.read()) {
        out.write(c);
    }

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

    return outputFile;
}

From source file:com.pinterest.terrapin.zookeeper.ViewInfo.java

public static ViewInfo fromCompressedJson(byte[] compressedJson) throws Exception {
    ByteArrayInputStream in = new ByteArrayInputStream(compressedJson);
    GZIPInputStream zipIs = new GZIPInputStream(in);
    ViewInfo viewInfo = fromJson(IOUtils.toByteArray(zipIs));
    in.close();/*from  w  w w . j  a  v  a  2s  . c  o  m*/
    zipIs.close();
    return viewInfo;
}

From source file:com.osamashabrez.clientserver.json.ClientServerJSONActivity.java

/** Called when the activity is first created. */
@Override/*from w  w  w .  j  a  va2 s.  c  o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    buildref = (EditText) findViewById(R.id.editTextbuild);
    buildref.setFocusable(false);
    buildref.setClickable(false);
    recvdref = (EditText) findViewById(R.id.editTextrecvd);
    recvdref.setFocusable(false);
    recvdref.setClickable(false);
    JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
    jsonobj = new JSONObject();
    try {
        // adding some keys
        jsonobj.put("key", "value");
        jsonobj.put("weburl", "hashincludetechnology.com");

        // lets add some headers (nested headers)
        JSONObject header = new JSONObject();
        header.put("devicemodel", android.os.Build.MODEL); // Device model
        header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version
        header.put("language", Locale.getDefault().getISO3Language()); // Language
        jsonobj.put("header", header);
        // Display the contents of the JSON objects
        buildref.setText(jsonobj.toString(2));
    } catch (JSONException ex) {
        buildref.setText("Error Occurred while building JSON");
        ex.printStackTrace();
    }
    // Now lets begin with the server part
    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppostreq = new HttpPost(wurl);
        StringEntity se = new StringEntity(jsonobj.toString());
        //se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        se.setContentType("application/json;charset=UTF-8");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
        httppostreq.setEntity(se);
        //           httppostreq.setHeader("Accept", "application/json");
        //           httppostreq.setHeader("Content-type", "application/json");
        //           httppostreq.setHeader("User-Agent", "android");
        HttpResponse httpresponse = httpclient.execute(httppostreq);
        HttpEntity resultentity = httpresponse.getEntity();
        if (resultentity != null) {
            InputStream inputstream = resultentity.getContent();
            Header contentencoding = httpresponse.getFirstHeader("Content-Encoding");
            if (contentencoding != null && contentencoding.getValue().equalsIgnoreCase("gzip")) {
                inputstream = new GZIPInputStream(inputstream);
            }

            String resultstring = convertStreamToString(inputstream);
            inputstream.close();
            resultstring = resultstring.substring(1, resultstring.length() - 1);
            recvdref.setText(resultstring + "\n\n" + httppostreq.toString().getBytes());
            //              JSONObject recvdjson = new JSONObject(resultstring);
            //               recvdref.setText(recvdjson.toString(2));
        }
    } catch (Exception e) {
        recvdref.setText("Error Occurred while processing JSON");
        recvdref.setText(e.getMessage());
    }
}

From source file:com.sun.faces.renderkit.ResponseStateManagerImpl.java

public Object getTreeStructureToRestore(FacesContext context, String treeId) {
    StateManager stateManager = Util.getStateManager(context);

    Object structure = null;/*  w w w.  j  a v  a 2s . co  m*/
    Object state = null;
    ByteArrayInputStream bis = null;
    GZIPInputStream gis = null;
    ObjectInputStream ois = null;
    boolean compress = isCompressStateSet(context);

    Map requestParamMap = context.getExternalContext().getRequestParameterMap();

    String viewString = (String) requestParamMap.get(RIConstants.FACES_VIEW);
    if (viewString == null) {
        return null;
    }
    if (stateManager.isSavingStateInClient(context)) {
        byte[] bytes = Base64.decode(viewString.getBytes());
        try {
            bis = new ByteArrayInputStream(bytes);
            if (isCompressStateSet(context)) {
                if (log.isDebugEnabled()) {
                    log.debug("Deflating state before restoring..");
                }
                gis = new GZIPInputStream(bis);
                ois = new ApplicationObjectInputStream(gis);
            } else {
                ois = new ApplicationObjectInputStream(bis);
            }
            structure = ois.readObject();
            state = ois.readObject();
            Map requestMap = context.getExternalContext().getRequestMap();
            // store the state object temporarily in request scope until it is
            // processed by getComponentStateToRestore which resets it.
            requestMap.put(FACES_VIEW_STATE, state);
            bis.close();
            if (compress) {
                gis.close();
            }
            ois.close();
        } catch (java.io.OptionalDataException ode) {
            log.error(ode.getMessage(), ode);
            throw new FacesException(ode);
        } catch (java.lang.ClassNotFoundException cnfe) {
            log.error(cnfe.getMessage(), cnfe);
            throw new FacesException(cnfe);
        } catch (java.io.IOException iox) {
            log.error(iox.getMessage(), iox);
            throw new FacesException(iox);
        }
    } else {
        structure = viewString;
    }
    return structure;
}

From source file:edu.umn.cs.spatialHadoop.nasa.HDFRasterLayer.java

@Override
public void readFields(DataInput in) throws IOException {
    super.readFields(in);
    this.timestamp = in.readLong();
    int length = in.readInt();
    byte[] serializedData = new byte[length];
    in.readFully(serializedData);//from   w ww  .  ja v  a2 s. c o m
    ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
    GZIPInputStream gzis = new GZIPInputStream(bais);

    byte[] buffer = new byte[8];
    gzis.read(buffer);
    ByteBuffer bbuffer = ByteBuffer.wrap(buffer);
    int width = bbuffer.getInt();
    int height = bbuffer.getInt();
    // Reallocate memory only if needed
    if (width != this.getWidth() || height != this.getHeight()) {
        sum = new long[width][height];
        count = new long[width][height];
    }
    buffer = new byte[getHeight() * 2 * 8];
    for (int x = 0; x < getWidth(); x++) {
        int size = 0;
        while (size < buffer.length) {
            size += gzis.read(buffer, size, buffer.length - size);
        }
        bbuffer = ByteBuffer.wrap(buffer);
        for (int y = 0; y < getHeight(); y++) {
            sum[x][y] = bbuffer.getLong();
            count[x][y] = bbuffer.getLong();
        }
    }
}