Example usage for org.apache.http.client.config CookieSpecs STANDARD

List of usage examples for org.apache.http.client.config CookieSpecs STANDARD

Introduction

In this page you can find the example usage for org.apache.http.client.config CookieSpecs STANDARD.

Prototype

String STANDARD

To view the source code for org.apache.http.client.config CookieSpecs STANDARD.

Click Source Link

Document

The RFC 2965 compliant policy (standard).

Usage

From source file:org.mycontroller.restclient.core.RestHttpClient.java

public RestHttpClient(TRUST_HOST_TYPE trustHostType) {
    customRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
    if (trustHostType == TRUST_HOST_TYPE.ANY) {
        client = getHttpClientTrustAll();
    } else {//from w  w w  .j  av a 2s  .  com
        client = getHttpClient();
    }
}

From source file:com.hp.mqm.clt.RestClient.java

public RestClient(Settings settings) {
    this.settings = settings;

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    cookieStore = new BasicCookieStore();
    httpClientBuilder.setDefaultCookieStore(cookieStore);
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
            .setSocketTimeout(DEFAULT_SO_TIMEOUT).setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT);

    // proxy setting
    if (StringUtils.isNotEmpty(settings.getProxyHost())) {
        HttpHost proxy = new HttpHost(settings.getProxyHost(), settings.getProxyPort());
        requestConfigBuilder.setProxy(proxy);
        if (settings.getProxyUser() != null) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(settings.getProxyHost(), settings.getProxyPort()),
                    new UsernamePasswordCredentials(settings.getProxyUser(), settings.getProxyPassword()));
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }//  w w  w .  j  ava2 s  .co m
    }
    httpClient = httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()).build();

}

From source file:me.vertretungsplan.parser.BaseParser.java

BaseParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) {
    this.scheduleData = scheduleData;
    this.cookieProvider = cookieProvider;
    this.cookieStore = new BasicCookieStore();
    this.colorProvider = new ColorProvider(scheduleData);
    this.encodingDetector = new UniversalDetector(null);

    try {// w w  w  .j a  v  a  2s  .c o  m
        KeyStore ks = loadKeyStore();
        MultiTrustManager multiTrustManager = new MultiTrustManager();
        multiTrustManager.addTrustManager(getDefaultTrustManager());
        multiTrustManager.addTrustManager(trustManagerFromKeystore(ks));

        TrustManager[] trustManagers = new TrustManager[] { multiTrustManager };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
        final HostnameVerifier hostnameVerifier;

        if (scheduleData.getData() != null && scheduleData.getData().has(PARAM_SSL_HOSTNAME)) {
            hostnameVerifier = new CustomHostnameVerifier(scheduleData.getData().getString(PARAM_SSL_HOSTNAME));
        } else {
            hostnameVerifier = new DefaultHostnameVerifier();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }, null, hostnameVerifier);

        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
                .build();
        this.executor = Executor.newInstance(httpclient).use(cookieStore);
    } catch (GeneralSecurityException | JSONException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.digitalpebble.stormcrawler.protocol.httpclient.HttpProtocol.java

@Override
public void configure(final Config conf) {

    super.configure(conf);

    this.maxContent = ConfUtils.getInt(conf, "http.content.limit", -1);

    String userAgent = getAgentString(ConfUtils.getString(conf, "http.agent.name"),
            ConfUtils.getString(conf, "http.agent.version"),
            ConfUtils.getString(conf, "http.agent.description"), ConfUtils.getString(conf, "http.agent.url"),
            ConfUtils.getString(conf, "http.agent.email"));

    builder = HttpClients.custom().setUserAgent(userAgent).setConnectionManager(CONNECTION_MANAGER)
            .setConnectionManagerShared(true).disableRedirectHandling().disableAutomaticRetries();

    String proxyHost = ConfUtils.getString(conf, "http.proxy.host", null);
    int proxyPort = ConfUtils.getInt(conf, "http.proxy.port", 8080);

    boolean useProxy = proxyHost != null && proxyHost.length() > 0;

    // use a proxy?
    if (useProxy) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        builder.setRoutePlanner(routePlanner);
    }//from  w  w  w. j  a  va  2s  . c  om

    int timeout = ConfUtils.getInt(conf, "http.timeout", 10000);

    Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setSocketTimeout(timeout);
    requestConfigBuilder.setConnectTimeout(timeout);
    requestConfigBuilder.setConnectionRequestTimeout(timeout);
    requestConfigBuilder.setCookieSpec(CookieSpecs.STANDARD);
    requestConfig = requestConfigBuilder.build();
}

