Java Code Examples for java.util.zip.Deflater

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project dolphin, under directory /joytyping/src/com/tan/util/.

Source file: Compressor.java

  23 
vote

public byte[] compress(final byte[] data,final int offset,final int length){
  Deflater deflater=new Deflater(Deflater.BEST_COMPRESSION,true);
  deflater.setInput(data,offset,length);
  deflater.finish();
  int len=-1;
  len=deflater.deflate(data,offset,length);
  if (len == -1)   return null;
  byte[] result=new byte[len];
  System.arraycopy(data,0,result,0,len);
  return result;
}
 

Example 2

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: Utils.java

  22 
vote

/** 
 * Compress data.
 * @param bytesToCompress is the byte array to compress.
 * @return a compressed byte array.
 * @throws java.io.IOException
 */
public static byte[] compress(byte[] bytesToCompress) throws IOException {
  Deflater compressor=new Deflater(Deflater.BEST_COMPRESSION);
  compressor.setInput(bytesToCompress);
  compressor.finish();
  ByteArrayOutputStream bos=new ByteArrayOutputStream(bytesToCompress.length);
  byte[] buf=new byte[bytesToCompress.length + 100];
  while (!compressor.finished()) {
    bos.write(buf,0,compressor.deflate(buf));
  }
  bos.close();
  return bos.toByteArray();
}
 

Example 3

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/format/gzip/.

Source file: GZIPMemberWriter.java

  22 
vote

public void write(InputStream is) throws IOException {
  CRCInputStream crc=new CRCInputStream(is);
  GZIPHeader gzHeader=new GZIPHeader();
  gzHeader.writeBytes(out);
  Deflater deflater=new Deflater(Deflater.DEFAULT_COMPRESSION,true);
  DeflaterOutputStream deflateOut=new DeflaterOutputStream(out,deflater);
  StreamCopy.copy(crc,deflateOut);
  deflateOut.finish();
  GZIPFooter gzFooter=new GZIPFooter(crc.getCRCValue(),crc.getByteCount());
  gzFooter.writeBytes(out);
  out.flush();
}
 

Example 4

From project big-data-plugin, under directory /src/org/pentaho/di/trans/steps/cassandrainput/.

Source file: CassandraInputData.java

  22 
vote

/** 
 * Compress a CQL query
 * @param queryStr the CQL query
 * @param compression compression option (GZIP is the only option - so far)
 * @return an array of bytes containing the compressed query
 */
public static byte[] compressQuery(String queryStr,Compression compression){
  byte[] data=queryStr.getBytes(Charset.forName(CassandraColumnMetaData.UTF8));
  Deflater compressor=new Deflater();
  compressor.setInput(data);
  compressor.finish();
  ByteArrayOutputStream byteArray=new ByteArrayOutputStream();
  byte[] buffer=new byte[1024];
  while (!compressor.finished()) {
    int size=compressor.deflate(buffer);
    byteArray.write(buffer,0,size);
  }
  return byteArray.toByteArray();
}
 

Example 5

From project eoit, under directory /EOITUtils/src/test/java/fr/eoit/util/dumper/.

Source file: DumperTest.java

  22 
vote

@Test public void testCompression(){
  byte[] strBytes=COPYRIGHTS.getBytes();
  byte[] output=new byte[8096];
  Deflater compresser=new Deflater(Deflater.BEST_COMPRESSION,true);
  compresser.setInput(strBytes);
  compresser.finish();
  int compressedDataLength=compresser.deflate(output);
  compresser.end();
  String inputString=new String(Hex.encodeHex(strBytes));
  String hexString=new String(Arrays.copyOf(output,compressedDataLength));
  int i=0;
  i++;
}
 

Example 6

From project graylog2-server, under directory /src/test/java/org/graylog2/.

Source file: TestHelper.java

  22 
vote

public static byte[] zlibCompress(String what) throws UnsupportedEncodingException {
  byte[] input=what.getBytes("UTF-8");
  byte[] output=new byte[4096];
  Deflater compresser=new Deflater();
  compresser.setInput(input);
  compresser.finish();
  compresser.deflate(output);
  return output;
}
 

Example 7

From project hcatalog, under directory /src/java/org/apache/hcatalog/mapreduce/.

Source file: InputJobInfo.java

  22 
vote

/** 
 * Serialize this object, compressing the partitions which can exceed the allowed jobConf size.
 * @see <a href="https://issues.apache.org/jira/browse/HCATALOG-453">HCATALOG-453</a>
 */
private void writeObject(ObjectOutputStream oos) throws IOException {
  oos.defaultWriteObject();
  Deflater def=new Deflater(Deflater.BEST_COMPRESSION);
  ObjectOutputStream partInfoWriter=new ObjectOutputStream(new DeflaterOutputStream(oos,def));
  partInfoWriter.writeObject(partitions);
  partInfoWriter.close();
}
 

Example 8

From project JVerge, under directory /src/persist/.

Source file: ExtendedDataOutputStream.java

  22 
vote

public void writeCompressedBytes(byte[] data) throws IOException {
  byte[] output=new byte[data.length];
  Deflater compresser=new Deflater();
  compresser.setInput(data);
  compresser.finish();
  int compressedDataLength=compresser.deflate(output);
  byte[] compressedOutput=new byte[compressedDataLength];
  for (int i=0; i < compressedDataLength; i++)   compressedOutput[i]=output[i];
  this.writeSignedIntegerLittleEndian(data.length);
  this.writeSignedIntegerLittleEndian(compressedDataLength);
  this.write(compressedOutput);
  System.out.println("Uncompressed: " + data.length + " Compressed: "+ compressedDataLength+ " "+ compressedOutput.length);
}
 

