List of usage examples for java.util.zip Deflater Deflater
public Deflater(int level, boolean nowrap)
From source file:divconq.ctp.stream.GzipStream.java
@Override public ReturnOption handle(FileDescriptor file, ByteBuf data) { if (file == FileDescriptor.FINAL) return this.downstream.handle(file, data); // we don't know what to do with a folder at this stage - gzip is for file content only // folder scanning is upstream in the FileSourceStream and partners if (file.isFolder()) return ReturnOption.CONTINUE; // init if not set for this round of processing if (this.deflater == null) { this.deflater = new Deflater(this.compressionLevel, true); this.crc.reset(); this.writeHeader = true; }/*from www . ja v a 2 s . c om*/ ByteBuf in = data; ByteBuf out = null; if (in != null) { byte[] inAry = in.array(); // always allow for a header (10) plus footer (8) plus extra (12) // in addition to content int sizeEstimate = (int) Math.ceil(in.readableBytes() * 1.001) + 30; out = Hub.instance.getBufferAllocator().heapBuffer(sizeEstimate); if (this.writeHeader) { this.writeHeader = false; out.writeBytes(gzipHeader); } this.crc.update(inAry, in.arrayOffset(), in.writerIndex()); this.deflater.setInput(inAry, in.arrayOffset(), in.writerIndex()); while (!this.deflater.needsInput()) deflate(out); } else out = Hub.instance.getBufferAllocator().heapBuffer(30); FileDescriptor blk = new FileDescriptor(); if (StringUtil.isEmpty(this.lastpath)) { if (StringUtil.isNotEmpty(this.nameHint)) this.lastpath = "/" + this.nameHint; else if (file.getPath() != null) this.lastpath = "/" + GzipUtils.getCompressedFilename(file.path().getFileName()); else this.lastpath = "/" + FileUtil.randomFilename("gz"); } blk.setPath(this.lastpath); file.setModTime(System.currentTimeMillis()); if (file.isEof()) { this.deflater.finish(); while (!this.deflater.finished()) deflate(out); int crcValue = (int) this.crc.getValue(); out.writeByte(crcValue); out.writeByte(crcValue >>> 8); out.writeByte(crcValue >>> 16); out.writeByte(crcValue >>> 24); int uncBytes = this.deflater.getTotalIn(); out.writeByte(uncBytes); out.writeByte(uncBytes >>> 8); out.writeByte(uncBytes >>> 16); out.writeByte(uncBytes >>> 24); this.deflater.end(); this.deflater = null; // cause a reset for next time we use stream blk.setEof(true); } if (in != null) in.release(); return this.downstream.handle(blk, out); }
From source file:com.tremolosecurity.unison.u2f.util.U2fUtil.java
public static String encode(List<SecurityKeyData> devices, String encyrptionKeyName) throws Exception { ArrayList<KeyHolder> keys = new ArrayList<KeyHolder>(); for (SecurityKeyData dr : devices) { KeyHolder kh = new KeyHolder(); kh.setCounter(dr.getCounter());//from w w w. j a va2 s . co m kh.setEnrollmentTime(dr.getEnrollmentTime()); kh.setKeyHandle(dr.getKeyHandle()); kh.setPublicKey(dr.getPublicKey()); kh.setTransports(dr.getTransports()); keys.add(kh); } String json = gson.toJson(keys); EncryptedMessage msg = new EncryptedMessage(); SecretKey key = GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(encyrptionKeyName); if (key == null) { throw new Exception("Queue message encryption key not found"); } Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); msg.setMsg(cipher.doFinal(json.getBytes("UTF-8"))); msg.setIv(cipher.getIV()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true)); compressor.write(gson.toJson(msg).getBytes("UTF-8")); compressor.flush(); compressor.close(); String b64 = new String(Base64.encodeBase64(baos.toByteArray())); return b64; }
From source file:com.alibaba.citrus.service.requestcontext.session.encoder.AbstractSerializationEncoder.java
/** ? */ public String encode(Map<String, Object> attrs, StoreContext storeContext) throws SessionEncoderException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 1. ?/* w ww. j av a 2 s .com*/ // 2. Deflater def = new Deflater(Deflater.BEST_COMPRESSION, false); DeflaterOutputStream dos = new DeflaterOutputStream(baos, def); try { serializer.serialize(assertNotNull(attrs, "objectToEncode is null"), dos); } catch (Exception e) { throw new SessionEncoderException("Failed to encode session state", e); } finally { try { dos.close(); } catch (IOException e) { } def.end(); } byte[] plaintext = baos.toByteArray().toByteArray(); // 3. byte[] cryptotext = encrypt(plaintext); // 4. base64? try { String encodedValue = new String(Base64.encodeBase64(cryptotext, false), "ISO-8859-1"); return URLEncoder.encode(encodedValue, "ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new SessionEncoderException("Failed to encode session state", e); } }
From source file:ch.cern.security.saml2.utils.xml.XMLUtils.java
/** * Compress the xml string and encodes it in Base64 * /*from ww w . j a v a 2 s.c om*/ * @param xmlString * @param isDebugEnabled * @return xml string encoded * @throws IOException * @throws UnsupportedEncodingException */ public static String xmlDeflateAndEncode(String xmlString, boolean isDebugEnabled) throws IOException, UnsupportedEncodingException { if (isDebugEnabled) nc.notice(xmlString); // Deflate the SAMLResponse value ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); Deflater deflater = new Deflater(Deflater.DEFLATED, true); DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater); deflaterStream.write(xmlString.getBytes()); deflaterStream.finish(); // Encoded the deflatedResponse in base64 Base64 base64encoder = new Base64(); String base64response = new String(base64encoder.encode(bytesOut.toByteArray()), "UTF-8"); if (isDebugEnabled) nc.notice(base64response); return base64response; }
From source file:ZipUtil.java
public static void zipFileToFile(File flSource, File flTarget) throws IOException { Deflater oDeflate = new Deflater(Deflater.DEFLATED, false); FileInputStream stmFileIn = new FileInputStream(flSource); FileOutputStream stmFileOut = new FileOutputStream(flTarget); DeflaterOutputStream stmDeflateOut = new DeflaterOutputStream(stmFileOut, oDeflate); try {//from www .ja va 2s . c om // FileUtil.inputStreamToOutputStream(stmFileIn, stmDeflateOut); } //end try finally { stmDeflateOut.finish(); stmDeflateOut.flush(); stmDeflateOut.close(); stmFileOut.close(); stmFileIn.close(); } }
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;//w w w . ja 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.simbasecurity.core.saml.SAMLServiceImpl.java
protected String encodeSAMLRequest(byte[] pSAMLRequest) throws RuntimeException { Base64 base64Encoder = new Base64(); try {//w ww. j a v a 2 s .com ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); DeflaterOutputStream def = new DeflaterOutputStream(byteArray, deflater); def.write(pSAMLRequest); def.close(); byteArray.close(); String stream = new String(base64Encoder.encode(byteArray.toByteArray())); return stream.trim(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.squale.welcom.struts.webServer.WebEngine.java
/** * gzip / deflate / none// w w w . j ava 2 s .c o m * * @return OutPuStream en focntion de la configuration * @throws IOException IOException */ public OutputStream getOutputStream() throws IOException { OutputStream out; if ((request.getHeader("Accept-Encoding") != null) && (request.getHeader("Accept-Encoding").indexOf( WelcomConfigurator.getMessage(WelcomConfigurator.OPTIFLUX_COMPRESSION_MODE).toLowerCase()) > -1)) { response.setHeader("Content-Encoding", WelcomConfigurator.getMessage(WelcomConfigurator.OPTIFLUX_COMPRESSION_MODE).toLowerCase()); if (Util.isEqualsIgnoreCase(WelcomConfigurator.getMessage(WelcomConfigurator.OPTIFLUX_COMPRESSION_MODE), "deflate")) { out = new DeflaterOutputStream(response.getOutputStream(), new Deflater(COMPRESSION_LEVEL, true)); } else { out = new GZIPOutputStream(response.getOutputStream()); } } else { out = response.getOutputStream(); } return out; }
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;/*from w w w .j a v a 2 s . c om*/ 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:com.alibaba.citrus.service.requestcontext.session.valueencoder.AbstractSessionValueEncoder.java
private byte[] compress(byte[] data) throws SessionValueEncoderException { if (!doCompress()) { return data; }//from w w w . j a v a 2 s . c o m ByteArrayOutputStream baos = new ByteArrayOutputStream(); Deflater def = new Deflater(Deflater.BEST_COMPRESSION, false); DeflaterOutputStream dos = new DeflaterOutputStream(baos, def); try { dos.write(data); } catch (Exception e) { throw new SessionValueEncoderException(e); } finally { try { dos.close(); } catch (IOException e) { } def.end(); } return baos.toByteArray(); }