Example usage for org.apache.http.impl.conn BasicHttpClientConnectionManager shutdown

List of usage examples for org.apache.http.impl.conn BasicHttpClientConnectionManager shutdown

Introduction

In this page you can find the example usage for org.apache.http.impl.conn BasicHttpClientConnectionManager shutdown.

Prototype

boolean shutdown

To view the source code for org.apache.http.impl.conn BasicHttpClientConnectionManager shutdown.

Click Source Link

Usage

From source file:com.tremolosecurity.proxy.filters.PreAuthFilter.java

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL))
            .getAuthInfo();/*from  www  . j  ava2 s . c o  m*/
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    List<Cookie> cookies = null;

    if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) {
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        HttpSession session = request.getSession();
        String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH");
        if (uid == null || !uid.equals(userData.getUserDN())) {
            session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN());
            HashMap<String, String> uriParams = new HashMap<String, String>();
            uriParams.put("fullURI", this.uri);

            UrlHolder remHolder = cfg.findURL(this.url);

            org.apache.http.client.methods.HttpRequestBase method = null;

            if (this.postSAML) {
                PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias);
                java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias);

                Saml2Assertion assertion = new Saml2Assertion(
                        userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null,
                        this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion,
                        this.signResponse, false, this.nameIDType, this.authnCtxClassRef);

                String respXML = "";

                try {
                    respXML = assertion.generateSaml2Response();
                } catch (Exception e) {
                    throw new ServletException("Could not generate SAMLResponse", e);
                }

                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));

                formparams.add(new BasicNameValuePair("SAMLResponse", base64));
                if (this.relayState != null && !this.relayState.isEmpty()) {
                    formparams.add(new BasicNameValuePair("RelayState", this.relayState));
                }

                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                HttpPost post = new HttpPost(this.assertionConsumerURL);
                post.setEntity(entity);
                method = post;

            } else {
                HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams));
                method = get;
            }

            LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0),
                    this.loginAttribute, method, lastMileKeyAlias, true);
            BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                    cfg.getHttpClientSocketRegistry());
            try {
                CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm)
                        .setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build();

                HttpResponse resp = httpclient.execute(method);

                if (resp.getStatusLine().getStatusCode() == 500) {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(resp.getEntity().getContent()));
                    StringBuffer error = new StringBuffer();
                    String line = null;
                    while ((line = in.readLine()) != null) {
                        error.append(line).append('\n');
                    }

                    logger.warn("Pre-Auth Failed : " + error);
                }

                org.apache.http.Header[] headers = resp.getAllHeaders();

                StringBuffer stmp = new StringBuffer();

                cookies = new ArrayList<Cookie>();

                for (org.apache.http.Header header : headers) {
                    if (header.getName().equalsIgnoreCase("set-cookie")
                            || header.getName().equalsIgnoreCase("set-cookie2")) {
                        //System.out.println(header.getValue());
                        String cookieVal = header.getValue();
                        /*if (cookieVal.endsWith("HttpOnly")) {
                           cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly"));
                        }
                                
                        //System.out.println(cookieVal);*/

                        List<HttpCookie> cookiesx = HttpCookie.parse(cookieVal);
                        for (HttpCookie cookie : cookiesx) {

                            String cookieFinalName = cookie.getName();
                            if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
                                stmp.setLength(0);
                                stmp.append("JSESSIONID").append('-')
                                        .append(holder.getApp().getName().replaceAll(" ", "|"));
                                cookieFinalName = stmp.toString();
                            }

                            //logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'");

                            Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
                            respcookie.setComment(cookie.getComment());
                            if (cookie.getDomain() != null) {
                                //respcookie.setDomain(cookie.getDomain());
                            }
                            respcookie.setMaxAge((int) cookie.getMaxAge());
                            respcookie.setPath(cookie.getPath());

                            respcookie.setSecure(cookie.getSecure());
                            respcookie.setVersion(cookie.getVersion());
                            cookies.add(respcookie);

                            if (request.getCookieNames().contains(respcookie.getName())) {
                                request.removeCookie(cookieFinalName);
                            }

                            request.addCookie(new Cookie(cookie.getName(), cookie.getValue()));
                        }
                    }
                }

            } finally {
                bhcm.shutdown();
            }
        }
    }

    chain.nextFilter(request, response, chain);
    if (cookies != null) {

        for (Cookie cookie : cookies) {

            response.addCookie(cookie);
        }
    }

}