Example usage for java.util.zip Deflater Deflater

List of usage examples for java.util.zip Deflater Deflater

Introduction

In this page you can find the example usage for java.util.zip Deflater Deflater.

Prototype

public Deflater(int level, boolean nowrap) 

Source Link

Document

Creates a new compressor using the specified compression level.

Usage

From source file:org.apache.tez.common.TezCommonUtils.java

@Private
public static Deflater newBestSpeedDeflater() {
    return new Deflater(Deflater.BEST_SPEED, NO_WRAP);
}

From source file:org.wso2.carbon.identity.saml.inbound.util.SAMLSSOUtil.java

/**
 * Compresses the response String/*from   ww w  .j  av a  2s  .  co  m*/
 *
 * @param response
 * @return
 * @throws IOException
 */
public static String compressResponse(String response) throws IOException {

    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    try {
        deflaterOutputStream.write(response.getBytes(StandardCharsets.UTF_8));
    } finally {
        deflaterOutputStream.close();
    }
    return Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
}

From source file:com.gargoylesoftware.htmlunit.WebClient3Test.java

private void doTestDeflateCompression(final boolean gzipCompatibleCompression) throws Exception {
    final byte[] input = "document.title = 'modified';".getBytes("UTF-8");

    final byte[] buffer = new byte[100];
    final Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, gzipCompatibleCompression);
    deflater.setInput(input);//from   w  w  w . ja v  a  2s .c o  m
    deflater.finish();

    final int compressedDataLength = deflater.deflate(buffer);
    final byte[] content = new byte[compressedDataLength];
    System.arraycopy(buffer, 0, content, 0, compressedDataLength);

    final List<NameValuePair> headers = new ArrayList<>();
    headers.add(new NameValuePair("Content-Encoding", "deflate"));
    headers.add(new NameValuePair("Content-Length", String.valueOf(compressedDataLength)));

    final MockWebConnection conn = getMockWebConnection();
    conn.setResponse(URL_SECOND, content, 200, "OK", "text/javascript", headers);

    final String html = "<html><head>" + "<title>Hello world</title>" + "<script src='" + URL_SECOND
            + "'></script>" + "</head><body><script>alert(document.title)</script></body></html>";
    loadPageWithAlerts2(html);
}

From source file:com.tremolosecurity.proxy.auth.SAML2Auth.java

