Example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore

List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore.

Prototype

public BasicCookieStore() 

Source Link

Usage

From source file:org.apache.felix.http.itest.SessionHandlingTest.java

@Test
public void testSessionAttributes() throws Exception {
    setupContext("test1", "/");
    setupContext("test2", "/");

    setupLatches(2);//  w w w  . j  a  v a 2  s  .  co  m

    setupServlet("foo", new String[] { "/foo" }, 1, "test1");
    setupServlet("bar", new String[] { "/bar" }, 2, "test2");

    assertTrue(initLatch.await(5, TimeUnit.SECONDS));

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setDefaultCookieStore(new BasicCookieStore()).build();

    JSONObject json;

    // session should not be available
    // check for foo servlet
    json = getJSONResponse(httpclient, "/foo");
    assertFalse(((Boolean) json.get("session")).booleanValue());

    // check for bar servlet
    json = getJSONResponse(httpclient, "/bar");
    assertFalse(((Boolean) json.get("session")).booleanValue());

    // create session for  context of servlet foo
    // check session and session attribute
    json = getJSONResponse(httpclient, "/foo?create=true");
    assertTrue(((Boolean) json.get("session")).booleanValue());
    assertEquals("test1", json.get("value"));
    final String sessionId1 = (String) json.get("sessionId");
    assertNotNull(sessionId1);

    // check session for servlet bar (= no session)
    json = getJSONResponse(httpclient, "/bar");
    assertFalse(((Boolean) json.get("session")).booleanValue());
    // another request to servlet foo, still the same
    json = getJSONResponse(httpclient, "/foo");
    assertTrue(((Boolean) json.get("session")).booleanValue());
    assertEquals("test1", json.get("value"));
    assertEquals(sessionId1, json.get("sessionId"));

    // create session for second context
    json = getJSONResponse(httpclient, "/bar?create=true");
    assertTrue(((Boolean) json.get("session")).booleanValue());
    assertEquals("test2", json.get("value"));
    final String sessionId2 = (String) json.get("sessionId");
    assertNotNull(sessionId2);
    assertFalse(sessionId1.equals(sessionId2));

    // and context foo is untouched
    json = getJSONResponse(httpclient, "/foo");
    assertTrue(((Boolean) json.get("session")).booleanValue());
    assertEquals("test1", json.get("value"));
    assertEquals(sessionId1, json.get("sessionId"));

    // invalidate session for foo context
    json = getJSONResponse(httpclient, "/foo?destroy=true");
    assertFalse(((Boolean) json.get("session")).booleanValue());
    // bar should be untouched
    json = getJSONResponse(httpclient, "/bar");
    assertTrue(((Boolean) json.get("session")).booleanValue());
    assertEquals("test2", json.get("value"));
    assertEquals(sessionId2, json.get("sessionId"));
}

From source file:com.ea.core.bridge.ws.rest.client.AbstractRestClient.java

public AbstractRestClient(URL httpUrl) {
    super(httpUrl);

    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
        @Override/*  ww  w .  j  a  v  a 2  s. c o m*/
        public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer,
                MessageConstraints constraints) {
            LineParser lineParser = new BasicLineParser() {
                @Override
                public Header parseHeader(final CharArrayBuffer buffer) {
                    try {
                        return super.parseHeader(buffer);
                    } catch (ParseException ex) {
                        return new BasicHeader(buffer.toString(), null);
                    }
                }
            };
            return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE,
                    constraints) {
                @Override
                protected boolean reject(final CharArrayBuffer line, int count) {
                    // try to ignore all garbage preceding a status line infinitely
                    return false;
                }
            };
        }
    };
    HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory);

    SSLContext sslcontext = SSLContexts.createSystemDefault();
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("myhost") || host.equalsIgnoreCase("localhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return super.resolve(host);
            }
        }

    };

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, connFactory, dnsResolver);

    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);

    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(10);
    connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    CookieStore cookieStore = new BasicCookieStore();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(3000)
            .setConnectTimeout(3000).setSocketTimeout(3000).build();

    client = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credentialsProvider)
            //            .setProxy(new HttpHost("myproxy", 8080))
            .setDefaultRequestConfig(defaultRequestConfig).build();
}

From source file:edu.mit.scratch.Scratch.java

