java.util.zip.DeflaterInputStream Java Examples

The following examples show how to use java.util.zip.DeflaterInputStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EncodingUtility.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Description("Encodes string to base64.<br/>"+
        "<b>content</b> - string to encode.<br/>" +
        "<b>compress</b> - perform compression of the result string (y / Y / n / N).<br/>" +
        "Example:<br/>" +
        "#EncodeBase64(\"Test content\", \"n\") returns \"VGVzdCBjb250ZW50\"<br/>"+
        "Example:<br/>" +
        "#EncodeBase64(\"Test content\", \"y\") returns \"eJwLSS0uUUjOzytJzSsBAB2pBLw=\"<br/>")
@UtilityMethod
public String EncodeBase64(String content, Object compress) throws Exception{
    Boolean doCompress = BooleanUtils.toBoolean((String)compress);
    byte[] result;
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
         try (OutputStream b64 = new Base64OutputStream(os, true, -1, new byte[0]);
                InputStream ba = new ByteArrayInputStream(content.getBytes());
                InputStream is = doCompress ? new DeflaterInputStream(ba) : ba) {
            IOUtils.copy(is, b64);
        }
        os.flush();
        result = os.toByteArray();
    }
    return new String(result);
}
 
Example #2
Source File: Recorder.java    From webarchive-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Get a replay cued up for the 'content' (after all leading headers)
 * 
 * @return A replay input stream.
 * @throws IOException
 */
public InputStream getContentReplayInputStream() throws IOException {
    InputStream entityStream = getEntityReplayInputStream();
    if(StringUtils.isEmpty(contentEncoding)) {
        return entityStream;
    } else if ("gzip".equalsIgnoreCase(contentEncoding) || "x-gzip".equalsIgnoreCase(contentEncoding)) {
        try {
            return new GZIPInputStream(entityStream);
        } catch (IOException ioe) {
            logger.log(Level.WARNING,"gzip problem; using raw entity instead",ioe);
            IOUtils.closeQuietly(entityStream); // close partially-read stream
            return getEntityReplayInputStream(); 
        }
    } else if ("deflate".equalsIgnoreCase(contentEncoding)) {
        return new DeflaterInputStream(entityStream);
    } else if ("identity".equalsIgnoreCase(contentEncoding) || "none".equalsIgnoreCase(contentEncoding)) {
        return entityStream;
    } else {
        // shouldn't be reached given check on setContentEncoding
        logger.log(Level.INFO,"Unknown content-encoding '"+contentEncoding+"' declared; using raw entity instead");
        return entityStream; 
    }
}
 
Example #3
Source File: ZipCombiner.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Writes an entry with the given name, date and external file attributes from the buffer. */
private void writeEntryFromBuffer(ZipFileEntry entry, byte[] uncompressed) throws IOException {
  CRC32 crc = new CRC32();
  crc.update(uncompressed);

  entry.setCrc(crc.getValue());
  entry.setSize(uncompressed.length);
  if (mode == OutputMode.FORCE_STORED) {
    entry.setMethod(Compression.STORED);
    entry.setCompressedSize(uncompressed.length);
    writeEntry(entry, new ByteArrayInputStream(uncompressed));
  } else {
    ByteArrayOutputStream compressed = new ByteArrayOutputStream();
    copyStream(new DeflaterInputStream(new ByteArrayInputStream(uncompressed), getDeflater()),
        compressed);
    entry.setMethod(Compression.DEFLATED);
    entry.setCompressedSize(compressed.size());
    writeEntry(entry, new ByteArrayInputStream(compressed.toByteArray()));
  }
}
 
Example #4
Source File: DeflaterInputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testReadWithBuffer() throws IOException {
    byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    byte[] buffer = new byte[8];
    InputStream in = new DeflaterInputStream(new ByteArrayInputStream(data));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    assertEquals(1, in.available());
    int count;
    while ((count = in.read(buffer, 0, 5)) != -1) {
        assertTrue(count <= 5);
        out.write(buffer, 0, count);
    }
    assertEquals(0, in.available());

    assertEquals(Arrays.toString(data), Arrays.toString(inflate(out.toByteArray())));

    in.close();
    try {
        in.available();
        fail();
    } catch (IOException expected) {
    }
}
 