From source file:com.tremolosecurity.scalejs.register.ws.ScaleRegister.java

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    Gson gson = new Gson();
    request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError",
            "com.tremolosecurity.unison.proxy.noRedirectOnError");
    if (request.getRequestURI().endsWith("/register/config")) {
        response.setContentType("application/json");
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().println(gson.toJson(scaleConfig).trim());

    } else if (request.getRequestURI().endsWith("/register/submit")) {
        ScaleError errors = new ScaleError();
        String json = new String((byte[]) request.getAttribute(ProxySys.MSG_BODY));
        NewUserRequest newUser = gson.fromJson(json, NewUserRequest.class);

        if (scaleConfig.isRequireReCaptcha()) {
            if (newUser.getReCaptchaCode() == null || newUser.getReCaptchaCode().isEmpty()) {
                errors.getErrors().add("Please verify you are not a robot");
            } else {
                BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                        GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
                RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
                CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm)
                        .setDefaultRequestConfig(rc).build();
                HttpPost httppost = new HttpPost("https://www.google.com/recaptcha/api/siteverify");

                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                formparams.add(new BasicNameValuePair("secret", scaleConfig.getRcSecretKey()));
                formparams.add(new BasicNameValuePair("response", newUser.getReCaptchaCode()));
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

                httppost.setEntity(entity);

                CloseableHttpResponse resp = http.execute(httppost);

                ReCaptchaResponse res = gson.fromJson(EntityUtils.toString(resp.getEntity()),
                        ReCaptchaResponse.class);

                if (!res.isSuccess()) {
                    errors.getErrors().add("Human validation failed");
                }/*from  www.j a v a  2 s .  co  m*/

                http.close();
                bhcm.close();

            }
        }

        if (scaleConfig.isRequireTermsAndConditions() && !newUser.isCheckedTermsAndConditions()) {
            errors.getErrors().add("You must accept the terms and conditions to register");
        }

        if (this.scaleConfig.isRequireReason()
                && (newUser.getReason() == null || newUser.getReason().isEmpty())) {
            errors.getErrors().add("Reason is required");
        }

        if (this.scaleConfig.isPreSetPassword()) {
            if (newUser.getPassword() == null || newUser.getPassword().isEmpty()) {
                errors.getErrors().add("Password is required");
            } else if (!newUser.getPassword().equals(newUser.getPassword2())) {
                errors.getErrors().add("Passwords must match");
            }
        }

        for (String attributeName : this.scaleConfig.getAttributes().keySet()) {
            String value = newUser.getAttributes().get(attributeName);

            if (this.scaleConfig.getAttributes().get(attributeName) == null) {
                errors.getErrors().add("Invalid attribute : '" + attributeName + "'");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).isReadOnly()) {
                errors.getErrors().add("Attribute is read only : '"
                        + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "'");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).isRequired()
                    && (value == null || value.length() == 0)) {
                errors.getErrors().add("Attribute is required : '"
                        + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "'");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).getMinChars() > 0
                    && this.scaleConfig.getAttributes().get(attributeName).getMinChars() < value.length()) {
                errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                        + " must have at least "
                        + this.scaleConfig.getAttributes().get(attributeName).getMinChars() + " characters");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).getMaxChars() > 0
                    && this.scaleConfig.getAttributes().get(attributeName).getMaxChars() > value.length()) {
                errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                        + " must have at most "
                        + this.scaleConfig.getAttributes().get(attributeName).getMaxChars() + " characters");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).getType().equalsIgnoreCase("list")) {
                boolean found = false;
                for (NVP nvp : this.scaleConfig.getAttributes().get(attributeName).getValues()) {
                    if (nvp.getValue().equalsIgnoreCase(value)) {
                        found = true;
                    }
                }

                if (!found) {
                    errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                            + " has an invalid value");
                }
            }

            if (this.scaleConfig.getAttributes().get(attributeName).getPattern() != null) {
                boolean ok = true;
                try {
                    Matcher m = this.scaleConfig.getAttributes().get(attributeName).getPattern().matcher(value);
                    if (m == null || !m.matches()) {
                        ok = false;
                    }
                } catch (Exception e) {
                    ok = false;
                }

                if (!ok) {
                    errors.getErrors().add("Attribute value not valid : '"
                            + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "' - "
                            + this.scaleConfig.getAttributes().get(attributeName).getRegExFailedMsg());
                }
            }

            if (this.scaleConfig.getAttributes().get(attributeName).isUnique()) {
                String filter = equal(attributeName, value).toString();

                LDAPSearchResults res = GlobalEntries.getGlobalEntries().getConfigManager().getMyVD().search(
                        GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot(), 2, filter,
                        new ArrayList<String>());
                if (res.hasMore()) {
                    errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                            + " is not available");
                }
                while (res.hasMore())
                    res.next();
            }
        }

        WFCall wfcall = null;
        String wfName = this.scaleConfig.getWorkflowName();
        if (errors.getErrors().isEmpty()) {
            if (scaleConfig.isUseCustomSubmission()) {

                AuthInfo userData = ((AuthController) request.getSession()
                        .getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();

                wfName = cru.createTremoloUser(newUser, errors.getErrors(), userData);
            }
        }

        if (errors.getErrors().isEmpty()) {
            TremoloUser user = new TremoloUser();

            AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL))
                    .getAuthInfo();

            if (this.scaleConfig.isSubmitLoggedInUser()) {
                user.setUid(
                        userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0));
                user.getAttributes().add(new Attribute(this.scaleConfig.getUidAttributeName(),
                        userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0)));
            } else {
                user.setUid(newUser.getAttributes().get(this.scaleConfig.getUidAttributeName()));
            }

            for (String attrName : newUser.getAttributes().keySet()) {
                user.getAttributes().add(new Attribute(attrName, newUser.getAttributes().get(attrName)));
            }

            if (this.scaleConfig.isPreSetPassword()) {
                user.setUserPassword(newUser.getPassword());

            }

            wfcall = new WFCall();
            wfcall.setUidAttributeName(this.scaleConfig.getUidAttributeName());
            wfcall.setReason(newUser.getReason());
            wfcall.setName(wfName);
            wfcall.setUser(user);

            HashMap<String, Object> params = new HashMap<String, Object>();
            wfcall.setRequestParams(params);

            if (userData.getAuthLevel() != 0 && !this.scaleConfig.isSubmitLoggedInUser()) {
                wfcall.setRequestor(
                        userData.getAttribs()
                                .get(GlobalEntries.getGlobalEntries().getConfigManager().getCfg()
                                        .getProvisioning().getApprovalDB().getUserIdAttribute())
                                .getValues().get(0));
                wfcall.getRequestParams().put(Approval.SEND_NOTIFICATION, "false");
                wfcall.getRequestParams().put(Approval.REASON, newUser.getReason());
                wfcall.getRequestParams().put(Approval.IMMEDIATE_ACTION, "true");
            }

            ExecuteWorkflow exec = new ExecuteWorkflow();

            try {
                exec.execute(wfcall, GlobalEntries.getGlobalEntries().getConfigManager());
            } catch (Exception e) {
                throw new ProvisioningException("Could not complete registration", e);
            }

            SubmitResponse res = new SubmitResponse();
            res.setAddNewUsers(userData.getAuthLevel() != 0);
            ScaleJSUtils.addCacheHeaders(response);
            response.getWriter().print(gson.toJson(res));
            response.getWriter().flush();

        } else {
            response.setStatus(500);
            ScaleJSUtils.addCacheHeaders(response);
            response.getWriter().print(gson.toJson(errors).trim());
            response.getWriter().flush();
        }

    } else {
        response.setStatus(500);
        ScaleJSUtils.addCacheHeaders(response);
        ScaleError error = new ScaleError();
        error.getErrors().add("Operation not supported");
        response.getWriter().print(gson.toJson(error).trim());
        response.getWriter().flush();
    }

}