public static ScratchSession register(final String username, final String password, final String gender,
        final int birthMonth, final String birthYear, final String country, final String email)
        throws ScratchUserException {
    // Long if statement to verify all fields are valid
    if ((username.length() < 3) || (username.length() > 20) || (password.length() < 6) || (gender.length() < 2)
            || (birthMonth < 1) || (birthMonth > 12) || (birthYear.length() != 4) || (country.length() == 0)
            || (email.length() < 5)) {
        throw new ScratchUserException(); // TDL: Specify reason for failure
    } else {/*  w w w  .  j  a  v  a2 s  .  c  o m*/
        try {
            final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
                    .build();

            final CookieStore cookieStore = new BasicCookieStore();
            final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
            lang.setDomain(".scratch.mit.edu");
            lang.setPath("/");
            cookieStore.addCookie(lang);

            CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                    .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
            CloseableHttpResponse resp;

            final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/")
                    .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu")
                    .addHeader("X-Requested-With", "XMLHttpRequest").build();
            try {
                resp = httpClient.execute(csrf);
            } catch (final IOException e) {
                e.printStackTrace();
                throw new ScratchUserException();
            }
            try {
                resp.close();
            } catch (final IOException e) {
                throw new ScratchUserException();
            }

            String csrfToken = null;
            for (final Cookie c : cookieStore.getCookies())
                if (c.getName().equals("scratchcsrftoken"))
                    csrfToken = c.getValue();

            /*
             * try {
             * username = URLEncoder.encode(username, "UTF-8");
             * password = URLEncoder.encode(password, "UTF-8");
             * birthMonth = Integer.parseInt(URLEncoder.encode("" +
             * birthMonth, "UTF-8"));
             * birthYear = URLEncoder.encode(birthYear, "UTF-8");
             * gender = URLEncoder.encode(gender, "UTF-8");
             * country = URLEncoder.encode(country, "UTF-8");
             * email = URLEncoder.encode(email, "UTF-8");
             * } catch (UnsupportedEncodingException e1) {
             * e1.printStackTrace();
             * }
             */

            final BasicClientCookie csrfCookie = new BasicClientCookie("scratchcsrftoken", csrfToken);
            csrfCookie.setDomain(".scratch.mit.edu");
            csrfCookie.setPath("/");
            cookieStore.addCookie(csrfCookie);
            final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
            debug.setDomain(".scratch.mit.edu");
            debug.setPath("/");
            cookieStore.addCookie(debug);

            httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                    .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();

            /*
             * final String data = "username=" + username + "&password=" +
             * password + "&birth_month=" + birthMonth + "&birth_year=" +
             * birthYear + "&gender=" + gender + "&country=" + country +
             * "&email=" + email +
             * "&is_robot=false&should_generate_admin_ticket=false&usernames_and_messages=%3Ctable+class%3D'banhistory'%3E%0A++++%3Cthead%3E%0A++++++++%3Ctr%3E%0A++++++++++++%3Ctd%3EAccount%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EEmail%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EReason%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EDate%3C%2Ftd%3E%0A++++++++%3C%2Ftr%3E%0A++++%3C%2Fthead%3E%0A++++%0A%3C%2Ftable%3E%0A&csrfmiddlewaretoken="
             * + csrfToken;
             * System.out.println(data);
             */

            final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addTextBody("birth_month", birthMonth + "", ContentType.TEXT_PLAIN);
            builder.addTextBody("birth_year", birthYear, ContentType.TEXT_PLAIN);
            builder.addTextBody("country", country, ContentType.TEXT_PLAIN);
            builder.addTextBody("csrfmiddlewaretoken", csrfToken, ContentType.TEXT_PLAIN);
            builder.addTextBody("email", email, ContentType.TEXT_PLAIN);
            builder.addTextBody("gender", gender, ContentType.TEXT_PLAIN);
            builder.addTextBody("is_robot", "false", ContentType.TEXT_PLAIN);
            builder.addTextBody("password", password, ContentType.TEXT_PLAIN);
            builder.addTextBody("should_generate_admin_ticket", "false", ContentType.TEXT_PLAIN);
            builder.addTextBody("username", username, ContentType.TEXT_PLAIN);
            builder.addTextBody("usernames_and_messages",
                    "<table class=\"banhistory\"> <thead> <tr> <td>Account</td> <td>Email</td> <td>Reason</td> <td>Date</td> </tr> </thead> </table>",
                    ContentType.TEXT_PLAIN);

            final HttpUriRequest createAccount = RequestBuilder.post()
                    .setUri("https://scratch.mit.edu/accounts/register_new_user/")
                    .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                    .addHeader("Referer", "https://scratch.mit.edu/accounts/standalone-registration/")
                    .addHeader("Origin", "https://scratch.mit.edu")
                    .addHeader("Accept-Encoding", "gzip, deflate").addHeader("DNT", "1")
                    .addHeader("Accept-Language", "en-US,en;q=0.8")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .addHeader("X-Requested-With", "XMLHttpRequest").addHeader("X-CSRFToken", csrfToken)
                    .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id",
                            "54255D9A-9771-4CAC-9052-50C8AB7469E0")
                    .setEntity(builder.build()).build();
            resp = httpClient.execute(createAccount);
            System.out.println("REGISTER:" + resp.getStatusLine());
            final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            final StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null)
                result.append(line);
            System.out.println("exact:" + result.toString() + "\n" + resp.getStatusLine().getReasonPhrase()
                    + "\n" + resp.getStatusLine());
            if (resp.getStatusLine().getStatusCode() != 200)
                throw new ScratchUserException();
            resp.close();
        } catch (final Exception e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }
        try {
            return Scratch.createSession(username, password);
        } catch (final Exception e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }
    }
}