Example 9

From project LateralGM, under directory /org/lateralgm/file/.

Source file: GmStreamEncoder.java

  22 
vote

public void compress(byte[] data) throws IOException {
  Deflater compresser=new Deflater();
  compresser.setInput(data);
  compresser.finish();
  byte[] buffer=new byte[131072];
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  while (!compresser.finished()) {
    int len=compresser.deflate(buffer);
    baos.write(buffer,0,len);
  }
  write4(baos.size());
  write(baos.toByteArray());
}
 

Example 10

From project lesscss-servlet, under directory /src/main/java/com/asual/lesscss/.

Source file: ResourcePackage.java

  22 
vote

private static byte[] deflate(byte[] input) throws IOException {
  Deflater deflater=new Deflater();
  deflater.setLevel(Deflater.BEST_COMPRESSION);
  deflater.setInput(input);
  deflater.finish();
  ByteArrayOutputStream baos=new ByteArrayOutputStream(input.length);
  byte[] buf=new byte[1024];
  while (!deflater.finished()) {
    int count=deflater.deflate(buf);
    baos.write(buf,0,count);
  }
  baos.close();
  return baos.toByteArray();
}
 

Example 11

From project OSM-binary, under directory /src.java/crosby/binary/file/.

Source file: FileBlock.java

  22 
vote

protected void deflateInto(crosby.binary.Fileformat.Blob.Builder blobbuilder){
  int size=data.size();
  Deflater deflater=new Deflater();
  deflater.setInput(data.toByteArray());
  deflater.finish();
  byte out[]=new byte[size];
  deflater.deflate(out);
  if (!deflater.finished()) {
    ++warncount;
    if (warncount > 10 && warncount % 100 == 0)     System.out.println("Compressed buffers are too short, causing extra copy");
    out=Arrays.copyOf(out,size + size / 64 + 16);
    deflater.deflate(out,deflater.getTotalOut(),out.length - deflater.getTotalOut());
    if (!deflater.finished()) {
      throw new Error("Internal error in compressor");
    }
  }
  ByteString compressed=ByteString.copyFrom(out,0,deflater.getTotalOut());
  blobbuilder.setZlibData(compressed);
  deflater.end();
}
 

Example 12

From project PSXperia, under directory /src/com/yifanlu/PSXperiaTool/.

Source file: PSImageCreate.java

  22 
vote

protected void compressPart(InputStream in,OutputStream out) throws IOException {
  Logger.verbose("Compressing part.");
  Deflater defl=new Deflater(Deflater.DEFAULT_COMPRESSION);
  DeflaterOutputStream zOut=new DeflaterOutputStream(out,defl);
  mEntries.add((int)((FileOutputStream)out).getChannel().size());
  byte[] buff=new byte[PART_BS];
  int n;
  while ((n=in.read(buff,0,PART_BS)) != -1) {
    zOut.write(buff,0,n);
  }
  addBytesWritten((int)defl.getBytesWritten());
  zOut.finish();
  Logger.verbose("Done compressing part.");
}
 

Example 13

From project v7files, under directory /src/main/java/v7db/files/.

Source file: Compression.java

  22 
vote

/** 
 * @return 0, if the "deflated" data fills the whole output array
 */
static int deflate(byte[] data,int off,int len,byte[] out){
  Deflater deflater=new Deflater(BEST_COMPRESSION,true);
  deflater.setInput(data,off,len);
  deflater.finish();
  int size=deflater.deflate(out);
  if (size == 0 || size == out.length)   return 0;
  return size;
}
 

Example 14

From project vnc, under directory /src/com/tigervnc/decoder/.

Source file: TightDecoder.java

  22 
vote

void recordCompressedData(byte[] data,int off,int len) throws IOException {
  Deflater deflater=new Deflater();
  deflater.setInput(data,off,len);
  int bufSize=len + len / 100 + 12;
  byte[] buf=new byte[bufSize];
  deflater.finish();
  int compressedSize=deflater.deflate(buf);
  recordCompactLen(compressedSize);
  if (dos != null)   dos.write(buf,0,compressedSize);
}
 

Example 15

From project activemq-apollo, under directory /apollo-openwire/src/main/scala/org/apache/activemq/apollo/openwire/command/.

Source file: ActiveMQBytesMessage.java

  21 
vote

private void initializeWriting() throws OpenwireException {
  checkReadOnlyBody();
  if (this.dataOut == null) {
    this.bytesOut=new ByteArrayOutputStream();
    OutputStream os=bytesOut;
    if (Settings.enable_compression()) {
      try {
        os.write(new byte[4]);
      }
 catch (      IOException e) {
        throw new OpenwireException(e);
      }
      length=0;
      compressed=true;
      final Deflater deflater=new Deflater(Deflater.BEST_SPEED);
      os=new FilterOutputStream(new DeflaterOutputStream(os,deflater)){
        public void write(        byte[] arg0) throws IOException {
          length+=arg0.length;
          out.write(arg0);
        }
        public void write(        byte[] arg0,        int arg1,        int arg2) throws IOException {
          length+=arg2;
          out.write(arg0,arg1,arg2);
        }
        public void write(        int arg0) throws IOException {
          length++;
          out.write(arg0);
        }
        @Override public void close() throws IOException {
          super.close();
          deflater.end();
        }
      }
;
    }
    this.dataOut=new DataOutputStream(os);
  }
}
 

Example 16

From project avro, under directory /lang/java/avro/src/main/java/org/apache/avro/file/.

Source file: DeflateCodec.java

  21 
vote

private Deflater getDeflater(){
  if (null == deflater) {
    deflater=new Deflater(compressionLevel,nowrap);
  }
  deflater.reset();
  return deflater;
}
 