From source file:com.tremolosecurity.unison.proxy.auth.twitter.TwitterAuth.java

public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as)
        throws IOException, ServletException {

    HttpSession session = ((HttpServletRequest) request).getSession();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session
            .getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    MyVDConnection myvd = cfg.getMyVD();

    String consumerKey = authParams.get("consumerKey").getValues().get(0);
    String consumerSecret = authParams.get("consumerSecret").getValues().get(0);
    String accessToken = authParams.get("accessToken").getValues().get(0);
    String accessSecret = authParams.get("accessSecret").getValues().get(0);

    boolean linkToDirectory = Boolean.parseBoolean(authParams.get("linkToDirectory").getValues().get(0));
    String noMatchOU = authParams.get("noMatchOU").getValues().get(0);
    String uidAttr = authParams.get("uidAttr").getValues().get(0);
    String lookupFilter = authParams.get("lookupFilter").getValues().get(0);
    //String userLookupClassName = authParams.get("userLookupClassName").getValues().get(0);

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();

    URL reqURL = new URL(request.getRequestURL().toString());
    String redirectURL = reqURL.getProtocol() + "://" + reqURL.getHost();
    if (reqURL.getPort() != -1) {
        redirectURL += ":" + reqURL.getPort();
    }/*from www  .j  ava 2 s .  com*/

    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());

    AuthMechType amt = act.getAuthMech().get(as.getId());

    String authMechName = amt.getName();
    redirectURL += cfg.getAuthMechs().get(authMechName).getUri();

    if (request.getParameter("oauth_verifier") == null) {

        BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
        RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc)
                .build();

        HttpPost post = new HttpPost("https://api.twitter.com/oauth/request_token");

        this.signRequest(post, "", accessToken, accessSecret, consumerKey, consumerSecret);

        CloseableHttpResponse httpResp = http.execute(post);

        BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));

        StringBuffer token = new StringBuffer();

        String line = null;
        while ((line = in.readLine()) != null) {
            token.append(line);
        }

        httpResp.close();
        bhcm.close();

        System.err.println(token);

        List<NameValuePair> parsed = URLEncodedUtils.parse(token.toString(), Charsets.UTF_8);
        HashMap<String, String> accessTokens = new HashMap<String, String>();

        for (NameValuePair nvp : parsed) {
            accessTokens.put(nvp.getName(), nvp.getValue());
        }

        request.getSession().setAttribute("twitterAccessToken", accessTokens);

        StringBuffer b = new StringBuffer().append("https://api.twitter.com/oauth/authenticate?oauth_token=")
                .append(accessTokens.get("oauth_token"));
        response.sendRedirect(b.toString());
    } else {
        String oauthVerifier = request.getParameter("oauth_verifier");
        HashMap<String, String> accessTokens = (HashMap<String, String>) request.getSession()
                .getAttribute("twitterAccessToken");

        BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
        RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc)
                .build();

        HttpUriRequest post = new HttpPost();

        try {
            post = RequestBuilder.post().setUri(new java.net.URI("https://api.twitter.com/oauth/access_token"))
                    .addParameter("oauth_verifier", oauthVerifier).build();
        } catch (URISyntaxException e) {
            throw new ServletException("Could not create post request");
        }

        this.signRequest(post, "oauth_verifier=" + oauthVerifier, accessTokens.get("oauth_token"),
                accessTokens.get("oauth_token_secret"), consumerKey, consumerSecret);

        CloseableHttpResponse httpResp = http.execute(post);

        BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));

        StringBuffer token = new StringBuffer();

        String line = null;
        while ((line = in.readLine()) != null) {
            token.append(line);
        }

        EntityUtils.consumeQuietly(httpResp.getEntity());
        httpResp.close();

        System.err.println(token);

        List<NameValuePair> parsed = URLEncodedUtils.parse(token.toString(), Charsets.UTF_8);
        HashMap<String, String> userTokens = new HashMap<String, String>();

        for (NameValuePair nvp : parsed) {
            userTokens.put(nvp.getName(), nvp.getValue());
        }

        request.getSession().setAttribute("twitterUserToken", accessTokens);

        HttpGet get = new HttpGet(
                "https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true");
        this.signRequest(get, "", userTokens.get("oauth_token"), userTokens.get("oauth_token_secret"),
                consumerKey, consumerSecret);

        httpResp = http.execute(get);

        in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
        token.setLength(0);

        line = null;
        while ((line = in.readLine()) != null) {
            token.append(line);
        }

        EntityUtils.consumeQuietly(httpResp.getEntity());
        httpResp.close();

        System.err.println(token);

        httpResp.close();
        bhcm.close();

        Map attrs = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString());

        if (!linkToDirectory) {
            loadUnlinkedUser(session, noMatchOU, uidAttr, act, attrs);

            as.setSuccess(true);

        } else {
            lookupUser(as, session, myvd, noMatchOU, uidAttr, lookupFilter, act, attrs);
        }

        String redirectToURL = request.getParameter("target");
        if (redirectToURL != null && !redirectToURL.isEmpty()) {
            reqHolder.setURL(redirectToURL);
        }

        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);

    }

}