From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.RestServiceToAPIExecutor.java

/**
 * Update the APIM DB for the published API.
 *
 * @param api/*from w ww  . ja  va2  s  . c  om*/
 * @param serviceName
 */
private void publishDataToAPIM(GenericArtifact api, String serviceName) throws GovernanceException {

    if (apimEndpoint == null || apimUsername == null || apimPassword == null) {
        String msg = "APIManager endpoint URL or credentials are not defined";
        log.error(msg);
        throw new RuntimeException(msg + "API Publish might fail");
    }

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    authenticateAPIM(httpContext);
    String addAPIendpoint = apimEndpoint + "publisher/site/blocks/item-add/ajax/add.jag";

    try {
        // create a post request to addAPI.
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(addAPIendpoint);

        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        for (String key : api.getAttributeKeys()) {
            if (log.isDebugEnabled()) {
                log.error(key + "  :  " + api.getAttribute(key));
            }
        }

        if (api.getAttribute("overview_endpointURL") != null
                && api.getAttribute("overview_endpointURL").isEmpty()) {
            String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore.Publishing at gateway might fail";
            log.warn(msg);
        }

        //params.add(new BasicNameValuePair(API_ENDPOINT, api.getAttribute("overview_endpointURL")));
        params.add(new BasicNameValuePair(API_ACTION, API_ADD_ACTION));
        params.add(new BasicNameValuePair(API_NAME, serviceName));
        params.add(new BasicNameValuePair(API_CONTEXT, serviceName));
        params.add(new BasicNameValuePair(API_VERSION, api.getAttribute(SERVICE_VERSION)));
        params.add(new BasicNameValuePair("API_PROVIDER",
                CarbonContext.getThreadLocalCarbonContext().getUsername()));
        params.add(new BasicNameValuePair(API_TIER, defaultTier));
        params.add(new BasicNameValuePair(API_URI_PATTERN, DEFAULT_URI_PATTERN));
        params.add(new BasicNameValuePair(API_URI_HTTP_METHOD, DEFAULT_HTTP_VERB));
        params.add(new BasicNameValuePair(API_URI_AUTH_TYPE, DEFAULT_AUTH_TYPE));
        params.add(new BasicNameValuePair(API_VISIBLITY, DEFAULT_VISIBILITY));
        params.add(new BasicNameValuePair(API_THROTTLING_TIER, apiThrottlingTier));

        String[] endPoints = api.getAttributes(Constants.ENDPOINTS_ENTRY);
        if (endPoints != null && endPoints.length > 0) {
            List<String> endPointsList = Arrays.asList(endPoints);
            if (endPointsList.size() > 0) {
                String endpointConfigJson = "{\"production_endpoints\":{\"url\":\""
                        + getEnvironmentUrl(endPointsList) + "\",\"config\":null},\"endpoint_type\":\"http\"}";
                params.add(new BasicNameValuePair(Constants.ENDPOINT_CONFIG, endpointConfigJson));
            } else {
                String msg = "Endpoint is a must attribute to create an API definition at the APIStore";
                throw new GovernanceException(msg);
            }
        } else {
            String msg = "Endpoint is a must attribute to create an API definition at the APIStore";
            throw new GovernanceException(msg);
        }

        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        HttpResponse response = httpclient.execute(httppost, httpContext);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

    } catch (Exception e) {
        log.error("Error in updating APIM", e);
        throw new GovernanceException("Error in updating APIM", e);

    }
    // after publishing update the lifecycle status
    //updateStatus(service, serviceName, httpContext);
}