public void initializeSSO(HttpServletRequest req, HttpServletResponse resp, HttpSession session, boolean isJump,
        String jumpPage) throws MalformedURLException, ServletException {
    {//  w  w  w.j av a 2s.  c o m
        RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();

        HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session
                .getAttribute(ProxyConstants.AUTH_MECH_PARAMS);

        boolean isMultiIdp = authParams.get("isMultiIdP") != null
                && authParams.get("isMultiIdP").getValues().get(0).equalsIgnoreCase("true");

        String postAuthnReqTo = "";
        String redirAuthnReqTo = "";
        String assertionConsumerServiceURL = "";
        boolean signAuthnReq = false;

        String uri = (String) req.getAttribute(ProxyConstants.AUTH_REDIR_URI);
        if (uri == null) {
            uri = req.getRequestURI();
        }

        if (isMultiIdp) {

            URL url = new URL(req.getRequestURL().toString());
            String hostName = url.getHost();
            String dn = authParams.get("idpDir").getValues().get(0);

            try {
                StringBuffer b = new StringBuffer();

                LDAPSearchResults res = cfgMgr.getMyVD().search(dn, 2, equal("hostname", hostName).toString(),
                        new ArrayList<String>());
                if (!res.hasMore()) {
                    throw new ServletException("No IdP found");
                }

                LDAPEntry entry = res.next();
                postAuthnReqTo = entry.getAttribute("idpURL").getStringValue();

                redirAuthnReqTo = entry.getAttribute("idpRedirURL").getStringValue();

                assertionConsumerServiceURL = ProxyTools.getInstance().getFqdnUrl(uri, req);
                signAuthnReq = entry.getAttribute("signAuthnReq").getStringValue().equalsIgnoreCase("1");

            } catch (LDAPException e) {
                throw new ServletException("Could not load IdP data", e);
            }

        } else {
            postAuthnReqTo = authParams.get("idpURL").getValues().get(0);// "http://idp.partner.domain.com:8080/opensso/SSOPOST/metaAlias/testSaml2Idp";

            redirAuthnReqTo = authParams.get("idpRedirURL").getValues().get(0);

            assertionConsumerServiceURL = ProxyTools.getInstance().getFqdnUrl(uri, req);// "http://sp.localdomain.com:8080/SampleSP/echo";

            if (authParams.get("forceToSSL") != null
                    && authParams.get("forceToSSL").getValues().get(0).equalsIgnoreCase("true")) {
                if (!assertionConsumerServiceURL.startsWith("https")) {
                    assertionConsumerServiceURL = assertionConsumerServiceURL.replace("http://", "https://");
                }
            }

            signAuthnReq = authParams.get("signAuthnReq") != null
                    && authParams.get("signAuthnReq").getValues().get(0).equalsIgnoreCase("true");
        }

        ConfigManager cfg = (ConfigManager) req.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

        AuthnRequestBuilder authnBuilder = new AuthnRequestBuilder();
        AuthnRequest authn = authnBuilder.buildObject();
        authn.setAssertionConsumerServiceURL(assertionConsumerServiceURL);
        authn.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
        //authn.setDestination(postAuthnReqTo);
        authn.setDestination(redirAuthnReqTo);
        DateTime dt = new DateTime();

        String authMechanism = authParams.get("authCtxRef").getValues().get(0);

        byte[] idBytes = new byte[20];
        random.nextBytes(idBytes);

        /*StringBuffer id = new StringBuffer();
        for (byte b : idBytes) {
           id.append(Hex.encode(idBytes));
        }*/

        StringBuffer b = new StringBuffer();
        b.append('f').append(Hex.encodeHexString(idBytes));

        String id = b.toString();

        authn.setIssueInstant(dt);
        //authn.setID(Long.toString(random.nextLong()));
        authn.setID(id.toString());
        session.setAttribute("AUTOIDM_SAML2_REQUEST", authn.getID());
        IssuerBuilder ib = new IssuerBuilder();
        Issuer issuer = ib.buildObject();
        issuer.setValue(assertionConsumerServiceURL);

        authn.setIssuer(issuer);
        //authn.setAssertionConsumerServiceIndex(0);
        //authn.setAttributeConsumingServiceIndex(0);

        NameIDPolicyBuilder nidbpb = new NameIDPolicyBuilder();
        NameIDPolicy nidp = nidbpb.buildObject();
        //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
        nidp.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress");
        nidp.setAllowCreate(true);
        nidp.setSPNameQualifier(assertionConsumerServiceURL);
        //authn.setNameIDPolicy(nidp);

        authn.setIsPassive(false);
        //authn.setProviderName("tremolosecurity.com");

        if (!authMechanism.isEmpty() && !authMechanism.equalsIgnoreCase("none")) {
            AuthnContextClassRefBuilder accrb = new AuthnContextClassRefBuilder();
            AuthnContextClassRef accr = accrb.buildObject();

            accr.setAuthnContextClassRef(authMechanism);

            //accr.setAuthnContextClassRef("urn:federation:authentication:windows");
            //accr.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

            RequestedAuthnContextBuilder racb = new RequestedAuthnContextBuilder();
            RequestedAuthnContext rac = racb.buildObject();
            rac.getAuthnContextClassRefs().add(accr);
            rac.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
            authn.setRequestedAuthnContext(rac);
        }

        authn.setForceAuthn(false);

        try {
            // Get the Subject marshaller
            Marshaller marshaller = new AuthnRequestMarshaller();

            // Marshall the Subject
            //Element assertionElement = marshaller.marshall(authn);

            String xml = OpenSAMLUtils.xml2str(authn);
            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"));

            if (signAuthnReq) {

                String sigAlg = authParams.get("sigAlg") != null ? authParams.get("sigAlg").getValues().get(0)
                        : "RSA-SHA1";

                String xmlSigAlg = SAML2Auth.xmlDigSigAlgs.get(sigAlg);
                String javaSigAlg = SAML2Auth.javaDigSigAlgs.get(sigAlg);

                //sb.append("SAMLRequest=").append(xml).append("&SigAlg=").append(URLEncoder.encode("http://www.w3.org/2000/09/xmldsig#rsa-sha1", "UTF-8"));
                query.append("&SigAlg=").append(URLEncoder.encode(xmlSigAlg, "UTF-8"));

                java.security.Signature signer = java.security.Signature.getInstance(javaSigAlg);

                if (authParams.get("spSigKey") == null) {
                    throw new ServletException("No signature certificate specified");
                }
                String spSigKey = authParams.get("spSigKey").getValues().get(0);

                signer.initSign(cfgMgr.getPrivateKey(spSigKey));
                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(redirAuthnReqTo).append("?").append(query.toString());

            if (isJump) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Redirecting to Jump Page");
                    logger.debug("SAML2_JUMPPAGE='" + req.getAttribute("TREMOLO_AUTH_REDIR_URI"));
                }

                session.setAttribute("SAML2_JUMPPAGE", redirURL.toString());
                resp.sendRedirect(jumpPage);
            } else {
                resp.sendRedirect(redirURL.toString());
            }

            /*String b64 = new String(
                  org.apache.directory.shared.ldap.util.Base64
                .encode(bxml));
                    
            req.setAttribute("postaction", postAuthnReqTo);
            req.setAttribute("postdata", b64);
            req.getRequestDispatcher("/auth/fed/postauthnreq.jsp").forward(
                  req, resp);*/

        } catch (Exception e) {
            throw new ServletException("Error generating new authn request", e);
        }
    }
}

