List of usage examples for java.util.zip Deflater Deflater
public Deflater(int level, boolean nowrap)
From source file:org.resthub.rpc.AMQPProxy.java
/** * Create the request message body// w ww.j av a 2s.c o m * * @param method * @param args * @return * @throws IOException */ private byte[] createRequestBody(Method method, Object[] args) throws IOException { 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; } _factory.getSerializationHandler().writeMethodCall(method, args, os); return payload.toByteArray(); }
From source file:org.codice.ddf.security.common.jaxrs.RestSecurity.java
/** * Deflates a value and Base64 encodes the result. * * @param value value to deflate and Base64 encode * @return String/*from w ww .j a v a2s. c o m*/ * @throws IOException if the value cannot be converted */ public static String deflateAndBase64Encode(String value) throws IOException { ByteArrayOutputStream valueBytes = new ByteArrayOutputStream(); try (OutputStream tokenStream = new DeflaterOutputStream(valueBytes, new Deflater(Deflater.DEFLATED, GZIP_COMPATIBLE))) { tokenStream.write(value.getBytes(StandardCharsets.UTF_8)); tokenStream.close(); return Base64.getEncoder().encodeToString(valueBytes.toByteArray()); } }
From source file:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java
/** * Get String with the SAML2 AuthnRequest message * @param format -1=plain, 1=base64/*from w ww. ja v a 2 s. c o m*/ * @return * @throws XMLStreamException * @throws IOException */ public String getRequest(int format) throws XMLStreamException, IOException { _logger.info("For ID: " + this._id); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(baos, compresser); StringWriter sw = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = null; // ugly but effective: if (format == base64) { writer = factory.createXMLStreamWriter(deflaterOutputStream); } else { writer = factory.createXMLStreamWriter(sw); } writer.writeStartElement("samlp", "AuthnRequest", "urn:oasis:names:tc:SAML:2.0:protocol"); writer.writeNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); writer.writeAttribute("ID", _id); writer.writeAttribute("Version", "2.0"); writer.writeAttribute("IssueInstant", this._issueInstant); writer.writeAttribute("ProtocolBinding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); writer.writeAttribute("AssertionConsumerServiceURL", _acsUrl); writeIssuer(writer); writeNameIDPolicy(writer); writeRequestedAuthnContext(writer); writer.writeEndElement(); writer.flush(); if (format == base64) { deflaterOutputStream.close(); byte[] bain = baos.toByteArray(); byte[] encoded = Base64.encodeBase64(bain, false); String result = new String(encoded, Charset.forName("UTF-8")); return result; } else { return sw.toString(); } }
From source file:it.greenvulcano.util.zip.ZipHelper.java
/** * Compress the input buffer./*from www . ja v a2 s. co m*/ * * @param input * the data to compress * @return the compressed data * @throws ZipHelperException * if error occurs */ public byte[] zip(byte[] input) throws ZipHelperException { try { if (compresser == null) { compresser = new Deflater(compressionLevel, true); } byte[] output = new byte[input.length]; ByteArrayOutputStream outstream = new ByteArrayOutputStream(input.length); compresser.setInput(input); compresser.finish(); while (!compresser.needsInput()) { int compressedDataLength = compresser.deflate(output, 0, output.length); if (compressedDataLength > 0) { outstream.write(output, 0, compressedDataLength); } } if (!compresser.finished()) { int compressedDataLength = compresser.deflate(output, 0, output.length); if (compressedDataLength > 0) { outstream.write(output, 0, compressedDataLength); } } return outstream.toByteArray(); } catch (Exception exc) { throw new ZipHelperException("Error occurred compressing data: " + exc.getMessage(), exc); } finally { if (compresser != null) { compresser.reset(); } } }
From source file:org.wso2.carbon.appmgt.gateway.handlers.security.saml2.SAMLUtils.java
/** * Returns the marshalled and encoded SAML request. * * @param request/*from w w w .ja v a 2 s .co m*/ * @return * @throws SAMLException */ public static String marshallAndEncodeSAMLRequest(RequestAbstractType request) throws SAMLException { try { String marshalledRequest = SAMLSSOUtil.marshall(request); Deflater deflater = new Deflater(Deflater.DEFLATED, true); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater); deflaterOutputStream.write(marshalledRequest.getBytes("UTF-8")); deflaterOutputStream.close(); String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES); return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim(); } catch (IdentityException e) { throw new SAMLException("Can't marshall and encode SAML response", e); } catch (IOException e) { throw new SAMLException("Can't marshall and encode SAML response", e); } }
From source file:name.npetrovski.jphar.DataEntry.java
private OutputStream getCompressorOutputStream(final OutputStream os, Compression.Type compression) throws IOException { switch (compression) { case ZLIB://from w w w . ja v a 2 s . c o m return new DeflaterOutputStream(os, new Deflater(Deflater.DEFAULT_COMPRESSION, true)); case BZIP: return new BZip2CompressorOutputStream(os); case NONE: return os; default: throw new IOException("Unsupported compression type."); } }
From source file:fr.eo.util.dumper.Dumper.java
private static String getCompressedString(String value) { byte[] output = new byte[8096]; try {//from w w w. ja v a 2 s. c om byte[] input = value.getBytes("UTF-8"); Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true); compresser.setInput(input); compresser.finish(); int compressedDataLength = compresser.deflate(output); return "X'" + Hex.encodeHexString(Arrays.copyOf(output, compressedDataLength)) + "'"; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
From source file:prz.PRZ.java
/** * * @param bytes//from w w w.j av a 2 s .c o m * @return */ public static byte[] huffman_test(byte[] bytes) { Deflater d = new Deflater(9, true); d.setStrategy(Deflater.HUFFMAN_ONLY); DeflaterOutputStream dfos; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { dfos = new DeflaterOutputStream(baos, d); dfos.write(bytes); dfos.finish(); byte[] y = baos.toByteArray(); System.out.println("HUFF-> BitLength:" + (bytes.length * 8) + "| BestLength: " + (y.length * 8) + "| Ratio: " + ((double) y.length / (bytes.length))); return y; } catch (IOException ex) { Logger.getLogger(PRZ.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.tremolosecurity.proxy.auth.saml2.Saml2SingleLogout.java
@Override public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException { if (request == null || response == null) { //do nothing return;/*from w ww . j ava 2 s . c o m*/ } String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(digSigAlg); if (xmlAlg == null) { throw new ServletException("Unknown Signiture algorithm : '" + digSigAlg + "'"); } String javaAlg = SAML2Auth.javaDigSigAlgs.get(digSigAlg); UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); ConfigManager cfgMgr = holder.getConfig(); LogoutRequestBuilder lrb = new LogoutRequestBuilder(); LogoutRequest lr = lrb.buildObject(); DateTime dt = new DateTime(); lr.setIssueInstant(dt); lr.setDestination(logoutURL); byte[] idBytes = new byte[20]; random.nextBytes(idBytes); String id = "f" + Hex.encodeHexString(idBytes); lr.setID(id); IssuerBuilder ib = new IssuerBuilder(); Issuer issuer = ib.buildObject(); issuer.setValue(assertionConsumerServiceURL); lr.setIssuer(issuer); NameIDBuilder nidbpb = new NameIDBuilder(); NameID nid = nidbpb.buildObject(); //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified"); nid.setFormat(nameIDFormat); //nid.setSPNameQualifier(assertionConsumerServiceURL); nid.setValue(nameID); lr.setNameID(nid); SessionIndexBuilder sib = new SessionIndexBuilder(); SessionIndex si = sib.buildObject(); si.setSessionIndex(sessionIndex); lr.getSessionIndexes().add(si); try { // Get the Subject marshaller Marshaller marshaller = new LogoutRequestMarshaller(); // Marshall the Subject //Element assertionElement = marshaller.marshall(lr); String xml = OpenSAMLUtils.xml2str(lr); xml = xml.substring(xml.indexOf("?>") + 2); if (logger.isDebugEnabled()) { logger.debug("=======AuthnRequest============"); logger.debug(xml); logger.debug("=======AuthnRequest============"); } byte[] bxml = xml.getBytes("UTF-8"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true)); compressor.write(bxml); compressor.flush(); compressor.close(); String b64 = new String(Base64.encodeBase64(baos.toByteArray())); StringBuffer redirURL = new StringBuffer(); StringBuffer query = new StringBuffer(); idBytes = new byte[20]; random.nextBytes(idBytes); query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=") .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8")); query.append("&SigAlg=").append(URLEncoder.encode(xmlAlg, "UTF-8")); //http://www.w3.org/2000/09/xmldsig#rsa-sha1 java.security.Signature signer = java.security.Signature.getInstance(javaAlg); PrivateKey sigKey = cfgMgr.getPrivateKey(signingKeyAlias); if (sigKey == null) { throw new ServletException("Signing Key : '" + signingKeyAlias + "' not found"); } signer.initSign(sigKey); signer.update(query.toString().getBytes("UTF-8")); String base64Sig = new String(Base64.encodeBase64(signer.sign())); query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8")); redirURL.append(logoutURL).append("?").append(query.toString()); if (logger.isDebugEnabled()) { logger.debug("Logout URL : '" + redirURL.toString() + "'"); } //((ProxyResponse) response).removeHeader("Location"); response.sendRedirect(redirURL.toString()); } catch (Exception e) { throw new ServletException("Could not generate logout request", e); } }
From source file:org.resthub.rpc.AMQPHessianProxy.java
/** * Create the request message body//w w w . j av a 2s . c o m * @param method * @param args * @return * @throws IOException */ 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(); }