From source file:edu.mit.scratch.ScratchUser.java

public boolean comment(final ScratchSession session, final String comment) throws ScratchProjectException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    final CookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
    final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", session.getSessionID());
    final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", session.getCSRFToken());
    final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
    lang.setDomain(".scratch.mit.edu");
    lang.setPath("/");
    sessid.setDomain(".scratch.mit.edu");
    sessid.setPath("/");
    token.setDomain(".scratch.mit.edu");
    token.setPath("/");
    debug.setDomain(".scratch.mit.edu");
    debug.setPath("/");
    cookieStore.addCookie(lang);/*from  ww w .  j av  a  2 s . c o m*/
    cookieStore.addCookie(sessid);
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

    final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
    CloseableHttpResponse resp;

    final JSONObject obj = new JSONObject();
    obj.put("content", comment);
    obj.put("parent_id", "");
    obj.put("commentee_id", "");
    final String strData = obj.toString();

    HttpUriRequest update = null;
    try {
        update = RequestBuilder.post()
                .setUri("https://scratch.mit.edu/site-api/comments/user/" + this.getUsername() + "/add/")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu/users/" + this.getUsername() + "/")
                .addHeader("Origin", "https://scratch.mit.edu/")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("Cookie",
                        "scratchsessionsid=" + session.getSessionID() + "; scratchcsrftoken="
                                + session.getCSRFToken())
                .addHeader("X-CSRFToken", session.getCSRFToken()).setEntity(new StringEntity(strData)).build();
    } catch (final UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    try {
        resp = httpClient.execute(update);
        final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return false;
}

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

private void createClient() {
    log.info("Connecting to Opal: {}", opalURI);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    if (keyStore == null)
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, Boolean.TRUE);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,
            Collections.singletonList(OpalAuth.CREDENTIALS_HEADER));
    httpClient.getParams().setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME,
            OpalClientConnectionManagerFactory.class.getName());
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(DEFAULT_MAX_ATTEMPT, false));
    httpClient.getAuthSchemes().register(OpalAuth.CREDENTIALS_HEADER, new OpalAuthScheme.Factory());

    try {//from  w w w.j a  v a2 s  .  com
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", HTTPS_PORT, getSocketFactory()));
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
    client = enableCaching(httpClient);

    ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
}

From source file:org.openrdf.http.client.SparqlSession.java

public SparqlSession(HttpClient client, ExecutorService executor) {
    this.httpClient = client;
    this.httpContext = new BasicHttpContext();
    this.executor = executor;
    valueFactory = SimpleValueFactory.getInstance();
    params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    CookieStore cookieStore = new BasicCookieStore();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

    // parser used for processing server response data should be lenient
    parserConfig.addNonFatalError(BasicParserSettings.VERIFY_DATATYPE_VALUES);
    parserConfig.addNonFatalError(BasicParserSettings.VERIFY_LANGUAGE_TAGS);
}

From source file:sample.ui.mvc.MessageController.java