From source file:org.adeptnet.auth.saml.SAMLClient.java

private byte[] deflate(final byte[] input) throws IOException {
    // deflate and base-64 encode it
    final Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
    deflater.setInput(input);// ww  w .  j  a  v  a  2s. c  om
    deflater.finish();

    byte[] tmp = new byte[8192];
    int count;

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while (!deflater.finished()) {
        count = deflater.deflate(tmp);
        bos.write(tmp, 0, count);
    }
    bos.close();
    deflater.end();

    return bos.toByteArray();
}

From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java

@Override
public String encodeSAMLObject(SignableSAMLObject signableSAMLObject) throws MarshallingException, IOException {
    log.debug("Encoding SAML Object " + signableSAMLObject);

    // Now we must build our representation to put into the html form to be
    // submitted to the idp
    Marshaller marshaller = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(signableSAMLObject);
    org.w3c.dom.Element authDOM = marshaller.marshall(signableSAMLObject);
    StringWriter rspWrt = new StringWriter();
    XMLHelper.writeNode(authDOM, rspWrt);
    String messageXML = rspWrt.toString();

    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    deflaterOutputStream.write(messageXML.getBytes("UTF-8"));
    deflaterOutputStream.close();//  w  w  w  .j  a va  2 s .  c o m
    String samlRequestParameter = Shared.encodeBytes(byteArrayOutputStream.toByteArray());
    return samlRequestParameter;
}

From source file:org.wso2.appserver.webapp.security.utils.SSOUtils.java

/**
 * Encodes the SAML 2.0 based request XML object into its corresponding Base64 notation, based on the type of
 * SAML 2.0 binding.//w w  w  .j a  v a2s  .  co  m
 *
 * @param requestMessage the {@link RequestAbstractType} XML object to be encoded
 * @param binding        the SAML 2.0 binding type
 * @return encoded {@link String} corresponding to the request XML object
 * @throws SSOException if an error occurs while encoding SAML request
 */
public static String encodeRequestMessage(RequestAbstractType requestMessage, String binding)
        throws SSOException {
    Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory()
            .getMarshaller(requestMessage);
    Element authDOM = null;
    try {
        //  marshall this element, and its children, and root them in a newly created Document
        if (marshaller != null) {
            authDOM = marshaller.marshall(requestMessage);
        }
    } catch (MarshallingException e) {
        throw new SSOException(
                "Error occurred while encoding SAML 2.0 Request, failed to marshall the SAML 2.0. "
                        + "Request element XMLObject to its corresponding W3C DOM element",
                e);
    }

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    //  writes the node out to an output stream using the DOM
    if (authDOM != null) {
        SerializeSupport.writeNode(authDOM, outputStream);
    }

    if (SAMLConstants.SAML2_REDIRECT_BINDING_URI.equals(binding)) {
        //  compresses the message using default DEFLATE encoding, Base 64 encode and URL encode
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream,
                deflater)) {
            deflaterOutputStream.write(outputStream.toByteArray());
        } catch (IOException e) {
            throw new SSOException("Error occurred while deflate encoding SAML 2.0 request", e);
        }

        String encodedRequestMessage = Base64Support.encode(byteArrayOutputStream.toByteArray(), false);
        try {
            return URLEncoder.encode(encodedRequestMessage, StandardCharsets.UTF_8.name()).trim();
        } catch (UnsupportedEncodingException e) {
            throw new SSOException("Error occurred while encoding SAML 2.0 request", e);
        }
    } else {
        //  if the binding type encountered is HTTP-POST binding or an unsupported binding type
        return Base64Support.encode(outputStream.toByteArray(), false);
    }
}