Example 17

From project core_4, under directory /impl/src/main/java/org/richfaces/util/.

Source file: Util.java

  21 
vote

protected static byte[] encrypt(byte[] src){
  try {
    Deflater compressor=new Deflater(Deflater.BEST_SPEED);
    byte[] compressed=new byte[src.length + 100];
    compressor.setInput(src);
    compressor.finish();
    int totalOut=compressor.deflate(compressed);
    byte[] zipsrc=new byte[totalOut];
    System.arraycopy(compressed,0,zipsrc,0,totalOut);
    compressor.end();
    return CODEC.encode(zipsrc);
  }
 catch (  Exception e) {
    throw new FacesException("Error encode resource data",e);
  }
}
 

Example 18

From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/list/.

Source file: PrimitiveArrayEncoder.java

  21 
vote

/** 
 * Compress a string
 * @param expanded
 * @return compressed string.
 */
public static String compress(final String expanded){
  try {
    byte[] input=expanded.getBytes("US-ASCII");
    byte[] output=new byte[input.length];
    Deflater compresser=new Deflater();
    compresser.setInput(input);
    compresser.finish();
    final int size=compresser.deflate(output);
    return new String(output,0,size,"US-ASCII");
  }
 catch (  Exception ne) {
    ne.printStackTrace();
    return null;
  }
}
 

Example 19

From project echo2, under directory /src/webcontainer/java/nextapp/echo2/webcontainer/image/.

Source file: PngEncoder.java

  21 
vote

/** 
 * Writes the IDAT (Image data) chunks to the output stream.
 * @param out the OutputStream to write the chunk to
 * @param csum the Checksum that is updated as data is writtento the passed-in OutputStream
 * @throws IOException if a problem is encountered writing the output
 */
private void writeIdatChunks(OutputStream out,Checksum csum) throws IOException {
  int rowWidth=width * outputBpp;
  int row=0;
  Deflater deflater=new Deflater(compressionLevel);
  ByteArrayOutputStream byteOut=new ByteArrayOutputStream();
  DeflaterOutputStream defOut=new DeflaterOutputStream(byteOut,deflater);
  byte[] filteredPixelQueue=new byte[rowWidth];
  byte[][] outputPixelQueue=new byte[2][rowWidth];
  Arrays.fill(outputPixelQueue[1],(byte)0);
  int outputPixelQueueRow=0;
  int outputPixelQueuePrevRow=1;
  while (row < height) {
    if (filter == null) {
      defOut.write(0);
      translator.translate(outputPixelQueue[outputPixelQueueRow],row);
      defOut.write(outputPixelQueue[outputPixelQueueRow],0,rowWidth);
    }
 else {
      defOut.write(filter.getType());
      translator.translate(outputPixelQueue[outputPixelQueueRow],row);
      filter.filter(filteredPixelQueue,outputPixelQueue[outputPixelQueueRow],outputPixelQueue[outputPixelQueuePrevRow],outputBpp);
      defOut.write(filteredPixelQueue,0,rowWidth);
    }
    ++row;
    outputPixelQueueRow=row & 1;
    outputPixelQueuePrevRow=outputPixelQueueRow ^ 1;
  }
  defOut.finish();
  byteOut.close();
  writeInt(out,byteOut.size());
  csum.reset();
  out.write(IDAT);
  byteOut.writeTo(out);
  writeInt(out,(int)csum.getValue());
}
 

Example 20

From project echo3, under directory /src/server-java/webcontainer/nextapp/echo/webcontainer/util/.

Source file: PngEncoder.java

  21 
vote

/** 
 * Writes the IDAT (Image data) chunks to the output stream.
 * @param out the OutputStream to write the chunk to
 * @param csum the Checksum that is updated as data is writtento the passed-in OutputStream
 * @throws IOException if a problem is encountered writing the output
 */
private void writeIdatChunks(OutputStream out,Checksum csum) throws IOException {
  int rowWidth=width * outputBpp;
  int row=0;
  Deflater deflater=new Deflater(compressionLevel);
  ByteArrayOutputStream byteOut=new ByteArrayOutputStream();
  DeflaterOutputStream defOut=new DeflaterOutputStream(byteOut,deflater);
  byte[] filteredPixelQueue=new byte[rowWidth];
  byte[][] outputPixelQueue=new byte[2][rowWidth];
  Arrays.fill(outputPixelQueue[1],(byte)0);
  int outputPixelQueueRow=0;
  int outputPixelQueuePrevRow=1;
  while (row < height) {
    if (filter == null) {
      defOut.write(0);
      translator.translate(outputPixelQueue[outputPixelQueueRow],row);
      defOut.write(outputPixelQueue[outputPixelQueueRow],0,rowWidth);
    }
 else {
      defOut.write(filter.getType());
      translator.translate(outputPixelQueue[outputPixelQueueRow],row);
      filter.filter(filteredPixelQueue,outputPixelQueue[outputPixelQueueRow],outputPixelQueue[outputPixelQueuePrevRow],outputBpp);
      defOut.write(filteredPixelQueue,0,rowWidth);
    }
    ++row;
    outputPixelQueueRow=row & 1;
    outputPixelQueuePrevRow=outputPixelQueueRow ^ 1;
  }
  defOut.finish();
  byteOut.close();
  writeInt(out,byteOut.size());
  csum.reset();
  out.write(IDAT);
  byteOut.writeTo(out);
  writeInt(out,(int)csum.getValue());
}
 

Example 21

From project erjang, under directory /src/main/java/erjang/m/zlib/.

Source file: Native.java

  21 
vote