Example #5
Source File: DeflaterInputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testReadByteByByte() throws IOException {
    byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    InputStream in = new DeflaterInputStream(new ByteArrayInputStream(data));
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    assertEquals(1, in.available());
    int b;
    while ((b = in.read()) != -1) {
        out.write(b);
    }
    assertEquals(0, in.available());

    assertEquals(Arrays.toString(data), Arrays.toString(inflate(out.toByteArray())));

    in.close();
    try {
        in.available();
        fail();
    } catch (IOException expected) {
    }
}
 
Example #6
Source File: DeflaterInputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * DeflaterInputStream#DeflaterInputStream(InputStream)
 */
/* J2ObjC removed: not supported by Junit 4.11 (https://github.com/google/j2objc/issues/1318).
@DisableResourceLeakageDetection(
        why = "DeflaterInputStream does not clean up the default Deflater created in the"
                + " constructor if the constructor fails; i.e. constructor calls"
                + " this(..., new Deflater(), ...) and that constructor fails but does not know"
                + " that it needs to call Deflater.end() as the caller has no access to it",
        bug = "31798154") */
public void testDeflaterInputStreamInputStream() throws IOException {
    // ok
    new DeflaterInputStream(is).close();
    // fail
    try {
        new DeflaterInputStream(null);
        fail("should throw NullPointerException");
    } catch (NullPointerException e) {
        // expected
    }
}
 
Example #7
Source File: DeflaterInputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testRead_golden() throws Exception {
    try (DeflaterInputStream dis = new DeflaterInputStream(is)) {
        byte[] contents = Streams.readFully(dis);
        assertTrue(Arrays.equals(TEST_STRING_DEFLATED_BYTES, contents));
    }

    try (DeflaterInputStream dis = new DeflaterInputStream(
            new ByteArrayInputStream(TEST_STR.getBytes("UTF-8")))) {
        byte[] result = new byte[32];
        int count = 0;
        int bytesRead;
        while ((bytesRead = dis.read(result, count, 4)) != -1) {
            count += bytesRead;
        }
        assertEquals(23, count);
        byte[] splicedResult = new byte[23];
        System.arraycopy(result, 0, splicedResult, 0, 23);
        assertTrue(Arrays.equals(TEST_STRING_DEFLATED_BYTES, splicedResult));
    }
}
 
Example #8
Source File: DeflaterInputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * DeflaterInputStream#read()
 */
public void testRead() throws IOException {
    DeflaterInputStream dis = new DeflaterInputStream(is);
    assertEquals(1, dis.available());
    assertEquals(120, dis.read());
    assertEquals(1, dis.available());
    assertEquals(156, dis.read());
    assertEquals(1, dis.available());
    assertEquals(243, dis.read());
    assertEquals(1, dis.available());
    dis.close();
    try {
        dis.read();
        fail("should throw IOException");
    } catch (IOException e) {
        // expected
    }
}
 
Example #9
Source File: DeflaterInputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * DeflaterInputStream#available()
 */
public void testAvailable() throws IOException {
    byte[] buf = new byte[1024];
    DeflaterInputStream dis = new DeflaterInputStream(is);
    assertEquals(1, dis.available());
    assertEquals(120, dis.read());
    assertEquals(1, dis.available());
    assertEquals(22, dis.read(buf, 0, 1024));
    assertEquals(0, dis.available());
    assertEquals(-1, dis.read());
    assertEquals(0, dis.available());
    dis.close();
    try {
        dis.available();
        fail("should throw IOException");
    } catch (IOException e) {
        // expected
    }
}
 
Example #10
Source File: Encoder.java    From atlassian-agent with GNU General Public License v3.0 6 votes vote down vote up
private static byte[] zipText(byte[] licenseText) throws IOException {
    int len;
    byte[] buff = new byte[64];
    ByteArrayInputStream in = new ByteArrayInputStream(licenseText);
    DeflaterInputStream deflater = new DeflaterInputStream(in, new Deflater());
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        while ((len = deflater.read(buff)) > 0) {
            out.write(buff, 0, len);
        }

        return out.toByteArray();
    } finally {
        out.close();
        deflater.close();
        in.close();
    }
}
 
Example #11
Source File: DeflaterInputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * DeflaterInputStream#markSupported()
 */
public void testMarkSupported() throws IOException {
    DeflaterInputStream dis = new DeflaterInputStream(is);
    assertFalse(dis.markSupported());
    dis.close();
    assertFalse(dis.markSupported());
}
 
