List of usage examples for java.util.zip Deflater setInput
public void setInput(ByteBuffer input)
From source file:com.newrelic.agent.android.harvest.HarvestConnection.java
private byte[] deflate(String str) { Deflater deflater = new Deflater(); deflater.setInput(str.getBytes()); deflater.finish();/*from w w w .j av a 2 s .c o m*/ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] bArr = new byte[AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD]; while (!deflater.finished()) { int deflate = deflater.deflate(bArr); if (deflate <= 0) { this.log.error("HTTP request contains an incomplete payload"); } byteArrayOutputStream.write(bArr, 0, deflate); } deflater.end(); return byteArrayOutputStream.toByteArray(); }
From source file:org.jmangos.realm.network.packet.wow.client.CMSG_REQUEST_ACCOUNT_DATA.java
@Override protected void runImpl() { if (this.type > AccountDataType.NUM_ACCOUNT_DATA_TYPES.getValue()) { return;// w ww .java2 s . c o m } final HashMap<Integer, AccountData> adata = new HashMap<Integer, AccountData>(); // getAccount().getAccountData(); // /* // disabled // by // paalgyula // */ 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) { } // FIXME NEED COMPLETE @SuppressWarnings("unused") final byte[] compressedData = bos.toByteArray(); } }
From source file:org.apache.qpid.multiconsumer.AMQTest.java
private String compressString(String string) throws Exception { long start = System.currentTimeMillis(); byte[] input = string.getBytes(); Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION); compressor.setInput(input); compressor.finish();//w w w .j a v a 2s. c om // Get byte array from output of compressor ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length); byte[] buf = new byte[1024]; while (!compressor.finished()) { int cnt = compressor.deflate(buf); baos.write(buf, 0, cnt); } baos.close(); byte[] output = baos.toByteArray(); // Convert byte array into String byte[] base64 = Base64.encodeBase64(output); String sComp = new String(base64, UTF8); long diff = System.currentTimeMillis() - start; System.out.println( "Compressed text from " + input.length + " to " + sComp.getBytes().length + " in " + diff + " ms"); System.out.println("Compressed text = '" + sComp + "'"); return sComp; }
From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.safe.TSafeDeflateJsonQueryHandler.java
@Override public ByteBuffer encode(final WebsockQuery query) throws EncodeException { ByteBuffer result = null;/*www . j a v a 2 s . c o m*/ try { final JSONObject obj = JsonConverter.toJson(query); byte[] data = obj.toString().getBytes(); //compress final Deflater deflater = new Deflater(fCompression, true); deflater.setInput(data); int read = 0; int totalSize = 0; final List<byte[]> buffers = new LinkedList<byte[]>(); final byte[] buffer = new byte[BUFFER_SIZE]; read = deflater.deflate(buffer, 0, BUFFER_SIZE, Deflater.SYNC_FLUSH); while (read > 0) { totalSize += read; buffers.add(Arrays.copyOf(buffer, read)); read = deflater.deflate(buffer, 0, BUFFER_SIZE, Deflater.SYNC_FLUSH); } result = fuse(buffers, totalSize); if (fDebug) { fTotalBytesOut += totalSize; fLogger.log(Level.FINEST, "encoded compressed JSON message: " + totalSize + " bytes\n" + "total bytes sent: " + fTotalBytesOut); } } catch (JSONException e) { e.printStackTrace(); throw new EncodeException(query, "failed to encode JSON", e); } return result; }
From source file:org.graylog.plugins.beats.BeatsFrameDecoderTest.java
private ChannelBuffer buildCompressedFrame(byte[] payload, int compressionLevel) { final Deflater deflater = new Deflater(compressionLevel); deflater.setInput(payload); deflater.finish();//from w w w . j a v a2 s. c om final byte[] compressedPayload = new byte[1024]; final int compressedPayloadLength = deflater.deflate(compressedPayload); deflater.end(); final ChannelBuffer buffer = ChannelBuffers.buffer(6 + compressedPayloadLength); buffer.writeByte('2'); buffer.writeByte('C'); // Compressed payload length buffer.writeInt(compressedPayloadLength); // Compressed payload buffer.writeBytes(compressedPayload, 0, compressedPayloadLength); return buffer; }
From source file:spartanfinal.ProcessFiles.java
public byte[] compress(byte[] data) throws IOException { Deflater deflater = new Deflater(); deflater.setLevel(Deflater.BEST_COMPRESSION); deflater.setInput(data); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); deflater.finish();//from w w w . ja v a2 s . c o m byte[] buffer = new byte[1024]; while (!deflater.finished()) { int count = deflater.deflate(buffer); outputStream.write(buffer, 0, count); } byte[] output = outputStream.toByteArray(); return output; }
From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.unsafe.DeflateJsonQueryHandler.java
@Override public ByteBuffer encode(final WebsockQuery query) throws EncodeException { ByteBuffer result = null;/* w w w.j a v a2s.co m*/ try { final JSONObject obj = JsonConverter.toJson(query); byte[] data = obj.toString().getBytes(); //compress final Deflater deflater = new Deflater(fCompression, true); deflater.setInput(data); deflater.finish(); int totalSize = 0; int read = deflater.deflate(fBuffer, 0, BUFFER_SIZE, Deflater.SYNC_FLUSH); while (true) { totalSize += read; if (deflater.finished()) { //if finished, directly add buffer fBuffers.add(fBuffer); break; } else { //make a copy, reuse buffer fBuffers.add(Arrays.copyOf(fBuffer, read)); read = deflater.deflate(fBuffer, 0, BUFFER_SIZE, Deflater.SYNC_FLUSH); } } result = fuse(totalSize); deflater.end(); if (fDebug) { fTotalBytesOut += totalSize; fLogger.log(Level.FINEST, "encoded compressed JSON message: " + totalSize + " bytes\n" + "total bytes sent: " + fTotalBytesOut); } } catch (JSONException e) { e.printStackTrace(); throw new EncodeException(query, "failed to encode JSON", e); } return result; }
From source file:net.fenyo.mail4hotspot.dns.Msg.java
private byte[] process(final AdvancedServices advancedServices, final Inet4Address address) throws GeneralException { // log.debug("processing message of type " + input_buffer[0]); // for (byte b : input_buffer) log.debug("received byte: [" + b + "]"); if (input_buffer.length == 0) throw new GeneralException("invalid size"); if (input_buffer[0] == 0) { // UTF-8 message type final ByteBuffer bb = ByteBuffer.allocate(input_buffer.length - 1); bb.put(input_buffer, 1, input_buffer.length - 1); bb.position(0);//from w ww.j a va2 s . co m final String query = Charset.forName("UTF-8").decode(bb).toString(); // log.debug("RECEIVED query: [" + query + "]"); final String reply = advancedServices.processQueryFromClient(query, address); // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill output_buffer final ByteBuffer ob = Charset.forName("UTF-8").encode(reply); ob.get(output_buffer = new byte[ob.limit()]); output_size = output_buffer.length; } else { // binary message type // log.debug("processing binary message"); final ByteBuffer bb = ByteBuffer.allocate(input_buffer[0]); bb.put(input_buffer, 1, input_buffer[0]); bb.position(0); final String query = Charset.forName("UTF-8").decode(bb).toString(); // log.debug("RECEIVED query: [" + query + "]"); final BinaryMessageReply reply = advancedServices.processBinaryQueryFromClient(query, Arrays.copyOfRange(input_buffer, input_buffer[0] + 1, input_buffer.length), address); // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill string_part final ByteBuffer ob = Charset.forName("UTF-8").encode(reply.reply_string); final byte[] string_part = new byte[ob.limit()]; ob.get(string_part); if (string_part.length > 255) throw new GeneralException("string_part too long"); output_buffer = new byte[string_part.length + reply.reply_data.length + 1]; output_buffer[0] = (byte) string_part.length; for (int i = 0; i < string_part.length; i++) output_buffer[i + 1] = string_part[i]; for (int i = 0; i < reply.reply_data.length; i++) output_buffer[string_part.length + i + 1] = reply.reply_data[i]; output_size = output_buffer.length; } synchronized (compressed) { // http://docs.oracle.com/javase/7/docs/api/java/util/zip/Deflater.html#deflate(byte[]) // log.debug("processing binary message: length before compressing: " + output_buffer.length); final Deflater compresser = new Deflater(); compresser.setInput(output_buffer); compresser.finish(); final int nbytes = compresser.deflate(compressed); // log.debug("RET: " + nbytes); // log.debug("COMPRESSED: " + compressed.length); // log.debug("processing binary message: length after compressing: " + nbytes); if (compressed.length == nbytes) { log.error("compressed buffer too small..."); throw new GeneralException("compressed buffer too small..."); } output_buffer = Arrays.copyOf(compressed, nbytes); output_size = output_buffer.length; } synchronized (is_processed) { is_processed = true; } return new byte[] { 'E', 0 }; // 'E'rror 0 == OK }
From source file:org.dragonet.proxy.protocol.packet.LoginPacket.java
@Override public void encode() { try {//from w w w.ja v a2 s. com setChannel(NetworkChannel.CHANNEL_PRIORITY); // Basic info JSONObject jsonBasic = new JSONObject(); String b64Signature; String b64User; { JSONObject jsonSignature = new JSONObject(); jsonSignature.put("alg", "ES384"); jsonSignature.put("x5u", "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE+SKWsy2I5ecBTPZEfNgwgvuin2/iqqi3haMxXPpknsVKINpp5E7jlygXqBmSJad5VG+1uq75V9irGEtmpUINP5xhYiOrlEma+2aBJIUe17UT/r50yTnDhDrPoOY/eAHL"); b64Signature = Base64.getEncoder().encodeToString(jsonSignature.toString().getBytes("UTF-8")); } { JSONObject jsonUser = new JSONObject(); jsonUser.put("exp", System.currentTimeMillis() / 1000L + (60 * 10)); JSONObject jsonUserInfo = new JSONObject(); jsonUserInfo.put("displayName", username); jsonUserInfo.put("identity", clientUuid.toString()); jsonUser.put("extraData", jsonUserInfo); jsonUser.put("identityPublicKey", ""); // publicKey jsonUser.put("nbf", System.currentTimeMillis() / 1000L); b64User = Base64.getEncoder().encodeToString(jsonUser.toString().getBytes("UTF-8")); System.out.println(jsonUser.toString()); } String b64Basic = b64Signature + "." + b64User; // Meta info JSONObject jsonMeta = new JSONObject(); String strMeta; { jsonMeta.put("ClientRandomId", clientID); jsonMeta.put("ServerAddress", serverAddress); jsonMeta.put("SkinId", skin.getModel()); jsonMeta.put("SkinData", Base64.getEncoder().encodeToString(skin.getData())); strMeta = Base64.getEncoder().encodeToString(jsonMeta.toString().getBytes("UTF-8")); } String b64Meta = b64Signature + "." + strMeta; byte[] chainData; { byte[] dataBasic = b64Basic.getBytes("UTF-8"); byte[] dataMeta = b64Meta.getBytes("UTF-8"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PEBinaryWriter writer = new PEBinaryWriter(bos); writer.switchEndianness(); writer.writeInt(dataBasic.length); writer.switchEndianness(); writer.write(dataBasic); writer.switchEndianness(); writer.writeInt(dataMeta.length); writer.switchEndianness(); writer.write(dataMeta); chainData = bos.toByteArray(); } JSONObject jsonChain = new JSONObject(); jsonChain.put("chain", chainData); String strChain = jsonChain.toString(); byte[] b64Chain = Base64.getEncoder().encode(strChain.getBytes("UTF-8")); Deflater deflater = new Deflater(7); deflater.setInput(b64Chain); deflater.finish(); byte[] buff = new byte[40960]; int deflated = deflater.deflate(buff); buff = ArrayUtils.subarray(buff, 0, deflated); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PEBinaryWriter writer = new PEBinaryWriter(bos); writer.writeByte((byte) (this.pid() & 0xFF)); writer.writeInt(protocol); writer.writeInt(buff.length); writer.write(buff); this.setData(bos.toByteArray()); } catch (IOException | JSONException e) { } }
From source file:com.hichinaschool.flashcards.libanki.Utils.java
/** * Compress data.//from w w w .j a v a2s .co m * @param bytesToCompress is the byte array to compress. * @return a compressed byte array. * @throws java.io.IOException */ public static byte[] compress(byte[] bytesToCompress, int comp) throws IOException { // Compressor with highest level of compression. Deflater compressor = new Deflater(comp, true); // Give the compressor the data to compress. compressor.setInput(bytesToCompress); compressor.finish(); // Create an expandable byte array to hold the compressed data. // It is not necessary that the compressed data will be smaller than // the uncompressed data. ByteArrayOutputStream bos = new ByteArrayOutputStream(bytesToCompress.length); // Compress the data byte[] buf = new byte[65536]; while (!compressor.finished()) { bos.write(buf, 0, compressor.deflate(buf)); } bos.close(); // Get the compressed data return bos.toByteArray(); }