@BIF public static EBinary compress(EObject bin){
  EBinary b=bin.testBinary();
  if (b == null) {
    throw ERT.badarg(bin);
  }
  Deflater defl=new Deflater();
  BARR bos=new BARR();
  DeflaterOutputStream dos=new DeflaterOutputStream(bos,defl);
  try {
    b.writeTo(dos);
    dos.close();
  }
 catch (  IOException e) {
    throw new InternalError("should not happen");
  }
  return bos.asBinary();
}
 

Example 22

From project freemind, under directory /freemind/freemind/main/.

Source file: Tools.java

  21 
vote

public static String compress(String message){
  byte[] input=uTF8StringToByteArray(message);
  Deflater compressor=new Deflater();
  compressor.setLevel(Deflater.BEST_COMPRESSION);
  compressor.setInput(input);
  compressor.finish();
  ByteArrayOutputStream bos=new ByteArrayOutputStream(input.length);
  byte[] buf=new byte[1024];
  while (!compressor.finished()) {
    int count=compressor.deflate(buf);
    bos.write(buf,0,count);
  }
  try {
    bos.close();
  }
 catch (  IOException e) {
  }
  byte[] compressedData=bos.toByteArray();
  return toBase64(compressedData);
}
 

Example 23

From project gda-common, under directory /uk.ac.gda.common/src/uk/ac/gda/util/list/.

Source file: PrimitiveArrayEncoder.java

  21 
vote

/** 
 * Compress a string
 * @param expanded
 * @return compressed string.
 */
public static String compress(final String expanded){
  try {
    byte[] input=expanded.getBytes("US-ASCII");
    byte[] output=new byte[input.length];
    Deflater compresser=new Deflater();
    compresser.setInput(input);
    compresser.finish();
    final int size=compresser.deflate(output);
    return new String(output,0,size,"US-ASCII");
  }
 catch (  Exception ne) {
    ne.printStackTrace();
    return null;
  }
}
 

Example 24

From project httpClient, under directory /httpclient/src/test/java/org/apache/http/impl/client/integration/.

Source file: TestContentCodings.java

  21 
vote

/** 
 * Creates a new  {@link HttpRequestHandler} that will attempt to provide a deflate streamContent-Coding.
 * @param entityText the non-null String entity text to be returned by the server
 * @param rfc1951 if true, then the stream returned will be a raw RFC1951 deflate stream, which some servers return as a result of misinterpreting the HTTP 1.1 RFC. If false, then it will return an RFC2616 compliant deflate encoded zlib stream.
 * @return a non-null {@link HttpRequestHandler}
 */
private HttpRequestHandler createDeflateEncodingRequestHandler(final String entityText,final boolean rfc1951){
  return new HttpRequestHandler(){
    /** 
 * {@inheritDoc}
 */
    public void handle(    HttpRequest request,    HttpResponse response,    HttpContext context) throws HttpException, IOException {
      response.setEntity(new StringEntity(entityText));
      response.addHeader("Content-Type","text/plain");
      Header[] acceptEncodings=request.getHeaders("Accept-Encoding");
      for (      Header header : acceptEncodings) {
        for (        HeaderElement element : header.getElements()) {
          if ("deflate".equalsIgnoreCase(element.getName())) {
            response.addHeader("Content-Encoding","deflate");
            byte[] uncompressed=entityText.getBytes("utf-8");
            Deflater compressor=new Deflater(Deflater.DEFAULT_COMPRESSION,rfc1951);
            compressor.setInput(uncompressed);
            compressor.finish();
            byte[] output=new byte[100];
            int compressedLength=compressor.deflate(output);
            byte[] compressed=new byte[compressedLength];
            System.arraycopy(output,0,compressed,0,compressedLength);
            response.setEntity(new InputStreamEntity(new ByteArrayInputStream(compressed),compressedLength));
            return;
          }
        }
      }
    }
  }
;
}
 

Example 25

From project JGit, under directory /org.spearce.jgit/src/org/spearce/jgit/lib/.

Source file: ObjectWriter.java

  21 
vote

/** 
 * Construct an Object writer for the specified repository
 * @param d
 */
public ObjectWriter(final Repository d){
  r=d;
  buf=new byte[8192];
  md=Constants.newMessageDigest();
  def=new Deflater(r.getConfig().getCore().getCompression());
}
 

Example 26

From project JMaNGOS, under directory /Realm/src/main/java/org/jmangos/realm/network/packet/wow/client/.

Source file: CMSG_REQUEST_ACCOUNT_DATA.java

  21 
vote

@Override protected void runImpl(){
  if (this.type > AccountDataType.NUM_ACCOUNT_DATA_TYPES.getValue()) {
    return;
  }
  final HashMap<Integer,AccountData> adata=new HashMap<Integer,AccountData>();
  if (adata.containsKey(this.type)) {
    final Deflater compressor=new Deflater();
    final byte[] dataToCompress=adata.get(this.type).getData().getBytes(Charset.forName("UTF-8"));
    compressor.setInput(dataToCompress);
    compressor.finish();
    final ByteArrayOutputStream bos=new ByteArrayOutputStream(dataToCompress.length);
    final byte[] buf=new byte[1024];
    while (!compressor.finished()) {
      final int count=compressor.deflate(buf);
      bos.write(buf,0,count);
    }
    try {
      bos.close();
    }
 catch (    final IOException e) {
    }
    @SuppressWarnings("unused") final byte[] compressedData=bos.toByteArray();
  }
}
 

Example 27

From project kevoree-library, under directory /kalimucho/org.kevoree.library.kalimucho.kalimuchoNode/src/main/java/util/.

Source file: CompressByteArray.java

  21 
vote