Example #12
Source File: DeflaterInputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * DeflaterInputStream#mark()
 */
public void testMark() throws IOException {
    // mark do nothing
    DeflaterInputStream dis = new DeflaterInputStream(is);
    dis.mark(-1);
    dis.mark(0);
    dis.mark(1);
    dis.close();
    dis.mark(1);
}
 
Example #13
Source File: ObjectsStreamPDFBodyObjectsWriter.java    From sambox with Apache License 2.0 5 votes vote down vote up
void prepareForWriting()
{
    IOUtils.closeQuietly(dataWriter);
    setItem(COSName.N, asDirectObject(COSInteger.get(counter)));
    setItem(COSName.FIRST, asDirectObject(COSInteger.get(header.size())));
    setItem(COSName.FILTER, asDirectObject(COSName.FLATE_DECODE));
    this.filtered = new DeflaterInputStream(
            new SequenceInputStream(new ByteArrayInputStream(header.toByteArray()),
                    new ByteArrayInputStream(data.toByteArray())));
    this.header = null;
    this.data = null;
}
 
Example #14
Source File: ResourceReportClient.java    From twill with Apache License 2.0 5 votes vote down vote up
private InputStream getInputStream(HttpURLConnection urlConn) throws IOException {
  InputStream is = urlConn.getInputStream();
  String contentEncoding = urlConn.getContentEncoding();
  if (contentEncoding == null) {
    return is;
  }
  if ("gzip".equalsIgnoreCase(contentEncoding)) {
    return new GZIPInputStream(is);
  }
  if ("deflate".equalsIgnoreCase(contentEncoding)) {
    return new DeflaterInputStream(is);
  }
  // This should never happen
  throw new IOException("Unsupported content encoding " + contentEncoding);
}
 
Example #15
Source File: DecompressTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void deflate(InputStream in){
    byte[] destBuffer = new byte[1024];
    try {
        new DeflaterInputStream(in)
            .read(destBuffer, 0, destBuffer.length);
    } catch (IOException e){
        // Ignore
    }

}
 
Example #16
Source File: CommonActions.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
/**
 * Encode base64 text. Returns BASE64 string.
 *
 * @param actionContext
 *            - an implementation of {@link IActionContext}
 * @param inputData
 *            - hash map of script parameters - must contain value of column
 *            "FileName" and "Content" <br />
 * @throws Exception
 *             - throws an exception
 */
@Description("Encode file to base64.<br/>"+
        "<b>FileAlias</b> - file to encode.<br/>" +
        "<b>Compress</b> - do compress result string (y / Y / n / N).<br/>")
@CommonColumns(@CommonColumn(value = Column.Reference, required = true))
@CustomColumns({ @CustomColumn(value = "FileAlias", required = true), @CustomColumn(value = "Compress", required = false)})
@ActionMethod
public String LoadBase64Content(IActionContext actionContext, HashMap<?, ?> inputData) throws Exception {

    String fileAlias = unwrapFilters(inputData.get("FileAlias"));
    Boolean compress = BooleanUtils.toBoolean((String)unwrapFilters(inputData.get("Compress")));
    IDataManager dataManager = actionContext.getDataManager();
    SailfishURI target = SailfishURI.parse(fileAlias);

    if (dataManager.exists(target)) {

        byte[] result;

        try(ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            try (OutputStream b64 =  new Base64OutputStream(os, true, -1, new byte[0]);
                    InputStream dm = dataManager.getDataInputStream(target);
                    InputStream is = compress ? new DeflaterInputStream(dm) : dm) {
                IOUtils.copy(is, b64);
            }
            os.flush();
            result = os.toByteArray();
        }

        return new String(result);
    } else {
        throw new EPSCommonException(format("Specified %s file alias does not exists", fileAlias));
    }
}
 
Example #17
Source File: Compression.java    From activitystreams with Apache License 2.0 4 votes vote down vote up
public DeflaterInputStream decompressor(InputStream in)
    throws IOException {
  return new DeflaterInputStream(in);
}
 
Example #18
Source File: ReadOnlyFilteredCOSStreamTest.java    From sejda with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void embeddedFileIsCompressed() throws Exception {
    victim = ReadOnlyFilteredCOSStream.readOnlyEmbeddedFile(StreamSource.newInstance(stream, "chuck"));
    assertThat(victim.getFilteredStream(), instanceOf(DeflaterInputStream.class));
}