From source file:com.tremolosecurity.provisioning.customTasks.CallRemoteWorkflow.java

@Override
public boolean doTask(User user, Map<String, Object> request) throws ProvisioningException {

    HashMap<String, Object> newRequest = new HashMap<String, Object>();
    for (String name : this.fromRequest) {
        newRequest.put(name, request.get(name));
    }//from ww  w .  j a  v  a  2 s. c o m

    for (String key : this.staticRequest.keySet()) {
        newRequest.put(key, this.staticRequest.get(key));
    }

    WFCall wfCall = new WFCall();
    wfCall.setName(this.workflowName);
    wfCall.setRequestParams(newRequest);
    wfCall.setUser(new TremoloUser());
    wfCall.getUser().setUid(user.getUserID());
    wfCall.getUser().setUserPassword(user.getPassword());
    wfCall.getUser().setGroups(user.getGroups());
    wfCall.getUser().setAttributes(new ArrayList<Attribute>());
    wfCall.getUser().getAttributes().addAll(user.getAttribs().values());
    wfCall.setUidAttributeName(uidAttributeName);
    wfCall.setReason(task.getWorkflow().getUser().getRequestReason());
    if (task.getWorkflow().getRequester() != null) {
        wfCall.setRequestor(task.getWorkflow().getRequester().getUserID());
    } else {
        wfCall.setRequestor(this.lastMileUser);
    }

    DateTime notBefore = new DateTime();
    notBefore = notBefore.minusSeconds(timeSkew);
    DateTime notAfter = new DateTime();
    notAfter = notAfter.plusSeconds(timeSkew);

    com.tremolosecurity.lastmile.LastMile lastmile = null;

    try {
        lastmile = new com.tremolosecurity.lastmile.LastMile(this.uri, notBefore, notAfter, 0, "oauth2");

    } catch (URISyntaxException e) {
        throw new ProvisioningException("Could not generate lastmile", e);
    }

    Attribute attrib = new Attribute(this.lastMileUid, this.lastMileUser);
    lastmile.getAttributes().add(attrib);
    String encryptedXML = null;

    try {
        encryptedXML = lastmile
                .generateLastMileToken(this.task.getConfigManager().getSecretKey(this.lastmileKeyName));
    } catch (Exception e) {
        throw new ProvisioningException("Could not generate lastmile", e);
    }

    StringBuffer header = new StringBuffer();
    header.append("Bearer ").append(encryptedXML);

    BasicHttpClientConnectionManager bhcm = null;
    CloseableHttpClient http = null;

    try {
        bhcm = new BasicHttpClientConnectionManager(this.task.getConfigManager().getHttpClientSocketRegistry());

        RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
                .build();

        http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc).build();

        HttpPost post = new HttpPost(this.url);
        post.addHeader(new BasicHeader("Authorization", header.toString()));

        Gson gson = new Gson();
        StringEntity str = new StringEntity(gson.toJson(wfCall), ContentType.APPLICATION_JSON);
        post.setEntity(str);

        HttpResponse resp = http.execute(post);
        if (resp.getStatusLine().getStatusCode() != 200) {
            throw new ProvisioningException("Call failed");
        }

    } catch (IOException e) {
        throw new ProvisioningException("Could not make call", e);
    } finally {
        if (http != null) {
            try {
                http.close();
            } catch (IOException e) {
                logger.warn(e);
            }
        }

        if (bhcm != null) {
            bhcm.close();
        }

    }

    return true;
}