/** 
 * Compress the byte array in specified compression level
 * @param mode compression level
 * @return the compressed byte array
 */
public byte[] compress(int mode){
  Deflater compresseur=new Deflater();
  compresseur.setLevel(mode);
  compresseur.setInput(aCompresser);
  compresseur.finish();
  ByteArrayOutputStream compresse=new ByteArrayOutputStream(aCompresser.length);
  byte[] buf=new byte[1024];
  while (!compresseur.finished()) {
    int octetsLus=compresseur.deflate(buf);
    compresse.write(buf,0,octetsLus);
  }
  try {
    compresse.close();
    return compresse.toByteArray();
  }
 catch (  IOException e) {
    return null;
  }
}
 

Example 28

From project netty, under directory /codec/src/main/java/io/netty/handler/codec/compression/.

Source file: JdkZlibEncoder.java

  21 
vote

/** 
 * Creates a new zlib encoder with the specified  {@code compressionLevel}and the specified wrapper.
 * @param compressionLevel {@code 1} yields the fastest compression and {@code 9} yields thebest compression.   {@code 0} means no compression.  The defaultcompression level is  {@code 6}.
 * @throws CompressionException if failed to initialize zlib
 */
public JdkZlibEncoder(ZlibWrapper wrapper,int compressionLevel){
  if (compressionLevel < 0 || compressionLevel > 9) {
    throw new IllegalArgumentException("compressionLevel: " + compressionLevel + " (expected: 0-9)");
  }
  if (wrapper == null) {
    throw new NullPointerException("wrapper");
  }
  if (wrapper == ZlibWrapper.ZLIB_OR_NONE) {
    throw new IllegalArgumentException("wrapper '" + ZlibWrapper.ZLIB_OR_NONE + "' is not "+ "allowed for compression.");
  }
  gzip=wrapper == ZlibWrapper.GZIP;
  deflater=new Deflater(compressionLevel,wrapper != ZlibWrapper.ZLIB);
}
 

Example 29

From project OpenEMRConnect, under directory /oeclib/src/main/java/ke/go/moh/oec/lib/.

Source file: Compresser.java

  21 
vote

static void compress(Message m){
  String xml=m.getXml();
  byte[] xmlBytes=null;
  try {
    xmlBytes=m.getXml().getBytes("UTF-8");
  }
 catch (  UnsupportedEncodingException ex) {
    Logger.getLogger(Compresser.class.getName()).log(Level.SEVERE,null,ex);
  }
  byte[] compressedXml=new byte[xmlBytes.length + 1000];
  m.setCompressedXml(compressedXml);
  Deflater compresser=new Deflater();
  compresser.setInput(xmlBytes);
  compresser.finish();
  int compressedXmlLength=compresser.deflate(compressedXml);
  m.setCompressedXmlLength(compressedXmlLength);
  compresser.end();
}
 

Example 30

From project PowerTutor, under directory /src/edu/umich/PowerTutor/service/.

Source file: PowerEstimator.java

  21 
vote

private void openLog(boolean init){
  try {
    String logFilename=context.getFileStreamPath("PowerTrace.log").getAbsolutePath();
    if (init && prefs.getBoolean("sendPermission",true) && new File(logFilename).length() > 0) {
      logUploader.upload(logFilename);
    }
    Deflater deflater=new Deflater();
    deflater.setDictionary(DEFLATE_DICTIONARY.getBytes());
    deflateStream=new DeflaterOutputStream(new FileOutputStream(logFilename));
    logStream=new OutputStreamWriter(deflateStream);
  }
 catch (  IOException e) {
    logStream=null;
    Log.e(TAG,"Failed to open log file.  No log will be kept.");
  }
}
 

Example 31

From project qpid-hessian, under directory /src/main/java/org/apache/qpid/contrib/hessian/.

Source file: AMQPHessianProxy.java

  21 
vote

private byte[] createRequestBody(Method method,Object[] args) throws IOException {
  String methodName=method.getName();
  if (_factory.isOverloadEnabled() && args != null && args.length > 0) {
    methodName=AbstractSkeleton.mangleName(method,false);
  }
  ByteArrayOutputStream payload=new ByteArrayOutputStream(256);
  OutputStream os;
  if (_factory.isCompressed()) {
    Deflater deflater=new Deflater(Deflater.DEFAULT_COMPRESSION,true);
    os=new DeflaterOutputStream(payload,deflater);
  }
 else {
    os=payload;
  }
  AbstractHessianOutput out=_factory.getHessianOutput(os);
  out.call(methodName,args);
  if (os instanceof DeflaterOutputStream) {
    ((DeflaterOutputStream)os).finish();
  }
  out.flush();
  return payload.toByteArray();
}
 

Example 32

From project riot, under directory /media/src/org/riotfamily/media/meta/.

Source file: FlashInfo.java

  21 
vote

public byte[] compress(byte[] bytes,int length){
  byte[] compressed=null;
  byte[] temp=new byte[length];
  Deflater deflater=new Deflater(Deflater.BEST_COMPRESSION);
  deflater.setInput(bytes,8,length - 8);
  deflater.finish();
  int compressedLength=deflater.deflate(temp);
  compressed=new byte[compressedLength + 8];
  System.arraycopy(bytes,0,compressed,0,8);
  System.arraycopy(temp,0,compressed,8,compressedLength);
  temp[0]=67;
  int bl=bytes.length;
  temp[4]=(byte)(bl & 0x000000FF);
  temp[5]=(byte)((bl & 0x0000FF00) >> 8);
  temp[6]=(byte)((bl & 0x00FF0000) >> 16);
  temp[7]=(byte)((bl & 0xFF000000) >> 24);
  return compressed;
}
 