From source file:com.twinsoft.convertigo.engine.servlets.ReverseProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * //from  w ww  .  ja  va 2  s  .  c o m
 * @param httpMethodProxyRequest
 *            An object representing the proxy request to be made
 * @param httpServletResponse
 *            An object by which we can send the proxied response back to
 *            the client
 * @throws IOException
 *             Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException
 *             Can be thrown to indicate that another error has occurred
 * @throws EngineException
 */
private void doRequest(HttpMethodType httpMethodType, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    try {
        Engine.logEngine.debug("(ReverseProxyServlet) Starting request handling");

        if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) {
            System.setProperty("javax.net.debug", "all");
            Engine.logEngine.trace("(ReverseProxyServlet) Enabling SSL debug mode");
        } else {
            System.setProperty("javax.net.debug", "");
            Engine.logEngine.debug("(ReverseProxyServlet) Disabling SSL debug mode");
        }

        String baseUrl;
        String projectName;
        String connectorName;
        String contextName;
        String extraPath;

        {
            String requestURI = httpServletRequest.getRequestURI();
            Engine.logEngine.trace("(ReverseProxyServlet) Requested URI : " + requestURI);
            Matcher m = reg_fields.matcher(requestURI);
            if (m.matches() && m.groupCount() >= 5) {
                baseUrl = m.group(1);
                projectName = m.group(2);
                connectorName = m.group(3);
                contextName = m.group(4);
                extraPath = m.group(5);
            } else {
                throw new MalformedURLException(
                        "The request doesn't contains needed fields : projectName, connectorName and contextName");
            }
        }

        String sessionID = httpServletRequest.getSession().getId();

        Engine.logEngine.debug("(ReverseProxyServlet) baseUrl : " + baseUrl + " ; projectName : " + projectName
                + " ; connectorName : " + connectorName + " ; contextName : " + contextName + " ; extraPath : "
                + extraPath + " ; sessionID : " + sessionID);

        Context context = Engine.theApp.contextManager.get(null, contextName, sessionID, null, projectName,
                connectorName, null);

        Project project = Engine.theApp.databaseObjectsManager.getProjectByName(projectName);
        context.projectName = projectName;
        context.project = project;

        ProxyHttpConnector proxyHttpConnector = (ProxyHttpConnector) project.getConnectorByName(connectorName);
        context.connector = proxyHttpConnector;
        context.connectorName = proxyHttpConnector.getName();

        HostConfiguration hostConfiguration = proxyHttpConnector.hostConfiguration;

        // Proxy configuration
        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();

        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(ReverseProxyServlet) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }

        String targetHost = proxyHttpConnector.getServer();
        Engine.logEngine.debug("(ReverseProxyServlet) Target host: " + targetHost);
        int targetPort = proxyHttpConnector.getPort();
        Engine.logEngine.debug("(ReverseProxyServlet) Target port: " + targetPort);

        // Configuration SSL
        Engine.logEngine.debug("(ReverseProxyServlet) Https: " + proxyHttpConnector.isHttps());
        CertificateManager certificateManager = proxyHttpConnector.certificateManager;
        boolean trustAllServerCertificates = proxyHttpConnector.isTrustAllServerCertificates();

        if (proxyHttpConnector.isHttps()) {
            Engine.logEngine.debug("(ReverseProxyServlet) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);

            Engine.logEngine.debug(
                    "(ReverseProxyServlet) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!targetHost.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != targetPort)) {
                Engine.logEngine
                        .debug("(ReverseProxyServlet) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, trustAllServerCertificates),
                        targetPort);

                hostConfiguration.setHost(targetHost, targetPort, myhttps);
            }

            Engine.logEngine.debug("(ReverseProxyServlet) Updated host configuration for SSL purposes");
        } else {
            hostConfiguration.setHost(targetHost, targetPort);
        }

        HttpMethod httpMethodProxyRequest;

        String targetPath = proxyHttpConnector.getBaseDir() + extraPath;

        // Handle the query string
        if (httpServletRequest.getQueryString() != null) {
            targetPath += "?" + httpServletRequest.getQueryString();
        }
        Engine.logEngine.debug("(ReverseProxyServlet) Target path: " + targetPath);

        Engine.logEngine.debug("(ReverseProxyServlet) Requested method: " + httpMethodType);

        if (httpMethodType == HttpMethodType.GET) {
            // Create a GET request
            httpMethodProxyRequest = new GetMethod();
        } else if (httpMethodType == HttpMethodType.POST) {
            // Create a standard POST request
            httpMethodProxyRequest = new PostMethod();
            ((PostMethod) httpMethodProxyRequest)
                    .setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream()));
        } else {
            throw new IllegalArgumentException("Unknown HTTP method: " + httpMethodType);
        }

        String charset = httpMethodProxyRequest.getParams().getUriCharset();
        URI targetURI;
        try {
            targetURI = new URI(targetPath, true, charset);
        } catch (URIException e) {
            // Bugfix #1484
            String newTargetPath = "";
            for (String part : targetPath.split("&")) {
                if (!newTargetPath.equals("")) {
                    newTargetPath += "&";
                }
                String[] pair = part.split("=");
                try {
                    newTargetPath += URLDecoder.decode(pair[0], "UTF-8") + "="
                            + (pair.length > 1 ? URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8")
                                    : "");
                } catch (UnsupportedEncodingException ee) {
                    newTargetPath = targetPath;
                }
            }

            targetURI = new URI(newTargetPath, true, charset);
        }
        httpMethodProxyRequest.setURI(targetURI);

        // Tells the method to automatically handle authentication.
        httpMethodProxyRequest.setDoAuthentication(true);

        HttpState httpState = getHttpState(proxyHttpConnector, context);

        String basicUser = proxyHttpConnector.getAuthUser();
        String basicPassword = proxyHttpConnector.getAuthPassword();
        String givenBasicUser = proxyHttpConnector.getGivenAuthUser();
        String givenBasicPassword = proxyHttpConnector.getGivenAuthPassword();

        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(targetHost, targetPort, realm),
                    new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Credentials: " + userName + ":******");
        }

        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Proxy credentials: " + proxyUser + ":******");
        }

        // Forward the request headers
        setProxyRequestHeaders(httpServletRequest, httpMethodProxyRequest, proxyHttpConnector);

        // Use the CEMS HttpClient
        HttpClient httpClient = Engine.theApp.httpClient;
        httpMethodProxyRequest.setFollowRedirects(false);

        // Execute the request
        int intProxyResponseCode = httpClient.executeMethod(hostConfiguration, httpMethodProxyRequest,
                httpState);

        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software
        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            if (stringLocation == null) {
                throw new ServletException("Received status code: " + stringStatusCode + " but no "
                        + STRING_LOCATION_HEADER + " header was found in the response");
            }
            // Modify the redirect to go to this proxy servlet rather that
            // the
            // proxied host
            String redirect = handleRedirect(stringLocation, baseUrl, proxyHttpConnector);
            httpServletResponse.sendRedirect(redirect);
            Engine.logEngine.debug("(ReverseProxyServlet) Send redirect (" + redirect + ")");
            return;
        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            Engine.logEngine.debug("(ReverseProxyServlet) NOT MODIFIED (304)");
            return;
        }

        // Pass the response code back to the client
        httpServletResponse.setStatus(intProxyResponseCode);

        // Pass response headers back to the client
        Engine.logEngine.debug("(ReverseProxyServlet) Response headers back to the client:");
        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
        for (Header header : headerArrayResponse) {
            String headerName = header.getName();
            String headerValue = header.getValue();
            if (!headerName.equalsIgnoreCase("Transfer-Encoding")
                    && !headerName.equalsIgnoreCase("Set-Cookie")) {
                httpServletResponse.setHeader(headerName, headerValue);
                Engine.logEngine.debug("   " + headerName + "=" + headerValue);
            }
        }

        String contentType = null;
        Header[] contentTypeHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Type");
        for (Header contentTypeHeader : contentTypeHeaders) {
            contentType = contentTypeHeader.getValue();
            break;
        }

        String pageCharset = "UTF-8";
        if (contentType != null) {
            int iCharset = contentType.indexOf("charset=");
            if (iCharset != -1) {
                pageCharset = contentType.substring(iCharset + "charset=".length()).trim();
            }
            Engine.logEngine.debug("(ReverseProxyServlet) Using charset: " + pageCharset);
        }

        InputStream siteIn = httpMethodProxyRequest.getResponseBodyAsStream();

        // Handle gzipped content
        Header[] contentEncodingHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Encoding");
        boolean bGZip = false, bDeflate = false;
        for (Header contentEncodingHeader : contentEncodingHeaders) {
            HeaderElement[] els = contentEncodingHeader.getElements();
            for (int j = 0; j < els.length; j++) {
                if ("gzip".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode GZip stream");
                    siteIn = new GZIPInputStream(siteIn);
                    bGZip = true;
                } else if ("deflate".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode Deflate stream");
                    siteIn = new InflaterInputStream(siteIn, new Inflater(true));
                    bDeflate = true;
                }
            }
        }

        byte[] bytesDataResult;

        ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);

        // String resourceUrl = projectName + targetPath;

        String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);

        try {
            // Read either from the cache, either from the remote server
            // InputStream is = proxyCacheManager.getResource(resourceUrl);
            // if (is != null) {
            // Engine.logEngine.debug("(ReverseProxyServlet) Getting data from cache");
            // siteIn = is;
            // }
            int c = siteIn.read();
            while (c > -1) {
                baos.write(c);
                c = siteIn.read();
            }
            // if (is != null) is.close();
        } finally {
            context.statistics.stop(t, true);
        }

        bytesDataResult = baos.toByteArray();
        baos.close();
        Engine.logEngine.debug("(ReverseProxyServlet) Data retrieved!");

        // if (isDynamicContent(httpServletRequest.getPathInfo(),
        // proxyHttpConnector.getDynamicContentFiles())) {
        Engine.logEngine.debug("(ReverseProxyServlet) Dynamic content");

        bytesDataResult = handleStringReplacements(baseUrl, contentType, pageCharset, proxyHttpConnector,
                bytesDataResult);

        String billingClassName = context.getConnector().getBillingClassName();
        if (billingClassName != null) {
            try {
                Engine.logContext.debug("Billing class name required: " + billingClassName);
                AbstractBiller biller = (AbstractBiller) Class.forName(billingClassName).newInstance();
                Engine.logContext.debug("Executing the biller");
                biller.insertBilling(context);
            } catch (Throwable e) {
                Engine.logContext.warn("Unable to execute the biller (the billing is thus ignored): ["
                        + e.getClass().getName() + "] " + e.getMessage());
            }
        }
        // }
        // else {
        // Engine.logEngine.debug("(ReverseProxyServlet) Static content: " +
        // contentType);
        //            
        // // Determine if the resource has already been cached or not
        // CacheEntry cacheEntry =
        // proxyCacheManager.getCacheEntry(resourceUrl);
        // if (cacheEntry instanceof FileCacheEntry) {
        // FileCacheEntry fileCacheEntry = (FileCacheEntry) cacheEntry;
        // File file = new File(fileCacheEntry.fileName);
        // if (!file.exists())
        // proxyCacheManager.removeCacheEntry(cacheEntry);
        // cacheEntry = null;
        // }
        // if (cacheEntry == null) {
        // bytesDataResult = handleStringReplacements(contentType,
        // proxyHttpConnector, bytesDataResult);
        //
        // if (intProxyResponseCode == 200) {
        // Engine.logEngine.debug("(ReverseProxyServlet) Resource stored: "
        // + resourceUrl);
        // cacheEntry = proxyCacheManager.storeResponse(resourceUrl,
        // bytesDataResult);
        // cacheEntry.contentLength = bytesDataResult.length;
        // cacheEntry.contentType = contentType;
        // Engine.logEngine.debug("(ReverseProxyServlet) Cache entry: " +
        // cacheEntry);
        // }
        // }
        // }

        // Send the content to the client
        if (Engine.logEngine.isDebugEnabled() && MimeType.Html.is(contentType)) {
            Engine.logEngine.debug("Data proxied:\n" + new String(bytesDataResult, pageCharset));
        }

        if (bGZip || bDeflate) {
            baos = new ByteArrayOutputStream();
            OutputStream compressedOutputStream = bGZip ? new GZIPOutputStream(baos)
                    : new DeflaterOutputStream(baos,
                            new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
            compressedOutputStream.write(bytesDataResult);
            compressedOutputStream.close();
            bytesDataResult = baos.toByteArray();
            baos.close();
        }

        httpServletResponse.setContentLength(bytesDataResult.length);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        outputStreamClientResponse.write(bytesDataResult);

        Engine.logEngine.debug("(ReverseProxyServlet) End of document retransmission");
    } catch (Exception e) {
        Engine.logEngine.error("Error while trying to proxy page", e);
        throw new ServletException("Error while trying to proxy page", e);
    }
}