From source file:com.gsma.mobileconnect.utils.RestClient.java

/**
 * Execute the given request./*from   ww w.j av  a 2  s  . c  om*/
 * <p>
 * Abort the request if it exceeds the specified timeout.
 *
 * @param httpClient The client to use.
 * @param request The request to make.
 * @param context The context to use.
 * @param timeout The timeout to use.
 * @return A Http Response.
 * @throws RestException Thrown if the request fails or times out.
 */
private CloseableHttpResponse executeRequest(CloseableHttpClient httpClient, final HttpRequestBase request,
        HttpClientContext context, int timeout) throws RestException {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            request.abort();
        }
    }, timeout);

    RequestConfig localConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout)
            .setConnectTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD).build();
    request.setConfig(localConfig);
    try {
        return httpClient.execute(request, context);
    } catch (IOException ex) {
        String requestUri = request.getURI().toString();
        if (request.isAborted()) {
            throw new RestException("Rest end point did not respond", requestUri);
        }
        throw new RestException("Rest call failed", requestUri, ex);
    }
}

From source file:org.apache.jmeter.protocol.http.control.TestHC4CookieManager.java

/**
 * @throws Exception/*from ww w.j a v a 2s .  c o  m*/
 */
@Test
public void testBug56358() throws Exception {
    URL url = new URL("http://remote.com:10008/get/cookie");
    String headerLine = "test=value;Max-age=120;path=/;Version=1";
    man.setCookiePolicy(CookieSpecs.STANDARD);
    man.addCookieFromHeader(headerLine, url);

    Assert.assertEquals(1, man.getCookieCount());
    HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
    URL urlSameDomainDifferentPort = new URL("http://remote.com:10001/test/me");

    List<org.apache.http.cookie.Cookie> cookies = cookieHandler.getCookiesForUrl(man.getCookies(),
            urlSameDomainDifferentPort, CookieManager.ALLOW_VARIABLE_COOKIES);
    Assert.assertEquals(1, cookies.size());
    for (org.apache.http.cookie.Cookie cookie : cookies) {
        // See http://tools.ietf.org/html/rfc6265#section-5.2.3
        Assert.assertEquals("remote.com", cookie.getDomain());
        Assert.assertEquals("test", cookie.getName());
    }
}