Example 33

From project SpoutPlugin, under directory /src/main/java/org/getspout/spoutapi/packet/.

Source file: PacketAddonData.java

  21 
vote

@Override public void compress(){
  if (!compressed) {
    if (data != null) {
      Deflater deflater=new Deflater();
      deflater.setInput(data);
      deflater.setLevel(Deflater.BEST_COMPRESSION);
      deflater.finish();
      ByteArrayOutputStream bos=new ByteArrayOutputStream(data.length);
      byte[] buffer=new byte[1024];
      while (!deflater.finished()) {
        int bytesCompressed=deflater.deflate(buffer);
        bos.write(buffer,0,bytesCompressed);
      }
      try {
        bos.close();
      }
 catch (      IOException e) {
        e.printStackTrace();
      }
      data=bos.toByteArray();
    }
    compressed=true;
  }
}
 

Example 34

From project Switji, under directory /src/main/java/org/jinglenodes/session/persistence/.

Source file: PersistentCallSessionMapper.java

  21 
vote

public byte[] zip(final String data) throws UnsupportedEncodingException, IOException {
  byte[] input=data.getBytes(ENCODE);
  Deflater df=new Deflater();
  df.setInput(input);
  ByteArrayOutputStream baos=new ByteArrayOutputStream(input.length);
  df.finish();
  byte[] buff=new byte[1024];
  while (!df.finished()) {
    int count=df.deflate(buff);
    baos.write(buff,0,count);
  }
  baos.close();
  byte[] output=baos.toByteArray();
  log.debug("Original: " + input.length + "b - Compressed: "+ output.length+ "b");
  return output;
}
 

Example 35

From project TomP2P, under directory /src/main/java/net/tomp2p/utils/.

Source file: Utils.java

  21 
vote

public static byte[] compress(byte[] input){
  Deflater compressor=new Deflater();
  compressor.setLevel(Deflater.BEST_SPEED);
  compressor.setInput(input);
  compressor.finish();
  ByteArrayOutputStream bos=new ByteArrayOutputStream(input.length);
  byte[] buf=new byte[1024];
  while (!compressor.finished()) {
    int count=compressor.deflate(buf);
    bos.write(buf,0,count);
  }
  try {
    bos.close();
  }
 catch (  IOException e) {
  }
  return bos.toByteArray();
}
 

Example 36

From project jtrek, under directory /src/org/gamehost/jtrek/javatrek/.

Source file: TrekRawDataInterface.java

  20 
vote

public TrekRawDataInterface(Socket sck,TrekServer serverIn){
  TrekLog.logMessage("Creating Raw TrekPlayer thread...");
  server=serverIn;
  state=WAIT_LOGIN;
  outputBuffer=new String();
  macros=new Hashtable();
  playerOptions=new TrekPlayerOptions(this);
  shipName="";
  dbInt=new TrekJDBCInterface();
  messageQueue=new Vector();
  compressor=new Deflater();
  try {
    socket=sck;
    socket.setTcpNoDelay(true);
    in=sck.getInputStream();
    out=new DataOutputStream(new BufferedOutputStream(sck.getOutputStream()));
    try {
      int slashIndex=sck.getInetAddress().toString().indexOf('/');
      playerIP=sck.getInetAddress().toString().substring(slashIndex + 1);
      playerHostName=InetAddress.getByName(playerIP).toString();
    }
 catch (    Exception e) {
      TrekLog.logException(e);
    }
  }
 catch (  IOException ioe) {
    TrekLog.logMessage("Could not create Raw TrekPlayer object for " + sck.toString() + "!!");
  }
}
 

Example 37

From project xnio_1, under directory /api/src/main/java/org/xnio/.

Source file: XnioWorker.java

  20 
vote

/** 
 * Create a stream channel that compresses to the destination according to the configuration in the given option map.
 * @param delegate the channel to compress to
 * @param options the configuration options for the channel
 * @return a compressed channel
 * @throws IOException if the channel could not be constructed
 */
public StreamSinkChannel getDeflatingChannel(final StreamSinkChannel delegate,final OptionMap options) throws IOException {
  final int level=options.get(Options.COMPRESSION_LEVEL,-1);
  final boolean nowrap;
switch (options.get(Options.COMPRESSION_TYPE,CompressionType.DEFLATE)) {
case DEFLATE:
    nowrap=false;
  break;
case GZIP:
nowrap=true;
break;
default :
throw new IllegalArgumentException("Compression format not supported");
}
return getDeflatingChannel(delegate,new Deflater(level,nowrap));
}
 

Example 38

From project and-bible, under directory /jsword-tweaks/bakup/.

Source file: Zip.java

  19 
vote

public ByteArrayOutputStream compress() throws IOException {
  BufferedInputStream in=new BufferedInputStream(input);
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  DeflaterOutputStream out=new DeflaterOutputStream(bos,new Deflater(),BUF_SIZE);
  byte[] buf=new byte[BUF_SIZE];
  for (int count=in.read(buf); count != -1; count=in.read(buf)) {
    out.write(buf,0,count);
  }
  in.close();
  out.flush();
  out.close();
  return bos;
}
 

Example 39

From project candlepin, under directory /src/main/java/org/candlepin/util/.

Source file: X509V3ExtensionUtil.java

  19 
vote

private byte[] byteProcess(List<String> entries) throws IOException, UnsupportedEncodingException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  DeflaterOutputStream dos=new DeflaterOutputStream(baos,new Deflater(Deflater.BEST_COMPRESSION));
  for (  String segment : entries) {
    dos.write(segment.getBytes("UTF-8"));
    dos.write("\0".getBytes("UTF-8"));
  }
  dos.finish();
  dos.close();
  return baos.toByteArray();
}
 