From source file:org.wso2.carbon.identity.sso.agent.saml.SAML2SSOManager.java

protected String encodeRequestMessage(RequestAbstractType requestMessage, String binding)
        throws SSOAgentException {

    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(requestMessage);
    Element authDOM = null;//ww w . j a  v a 2s  .c  o  m
    try {
        authDOM = marshaller.marshall(requestMessage);
        StringWriter rspWrt = new StringWriter();
        XMLHelper.writeNode(authDOM, rspWrt);
        if (SAMLConstants.SAML2_REDIRECT_BINDING_URI.equals(binding)) {
            //Compress the message, Base 64 encode and URL encode
            Deflater deflater = new Deflater(Deflater.DEFLATED, true);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream,
                    deflater);
            deflaterOutputStream.write(rspWrt.toString().getBytes(Charset.forName("UTF-8")));
            deflaterOutputStream.close();
            String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(),
                    Base64.DONT_BREAK_LINES);
            return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim();
        } else if (SAMLConstants.SAML2_POST_BINDING_URI.equals(binding)) {
            return Base64.encodeBytes(rspWrt.toString().getBytes(), Base64.DONT_BREAK_LINES);
        } else {
            LOGGER.log(Level.FINE,
                    "Unsupported SAML2 HTTP Binding. Defaulting to " + SAMLConstants.SAML2_POST_BINDING_URI);
            return Base64.encodeBytes(rspWrt.toString().getBytes(), Base64.DONT_BREAK_LINES);
        }
    } catch (MarshallingException e) {
        throw new SSOAgentException("Error occurred while encoding SAML2 request", e);
    } catch (UnsupportedEncodingException e) {
        throw new SSOAgentException("Error occurred while encoding SAML2 request", e);
    } catch (IOException e) {
        throw new SSOAgentException("Error occurred while encoding SAML2 request", e);
    }
}

