Example usage for java.util.zip InflaterInputStream InflaterInputStream

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

Introduction

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

Prototype

public InflaterInputStream(InputStream in, Inflater inf) 

Source Link

Document

Creates a new input stream with the specified decompressor and a default buffer size.

Usage

From source file:ZipUtil.java

public static void unzipFileToFile(File flSource, File flTarget) throws IOException {
    Inflater oInflate = new Inflater(false);
    FileInputStream stmFileIn = new FileInputStream(flSource);
    FileOutputStream stmFileOut = new FileOutputStream(flTarget);
    InflaterInputStream stmInflateIn = new InflaterInputStream(stmFileIn, oInflate);

    try {//  w  w w.ja va2 s .  c o m
        inflaterInputStmToFileOutputStm(stmInflateIn, stmFileOut);
    } //end try
    finally {
        stmFileOut.flush();
        stmFileOut.close();
        stmInflateIn.close();
        stmFileIn.close();
    }
}

From source file:org.apache.fop.render.pdf.ImageRawPNGAdapter.java

/** {@inheritDoc} */
public void setup(PDFDocument doc) {
    super.setup(doc);
    ColorModel cm = ((ImageRawPNG) this.image).getColorModel();
    if (cm instanceof IndexColorModel) {
        numberOfInterleavedComponents = 1;
    } else {//ww  w  .j  a va2 s.co m
        // this can be 1 (gray), 2 (gray + alpha), 3 (rgb) or 4 (rgb + alpha)
        // numberOfInterleavedComponents = (cm.hasAlpha() ? 1 : 0) + cm.getNumColorComponents();
        numberOfInterleavedComponents = cm.getNumComponents();
    }

    // set up image compression for non-alpha channel
    FlateFilter flate;
    try {
        flate = new FlateFilter();
        flate.setApplied(true);
        flate.setPredictor(FlateFilter.PREDICTION_PNG_OPT);
        if (numberOfInterleavedComponents < 3) {
            // means palette (1) or gray (1) or gray + alpha (2)
            flate.setColors(1);
        } else {
            // means rgb (3) or rgb + alpha (4)
            flate.setColors(3);
        }
        flate.setColumns(image.getSize().getWidthPx());
        flate.setBitsPerComponent(this.getBitsPerComponent());
    } catch (PDFFilterException e) {
        throw new RuntimeException("FlateFilter configuration error", e);
    }
    this.pdfFilter = flate;
    this.disallowMultipleFilters();

    // Handle transparency channel if applicable; note that for palette images the transparency is
    // not TRANSLUCENT
    if (cm.hasAlpha() && cm.getTransparency() == ColorModel.TRANSLUCENT) {
        doc.getProfile().verifyTransparencyAllowed(image.getInfo().getOriginalURI());
        // TODO: Implement code to combine image with background color if transparency is not allowed
        // here we need to inflate the PNG pixel data, which includes alpha, separate the alpha channel
        // and then deflate it back again
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DeflaterOutputStream dos = new DeflaterOutputStream(baos, new Deflater());
        InputStream in = ((ImageRawStream) image).createInputStream();
        try {
            InflaterInputStream infStream = new InflaterInputStream(in, new Inflater());
            DataInputStream dataStream = new DataInputStream(infStream);
            // offset is the byte offset of the alpha component
            int offset = numberOfInterleavedComponents - 1; // 1 for GA, 3 for RGBA
            int numColumns = image.getSize().getWidthPx();
            int bytesPerRow = numberOfInterleavedComponents * numColumns;
            int filter;
            // read line by line; the first byte holds the filter
            while ((filter = dataStream.read()) != -1) {
                byte[] bytes = new byte[bytesPerRow];
                dataStream.readFully(bytes, 0, bytesPerRow);
                dos.write((byte) filter);
                for (int j = 0; j < numColumns; j++) {
                    dos.write(bytes, offset, 1);
                    offset += numberOfInterleavedComponents;
                }
                offset = numberOfInterleavedComponents - 1;
            }
            dos.close();
        } catch (IOException e) {
            throw new RuntimeException("Error processing transparency channel:", e);
        } finally {
            IOUtils.closeQuietly(in);
        }
        // set up alpha channel compression
        FlateFilter transFlate;
        try {
            transFlate = new FlateFilter();
            transFlate.setApplied(true);
            transFlate.setPredictor(FlateFilter.PREDICTION_PNG_OPT);
            transFlate.setColors(1);
            transFlate.setColumns(image.getSize().getWidthPx());
            transFlate.setBitsPerComponent(this.getBitsPerComponent());
        } catch (PDFFilterException e) {
            throw new RuntimeException("FlateFilter configuration error", e);
        }
        BitmapImage alphaMask = new BitmapImage("Mask:" + this.getKey(), image.getSize().getWidthPx(),
                image.getSize().getHeightPx(), baos.toByteArray(), null);
        alphaMask.setPDFFilter(transFlate);
        alphaMask.disallowMultipleFilters();
        alphaMask.setColorSpace(new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_GRAY));
        softMask = doc.addImage(null, alphaMask).makeReference();
    }
}