Example 40

From project commons-compress, under directory /src/main/java/org/apache/commons/compress/archivers/zip/.

Source file: ZipArchiveOutputStream.java

  19 
vote

/** 
 * Sets the compression level for subsequent entries. <p>Default is Deflater.DEFAULT_COMPRESSION.</p>
 * @param level the compression level.
 * @throws IllegalArgumentException if an invalid compressionlevel is specified.
 */
public void setLevel(int level){
  if (level < Deflater.DEFAULT_COMPRESSION || level > Deflater.BEST_COMPRESSION) {
    throw new IllegalArgumentException("Invalid compression level: " + level);
  }
  hasCompressionLevelChanged=(this.level != level);
  this.level=level;
}
 

Example 41

From project dcm4che, under directory /dcm4che-core/src/main/java/org/dcm4che/io/.

Source file: DicomOutputStream.java

  19 
vote

private void switchTransferSyntax(String tsuid) throws IOException {
  bigEndian=tsuid.equals(UID.ExplicitVRBigEndian);
  explicitVR=!tsuid.equals(UID.ImplicitVRLittleEndian);
  if (tsuid.equals(UID.DeflatedExplicitVRLittleEndian) || tsuid.equals(UID.JPIPReferencedDeflate)) {
    super.out=new DeflaterOutputStream(super.out,new Deflater(Deflater.DEFAULT_COMPRESSION,true));
  }
}
 

Example 42

From project Gemini-Blueprint, under directory /test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/util/jar/.

Source file: JarUtils.java

  19 
vote

/** 
 * Creates a jar based on the given entries and manifest. This method will always close the given output stream.
 * @param manifest jar manifest
 * @param entries map of resources keyed by the jar entry named
 * @param outputStream output stream for writing the jar
 * @return number of byte written to the jar
 */
public static int createJar(Manifest manifest,Map entries,OutputStream outputStream) throws IOException {
  int writtenBytes=0;
  JarOutputStream jarStream=null;
  try {
    jarStream=(manifest != null ? new JarOutputStream(outputStream,manifest) : new JarOutputStream(outputStream));
    jarStream.setLevel(Deflater.NO_COMPRESSION);
    for (Iterator iter=entries.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry element=(Map.Entry)iter.next();
      String entryName=(String)element.getKey();
      if (!entryName.startsWith(SLASH))       entryName=SLASH + entryName;
      Resource entryValue=(Resource)element.getValue();
      if (MANIFEST_JAR_LOCATION.equals(entryName)) {
        iter.remove();
      }
 else {
        writtenBytes+=JarUtils.writeToJar(entryValue,entryName,jarStream);
      }
    }
  }
  finally {
    try {
      jarStream.flush();
    }
 catch (    IOException ex) {
    }
    try {
      jarStream.finish();
    }
 catch (    IOException ex) {
    }
  }
  return writtenBytes;
}
 

Example 43

From project HBase-Lattice, under directory /hbl/src/main/java/com/inadco/hbl/compiler/.

Source file: YamlModelParser.java

  19 
vote

public static String encodeCubeModel(String yamlStr) throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  Writer w=new OutputStreamWriter(new DeflaterOutputStream(baos,new Deflater(9,false)),"utf-8");
  w.append(yamlStr);
  w.close();
  String result=new String(Base64.encodeBase64(baos.toByteArray()),"US-ASCII");
  decodeCubeModel(result);
  return result;
}
 

Example 44

From project jgraphx, under directory /src/com/mxgraph/util/png/.

Source file: mxPngImageEncoder.java

  19 
vote

private void writeIDAT() throws IOException {
  IDATOutputStream ios=new IDATOutputStream(dataOutput,8192);
  DeflaterOutputStream dos=new DeflaterOutputStream(ios,new Deflater(9));
  Raster ras=image.getData(new Rectangle(image.getMinX(),image.getMinY(),image.getWidth(),image.getHeight()));
  if (skipAlpha) {
    int numBands=ras.getNumBands() - 1;
    int[] bandList=new int[numBands];
    for (int i=0; i < numBands; i++) {
      bandList[i]=i;
    }
    ras=ras.createChild(0,0,ras.getWidth(),ras.getHeight(),0,0,bandList);
  }
  if (interlace) {
    encodePass(dos,ras,0,0,8,8);
    encodePass(dos,ras,4,0,8,8);
    encodePass(dos,ras,0,4,4,8);
    encodePass(dos,ras,2,0,4,4);
    encodePass(dos,ras,0,2,2,4);
    encodePass(dos,ras,1,0,2,2);
    encodePass(dos,ras,0,1,1,2);
  }
 else {
    encodePass(dos,ras,0,0,1,1);
  }
  dos.finish();
  ios.flush();
}
 

Example 45

From project jPOS, under directory /jpos/src/test/java/org/jpos/util/.

Source file: DailyLogListenerTest.java

  19 
vote

@Test public void testCloseCompressedOutputStream() throws Throwable {
  OutputStream os=new DeflaterOutputStream(new PrintStream(new ByteArrayOutputStream()),new Deflater());
  DailyLogListener dailyLogListener=new DailyLogListener();
  dailyLogListener.closeCompressedOutputStream(os);
  assertTrue("Test completed without Exception",true);
}
 

Example 46

From project jsword, under directory /src/main/java/org/crosswire/common/compress/.

Source file: Zip.java

  19 
vote