From source file:org.apache.marmotta.kiwi.io.KiWiIO.java

/**
 * Write a string to the data output. In case the string length exceeds LITERAL_COMPRESS_LENGTH, uses a LZW
 * compressed format, otherwise writes the plain bytes.
 *
 * @param out      output destination to write to
 * @param content  string to write//from   w w  w  .j  av a 2 s.  co  m
 * @throws IOException
 */
private static void writeContent(DataOutput out, String content) throws IOException {
    if (content.length() > LITERAL_COMPRESS_LENGTH) {
        // temporary buffer of the size of bytes in the content string (assuming that the compressed data will fit into it)
        byte[] data = content.getBytes("UTF-8");
        byte[] buffer = new byte[data.length];

        Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION, true);
        compressor.setInput(data);
        compressor.finish();

        int length = compressor.deflate(buffer);

        // only use compressed version if it is smaller than the number of bytes used by the string
        if (length < buffer.length) {
            log.debug("compressed string with {} bytes; compression ratio {}", data.length,
                    (double) length / data.length);

            out.writeByte(MODE_COMPRESSED);
            out.writeInt(data.length);
            out.writeInt(length);
            out.write(buffer, 0, length);
        } else {
            log.warn("compressed length exceeds string buffer: {} > {}", length, buffer.length);

            out.writeByte(MODE_DEFAULT);
            DataIO.writeString(out, content);
        }

        compressor.end();
    } else {
        out.writeByte(MODE_DEFAULT);
        DataIO.writeString(out, content);
    }
}