From source file:org.codice.ddf.security.common.jaxrs.RestSecurityTest.java

@Test
public void testInflateDeflateWithTokenDuplication() throws Exception {
    String token = "valid_grant valid_grant valid_grant valid_grant valid_grant valid_grant";

    DeflateEncoderDecoder deflateEncoderDecoder = new DeflateEncoderDecoder();
    byte[] deflatedToken = deflateEncoderDecoder.deflateToken(token.getBytes());

    String cxfInflatedToken = IOUtils.toString(deflateEncoderDecoder.inflateToken(deflatedToken));

    String streamInflatedToken = IOUtils
            .toString(new InflaterInputStream(new ByteArrayInputStream(deflatedToken), new Inflater(true)));

    assertNotSame(cxfInflatedToken, token);
    assertEquals(streamInflatedToken, token);
}

From source file:name.npetrovski.jphar.DataEntry.java

private InputStream getCompressorInputStream(final InputStream is, Compression.Type compression)
        throws IOException {
    switch (compression) {
    case ZLIB:/*from  w  w  w . j a  v  a  2 s.c  om*/
        return new InflaterInputStream(is, new Inflater(true));
    case BZIP:
        return new BZip2CompressorInputStream(is, true);
    case NONE:
        return is;
    default:
        throw new IOException("Unsupported compression type.");
    }

}

From source file:com.alibaba.citrus.service.requestcontext.session.encoder.AbstractSerializationEncoder.java

/** ? */
public Map<String, Object> decode(String encodedValue, StoreContext storeContext)
        throws SessionEncoderException {
    // 1. base64?
    byte[] cryptotext = null;

    try {//from  w  ww . jav  a 2s  .c om
        encodedValue = URLDecoder.decode(assertNotNull(encodedValue, "encodedValue is null"), "ISO-8859-1");
        cryptotext = Base64.decodeBase64(encodedValue.getBytes("ISO-8859-1"));

        if (isEmptyArray(cryptotext)) {
            throw new SessionEncoderException("Session state is empty: " + encodedValue);
        }
    } catch (Exception e) {
        throw new SessionEncoderException("Failed to decode session state: ", e);
    }

    // 2. 
    byte[] plaintext = decrypt(cryptotext);

    if (isEmptyArray(plaintext)) {
        throw new SessionEncoderException("Decrypted session state is empty: " + encodedValue);
    }

    // 3. 
    ByteArrayInputStream bais = new ByteArrayInputStream(plaintext);
    Inflater inf = new Inflater(false);
    InflaterInputStream iis = new InflaterInputStream(bais, inf);

    // 4. ???
    try {
        @SuppressWarnings("unchecked")
        Map<String, Object> attrs = (Map<String, Object>) serializer.deserialize(iis);
        return attrs;
    } catch (Exception e) {
        throw new SessionEncoderException("Failed to parse session state", e);
    } finally {
        try {
            iis.close();
        } catch (IOException e) {
        }

        inf.end();
    }
}

From source file:org.codice.ddf.security.common.jaxrs.RestSecurity.java

public static String inflateBase64(String base64EncodedValue) throws IOException {
    byte[] deflatedValue = Base64.getMimeDecoder().decode(base64EncodedValue);
    InputStream is = new InflaterInputStream(new ByteArrayInputStream(deflatedValue),
            new Inflater(GZIP_COMPATIBLE));
    return IOUtils.toString(is, StandardCharsets.UTF_8.name());
}