public ByteArrayOutputStream compress() throws IOException {
  BufferedInputStream in=new BufferedInputStream(input);
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  DeflaterOutputStream out=new DeflaterOutputStream(bos,new Deflater(),BUF_SIZE);
  byte[] buf=new byte[BUF_SIZE];
  for (int count=in.read(buf); count != -1; count=in.read(buf)) {
    out.write(buf,0,count);
  }
  in.close();
  out.flush();
  out.close();
  return bos;
}
 

Example 47

From project Red5, under directory /src/org/red5/io/amf3/.

Source file: ByteArray.java

  19 
vote

/** 
 * Compress contents using zlib.
 */
public void compress(){
  IoBuffer tmp=IoBuffer.allocate(0);
  tmp.setAutoExpand(true);
  DeflaterOutputStream deflater=new DeflaterOutputStream(tmp.asOutputStream(),new Deflater(Deflater.BEST_COMPRESSION));
  byte[] tmpData=new byte[data.limit()];
  data.position(0);
  data.get(tmpData);
  try {
    deflater.write(tmpData);
    deflater.finish();
  }
 catch (  IOException e) {
    tmp.free();
    throw new RuntimeException("could not compress data",e);
  }
 finally {
    if (deflater != null) {
      try {
        deflater.close();
      }
 catch (      IOException e1) {
      }
    }
  }
  data.free();
  data=tmp;
  data.flip();
  prepareIO();
}
 

Example 48

From project red5-mavenized, under directory /red5_base/src/main/java/org/red5/io/amf3/.

Source file: ByteArray.java

  19 
vote

/** 
 * Compress contents using zlib.
 */
public void compress(){
  ByteBuffer tmp=ByteBuffer.allocate(0);
  tmp.setAutoExpand(true);
  DeflaterOutputStream deflater=new DeflaterOutputStream(tmp.asOutputStream(),new Deflater(Deflater.BEST_COMPRESSION));
  byte[] tmpData=new byte[data.limit()];
  data.position(0);
  data.get(tmpData);
  try {
    deflater.write(tmpData);
    deflater.finish();
  }
 catch (  IOException e) {
    tmp.release();
    throw new RuntimeException("could not compress data",e);
  }
  data.release();
  data=tmp;
  data.flip();
  prepareIO();
}
 

Example 49

From project red5-server, under directory /src/org/red5/io/amf3/.

Source file: ByteArray.java

  19 
vote

/** 
 * Compress contents using zlib.
 */
public void compress(){
  IoBuffer tmp=IoBuffer.allocate(0);
  tmp.setAutoExpand(true);
  DeflaterOutputStream deflater=new DeflaterOutputStream(tmp.asOutputStream(),new Deflater(Deflater.BEST_COMPRESSION));
  byte[] tmpData=new byte[data.limit()];
  data.position(0);
  data.get(tmpData);
  try {
    deflater.write(tmpData);
    deflater.finish();
  }
 catch (  IOException e) {
    tmp.free();
    throw new RuntimeException("could not compress data",e);
  }
 finally {
    if (deflater != null) {
      try {
        deflater.close();
      }
 catch (      IOException e1) {
      }
    }
  }
  data.free();
  data=tmp;
  data.flip();
  prepareIO();
}
 

Example 50

From project showcase, under directory /src/main/java/org/richfaces/demo/mediaOutput/.

Source file: MediaBean.java

  19 
vote

@Override public void write(InputStream inChannel,OutputStream outChannel) throws IOException {
  if (isIndexed) {
    super.write(inChannel,outChannel);
  }
 else {
    byte[] ps=new byte[imageWidth * 3 + 1];
    byte[] bs=new byte[imageWidth * 3 + 1];
    assert(bs.length < BUFFER_SIZE);
    int read=0;
    InputStream inflaterInputStream=new BufferedInputStream(new InflaterInputStream(new LimitedInputStream(inChannel),new Inflater(),2048),BUFFER_SIZE);
    ByteArrayOutputStream baos=new ByteArrayOutputStream(sectionLength);
    DeflaterOutputStream deflaterOutputStream=new DeflaterOutputStream(baos,new Deflater(),2048);
    while ((read=(inflaterInputStream.read(bs))) > 0) {
      reconstruct(bs,ps);
      transformColors(bs,1,read - 1);
      deflaterOutputStream.write(bs,0,read);
      byte[] swapVar=bs;
      bs=ps;
      ps=swapVar;
    }
    deflaterOutputStream.finish();
    byte[] compressedSectionBytes=baos.toByteArray();
    writeInt(outChannel,compressedSectionBytes.length);
    CRC32 crc32=new CRC32();
    outChannel.write(chunkTypeBytes);
    crc32.update(chunkTypeBytes);
    if (inChannel.skip(4) < 4) {
      throw new IllegalArgumentException();
    }
    outChannel.write(compressedSectionBytes);
    writeInt(outChannel,(int)crc32.getValue());
  }
}
 

Example 51

From project Supersonic, under directory /src/main/java/be/hehehe/supersonic/service/.

Source file: Library.java

  19 
vote

private void saveToFile() throws SupersonicException {
  ZipOutputStream zip=null;
  File libraryDirectory=new File(LIBRARY_FILEPATH);
  if (!libraryDirectory.exists()) {
    libraryDirectory.mkdir();
  }
  File libraryFile=new File(LIBRARY_FILE);
  String json=new JSONSerializer().deepSerialize(albums);
  try {
    zip=new ZipOutputStream(new FileOutputStream(libraryFile));
    zip.setLevel(Deflater.BEST_COMPRESSION);
    zip.putNextEntry(new ZipEntry("library.json"));
    IOUtils.write(json,zip);
    zip.closeEntry();
  }
 catch (  IOException e) {
    throw new SupersonicException(e);
  }
 finally {
    IOUtils.closeQuietly(zip);
  }
}