private String getBidId(Message message) {
    try {//from w  w  w  .  j a v a2  s . c o  m
        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        doLogin(cookieStore, httpclient, ZHANGDAIYIXIAN);

        //

        String bidName = message.getBidName();
        // time
        //
        String mainUrl = "http://www.wujinsuo.cn:80/index.php";
        HttpGet httpget = new HttpGet(mainUrl);
        httpget.addHeader("Accept", ACCEPT);
        httpget.addHeader("User-Agent", AGENT);

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String resultString = httpclient.execute(httpget, responseHandler);
        // parse html
        Document doc = Jsoup.parse(resultString);
        Elements links = doc.select("a[href]");

        Element aElement = null;
        for (Element e : links) {
            List<Node> childNode = e.childNodes();
            if (childNode.size() != 1)
                continue;
            Node node = childNode.get(0);
            if ("span".equals(node.nodeName())) {
                String html = node.outerHtml();
                logger.info(html);
                if (html.contains(bidName)) {
                    // okle
                    aElement = e;
                }
            }
        }
        if (aElement == null) {
            // retry
            return "";
        } else {

            String href = aElement.attr("href");
            String bidId = StringUtils.substringAfter(href, "id=");
            logger.info(bidId);
            return bidId;
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:org.wildfly.elytron.web.undertow.server.FormAuthenticationWithClusteredSSOTest.java

@Test
public void testSingleLogoutWhenNodeIsFailing() throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

    assertLoginPage(httpClient.execute(new HttpGet(serverA.createUri())));

    // authenticate on NODE_A
    HttpPost httpAuthenticate = new HttpPost(serverA.createUri("/j_security_check"));
    List<NameValuePair> parameters = new ArrayList<>(2);

    parameters.add(new BasicNameValuePair("j_username", "ladybird"));
    parameters.add(new BasicNameValuePair("j_password", "Coleoptera"));

    httpAuthenticate.setEntity(new UrlEncodedFormEntity(parameters));

    HttpResponse execute = httpClient.execute(httpAuthenticate);

    assertSuccessfulResponse(execute, "ladybird");
    assertSuccessfulResponse(httpClient.execute(new HttpGet(serverB.createUri())), "ladybird");
    assertSuccessfulResponse(httpClient.execute(new HttpGet(serverC.createUri())), "ladybird");
    assertSuccessfulResponse(httpClient.execute(new HttpGet(serverD.createUri())), "ladybird");
    assertSuccessfulResponse(httpClient.execute(new HttpGet(serverE.createUri())), "ladybird");

    serverC.forceShutdown();/*from ww  w  .ja  v  a  2s  .c  o m*/
    serverE.forceShutdown();

    httpClient.execute(new HttpGet(serverB.createUri("/logout")));

    assertLoginPage(httpClient.execute(new HttpGet(serverA.createUri())));
    assertLoginPage(httpClient.execute(new HttpGet(serverB.createUri())));
    assertLoginPage(httpClient.execute(new HttpGet(serverD.createUri())));
}

From source file:fr.cnes.sitools.metacatalogue.resources.proxyservices.RedirectorHttps.java

/**
 * CloseableHttpResponse//from w ww.j  a v  a  2 s . c  o m
 * 
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public CloseableHttpResponse getCloseableResponse(String url, Series<Cookie> cookies)
        throws ClientProtocolException, IOException {

    HttpClientBuilder httpclientBuilder = HttpClients.custom();

    if (withproxy) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                ProxySettings.getProxyUser(), ProxySettings.getProxyPassword()));
        httpclientBuilder.setDefaultCredentialsProvider(credsProvider).build();
    }
    CloseableHttpClient httpclient = httpclientBuilder.build();

    HttpClientContext context = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();

    Iterator<Cookie> iter = cookies.iterator();

    while (iter.hasNext()) {
        Cookie restCookie = iter.next();
        BasicClientCookie cookie = new BasicClientCookie(restCookie.getName(), restCookie.getValue());
        // cookie.setDomain(restCookie.getDomain());
        cookie.setDomain(getDomainName(url));
        cookie.setPath(restCookie.getPath());
        cookie.setSecure(true);
        // cookie.setExpiryDate(restCookie);
        cookieStore.addCookie(cookie);
    }

    context.setCookieStore(cookieStore);

    HttpGet httpget = new HttpGet(url);

    Builder configBuilder = RequestConfig.custom();

    if (withproxy) {
        HttpHost proxy = new HttpHost(ProxySettings.getProxyHost(),
                Integer.parseInt(ProxySettings.getProxyPort()), "http");
        configBuilder.setProxy(proxy).build();
    }

    RequestConfig config = configBuilder.build();
    httpget.setConfig(config);

    return httpclient.execute(httpget, context);

}