From source file:com.alibaba.citrus.service.requestcontext.session.valueencoder.AbstractSessionValueEncoder.java

private byte[] decompress(byte[] data) throws SessionValueEncoderException {
    if (!doCompress()) {
        return data;
    }/*from   w w  w . ja  va2  s  .c o m*/

    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    Inflater inf = new Inflater(false);
    InflaterInputStream iis = new InflaterInputStream(bais, inf);

    try {
        return StreamUtil.readBytes(iis, true).toByteArray();
    } catch (Exception e) {
        throw new SessionValueEncoderException(e);
    } finally {
        inf.end();
    }
}

From source file:org.oscim.utils.overpass.OverpassAPIReader.java

/**
 * Open a connection to the given url and return a reader on the input
 * stream from that connection./*from w  ww .  ja  v  a2  s  .c  o m*/
 * 
 * @param pUrlStr
 *            The exact url to connect to.
 * @return An reader reading the input stream (servers answer) or
 *         <code>null</code>.
 * @throws IOException
 *             on io-errors
 */
private InputStream getInputStream(final String pUrlStr) throws IOException {
    URL url;
    int responseCode;
    String encoding;

    url = new URL(pUrlStr);
    myActiveConnection = (HttpURLConnection) url.openConnection();

    myActiveConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");

    responseCode = myActiveConnection.getResponseCode();

    if (responseCode != RESPONSECODE_OK) {
        String message;
        String apiErrorMessage;

        apiErrorMessage = myActiveConnection.getHeaderField("Error");

        if (apiErrorMessage != null) {
            message = "Received API HTTP response code " + responseCode + " with message \"" + apiErrorMessage
                    + "\" for URL \"" + pUrlStr + "\".";
        } else {
            message = "Received API HTTP response code " + responseCode + " for URL \"" + pUrlStr + "\".";
        }

        throw new IOException(message);
    }

    myActiveConnection.setConnectTimeout(TIMEOUT);

    encoding = myActiveConnection.getContentEncoding();

    responseStream = myActiveConnection.getInputStream();
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        responseStream = new GZIPInputStream(responseStream);
    } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
        responseStream = new InflaterInputStream(responseStream, new Inflater(true));
    }

    return responseStream;
}

From source file:org.pac4j.saml.client.RedirectSaml2ClientIT.java

private String getInflatedAuthnRequest(String location) throws Exception {
    List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(location), "UTF-8");
    Inflater inflater = new Inflater(true);
    byte[] decodedRequest = Base64.decodeBase64(pairs.get(0).getValue());
    ByteArrayInputStream is = new ByteArrayInputStream(decodedRequest);
    InflaterInputStream inputStream = new InflaterInputStream(is, inflater);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    return reader.readLine();
}

From source file:cn.edu.bit.whitesail.crawl.Crawler.java

private byte[] download(String URL) {
    byte[] result = null;
    HttpEntity httpEntity = null;/*  w w w .j  a va  2 s  .c om*/
    try {

        HttpGet httpGet = new HttpGet(URL);

        httpGet.addHeader("Accept-Language", "zh-cn,zh,en");
        httpGet.addHeader("Accept-Encoding", "gzip,deflate");

        HttpResponse response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        Header header = response.getFirstHeader("content-type");

        if (header == null || header.getValue().indexOf("text/html") < 0) {
            return null;
        }

        int pos = header.getValue().indexOf("charset=");
        if (pos >= 0) {
            detectedEncoding = header.getValue().substring(pos + 8);
        }

        httpEntity = response.getEntity();
        InputStream in = null;
        in = httpEntity.getContent();

        header = response.getFirstHeader("Content-Encoding");
        if (null != header) {
            if (header.getValue().indexOf("gzip") >= 0) {
                in = new GZIPInputStream(in);
            } else if (header.getValue().indexOf("deflate") >= 0) {
                in = new InflaterInputStream(in, new Inflater(true));
            }
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        result = out.toByteArray();

    } catch (IOException ex) {
        LOG.warn("downloading error,abandon");
        result = null;
    }
    return result;
}