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.jboss.as.test.integration.web.cookie.DefaultCookieVersionTestCase.java

private void commonSendCookieVersion(int cookieVersion) throws IOException, URISyntaxException {
    configureDefaultCookieVersion(cookieVersion);

    BasicCookieStore basicCookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("testCookie", "testCookieValue");
    cookie.setVersion(cookieVersion);/*from  w ww .j a  va2 s.  co m*/
    cookie.setDomain(cookieURL.getHost());
    basicCookieStore.addCookie(cookie);

    try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCookieStore(basicCookieStore)
            .build()) {
        HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieEchoServlet"));
        if (response.getEntity() != null) {
            Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(cookieVersion + "", EntityUtils.toString(response.getEntity()));
        }
    }
}

From source file:org.cloudfoundry.identity.uaa.integration.ImplicitTokenGrantIntegrationTests.java

@Test
public void authzWithIntermediateFormLoginSucceeds() throws Exception {

    BasicCookieStore cookies = new BasicCookieStore();

    ResponseEntity<Void> result = serverRunning.getForResponse(implicitUrl(), getHeaders(cookies));
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = result.getHeaders().getLocation().toString();
    if (result.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : result.getHeaders().get("Set-Cookie")) {
            int nameLength = cookie.indexOf('=');
            cookies.addCookie(/*from   w ww .j  av a 2s.c o  m*/
                    new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1)));
        }
    }

    ResponseEntity<String> response = serverRunning.getForString(location, getHeaders(cookies));
    if (response.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : response.getHeaders().get("Set-Cookie")) {
            int nameLength = cookie.indexOf('=');
            cookies.addCookie(
                    new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1)));
        }
    }
    // should be directed to the login screen...
    assertTrue(response.getBody().contains("/login.do"));
    assertTrue(response.getBody().contains("username"));
    assertTrue(response.getBody().contains("password"));

    location = "/login.do";

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", testAccounts.getUserName());
    formData.add("password", testAccounts.getPassword());
    formData.add(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME,
            IntegrationTestUtils.extractCookieCsrf(response.getBody()));

    result = serverRunning.postForRedirect(location, getHeaders(cookies), formData);

    // System.err.println(result.getStatusCode());
    // System.err.println(result.getHeaders());

    assertNotNull(result.getHeaders().getLocation());
    assertTrue(result.getHeaders().getLocation().toString().matches(REDIRECT_URL_PATTERN));
}

From source file:org.pixmob.appengine.client.AppEngineClient.java

/**
 * Create a new instance. No account is set: the method
 * {@link #setAccount(String)} must be called prior to executing a request.
 * @param context used for getting services and starting intents
 * @param appEngineHost hostname where the AppEngine is hosted
 * @param delegate {@link HttpClient} instance for making HTTP requests
 *//*from w w w  .j av a  2  s .  c om*/
public AppEngineClient(final Context context, final String appEngineHost, final HttpClient delegate) {
    this.context = context.getApplicationContext();
    this.appEngineHost = appEngineHost;

    delegateWasSet = delegate != null;
    this.delegate = delegateWasSet ? delegate : SSLEnabledHttpClient.newInstance(HTTP_USER_AGENT);

    accountManager = AccountManager.get(context);

    loginClient = SSLEnabledHttpClient.newInstance(HTTP_USER_AGENT);
    loginClient.setCookieStore(new BasicCookieStore());
    loginClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

    setRetryCount(3);
}

From source file:com.dhenton9000.filedownloader.FileDownloader.java

/**
 * Load in all the cookies WebDriver currently knows about so that we can mimic the browser cookie state
 *
 * @param seleniumCookieSet Set&lt;Cookie&gt;
 *///from w w  w  .  j  a  v  a 2 s. com
private BasicCookieStore mimicCookieState(Set<Cookie> seleniumCookieSet) {
    BasicCookieStore copyOfWebDriverCookieStore = new BasicCookieStore();
    for (Cookie seleniumCookie : seleniumCookieSet) {
        BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(),
                seleniumCookie.getValue());
        duplicateCookie.setDomain(seleniumCookie.getDomain());
        duplicateCookie.setSecure(seleniumCookie.isSecure());
        duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());
        duplicateCookie.setPath(seleniumCookie.getPath());
        copyOfWebDriverCookieStore.addCookie(duplicateCookie);
    }

    return copyOfWebDriverCookieStore;
}

From source file:io.undertow.server.handlers.session.URLRewritingSessionTestCase.java

@Test
public void testURLRewritingWithQueryParameters() throws IOException {
    TestHttpClient client = new TestHttpClient();
    client.setCookieStore(new BasicCookieStore());
    try {/*from w w  w .  j  a  v  a 2s  .  co  m*/
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath?a=b;c");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String url = HttpClientUtils.readResponse(result);
        Header[] header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());
        Assert.assertEquals("b;c", result.getHeaders("a")[0].getValue());

        get = new HttpGet(url);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        url = HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("1", header[0].getValue());
        Assert.assertEquals("b;c", result.getHeaders("a")[0].getValue());

        get = new HttpGet(url);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        url = HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("2", header[0].getValue());
        Assert.assertEquals("b;c", result.getHeaders("a")[0].getValue());

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

public String GetOSMUser(String usr, String psw) throws IOException {
    final OAuth10aService service = new ServiceBuilder().apiKey(API_KEY).apiSecret(API_SECRET)
            .build(OSMApi.instance());//w ww  .  java  2 s .c  om
    final OAuth1RequestToken requestToken = service.getRequestToken();
    String url = service.getAuthorizationUrl(requestToken);

    //Automated grant and login***************************************
    //Get logon form
    CookieStore httpCookieStore = new BasicCookieStore();
    HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore).build();
    //post.setHeader("User-Agent", USER_AGENT);
    try {
        PageContent pc = Helper.GetPageContent(url, client);

        List<Cookie> cookies = httpCookieStore.getCookies();
        System.out.println("Getting OSM Login page");
        String page = pc.GetPage();

        System.out.println("Sending username and password");

        int start_indx = page.indexOf("value=\"", page.indexOf("name=\"authenticity_token\"")) + 7;
        int end_indx = page.indexOf("\"", start_indx);

        String utf8 = "";
        String authenticity_token = page.substring(start_indx, end_indx);

        start_indx = page.indexOf("value=\"", page.indexOf("name=\"referer\"")) + 7;
        end_indx = page.indexOf("\"", start_indx);
        String referer = page.substring(start_indx, end_indx);

        Map<String, String> arguments = new HashMap<>();
        arguments.put("utf8", utf8);
        arguments.put("authenticity_token", authenticity_token);
        arguments.put("referer", referer);
        arguments.put("username", usr);
        arguments.put("password", psw);
        arguments.put("commit", "Login");
        arguments.put("openid_url", "");

        System.out.println("Logging in");
        page = sendForm(BASE_URL + "login", arguments, "POST", cookies);

        //Proccessing grant access page
        System.out.println("Processing Granting Access page");
        start_indx = page.indexOf("<form");//Find form tag
        start_indx = page.indexOf("action=\"", start_indx) + 8; //get action url
        end_indx = page.indexOf("\"", start_indx); //get closing tag
        String action_url = page.substring(start_indx, end_indx);
        if (action_url.startsWith("/")) {
            action_url = BASE_URL + action_url.substring(1, action_url.length());
        } else if (!action_url.toLowerCase().startsWith("http")) {
            //Need to post same level as current url
            end_indx = url.lastIndexOf("/") + 1;
            action_url = url.substring(0, end_indx) + action_url;
        }

        start_indx = page.indexOf("name=\"authenticity_token\"");
        start_indx = FindOpening(page, start_indx, "<");
        start_indx = page.indexOf("value=\"", start_indx) + 7;
        end_indx = page.indexOf("\"", start_indx);
        authenticity_token = page.substring(start_indx, end_indx);

        start_indx = page.indexOf("name=\"oauth_token\"");
        start_indx = FindOpening(page, start_indx, "<");
        start_indx = page.indexOf("value=\"", start_indx) + 7;
        end_indx = page.indexOf("\"", start_indx);
        String oauth_token = page.substring(start_indx, end_indx);

        arguments.clear();
        arguments.put("utf8", utf8);
        arguments.put("authenticity_token", authenticity_token);
        arguments.put("oauth_token", oauth_token);
        arguments.put("allow_read_prefs", "yes");
        arguments.put("commit", "Grant+Access");

        //Get PIN
        System.out.println("Submitting grant access");
        page = sendForm(action_url, arguments, "POST", cookies);

        //Find lovely PIN code in page that might be multilingual...(fun)
        start_indx = page.indexOf("class=\"content-body\"");
        end_indx = page.indexOf("</div>", start_indx);
        String tmp = page.substring(start_indx, end_indx); //Get aproximate location of pin code

        Pattern p = Pattern.compile("([A-Za-z0-9]){15,25}");
        Matcher m = p.matcher(tmp);
        String pin = "";
        if (m.find()) {
            pin = m.group();
        }
        final OAuth1AccessToken accessToken = service.getAccessToken(requestToken, pin);
        return accessToken.getToken() + "|" + accessToken.getTokenSecret();

    } catch (Exception ex) {
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
    }

    //End Automated grant and login **********************************
    return "";
}

From source file:com.ngdata.hbaseindexer.indexer.FusionPipelineClient.java

public FusionPipelineClient(String endpointUrl, String fusionUser, String fusionPass, String fusionRealm)
        throws MalformedURLException {

    this.fusionUser = fusionUser;
    this.fusionPass = fusionPass;
    this.fusionRealm = fusionRealm;

    String fusionLoginConf = System.getProperty(FusionKrb5HttpClientConfigurer.LOGIN_CONFIG_PROP);
    if (fusionLoginConf != null && !fusionLoginConf.isEmpty()) {
        httpClient = FusionKrb5HttpClientConfigurer.createClient(fusionUser);
        isKerberos = true;//from   www .jav  a  2 s .co  m
    } else {
        globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
        cookieStore = new BasicCookieStore();

        // build the HttpClient to be used for all requests
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore);
        httpClientBuilder.setMaxConnPerRoute(100);
        httpClientBuilder.setMaxConnTotal(500);

        if (fusionUser != null && fusionRealm == null)
            httpClientBuilder.addInterceptorFirst(new PreEmptiveBasicAuthenticator(fusionUser, fusionPass));

        httpClient = httpClientBuilder.build();
    }

    originalEndpoints = Arrays.asList(endpointUrl.split(","));
    try {
        sessions = establishSessions(originalEndpoints, fusionUser, fusionPass, fusionRealm);
    } catch (Exception exc) {
        if (exc instanceof RuntimeException) {
            throw (RuntimeException) exc;
        } else {
            throw new RuntimeException(exc);
        }
    }

    random = new Random();
    jsonObjectMapper = new ObjectMapper();

    requestCounter = new AtomicInteger(0);
}

From source file:com.openx.oauth.client.Helper.java

/**
 * Creates the OX3 API cookie store//from www .java 2s .  com
 * @param domain
 * @param value 
 */
protected void createCookieStore(String domain, String value) {
    if (cookieStore == null) {
        cookieStore = new BasicCookieStore();
    }
    BasicClientCookie cookie = new BasicClientCookie("openx3_access_token", value);
    cookie.setVersion(0);
    cookie.setDomain(domain.replace("http://", ""));
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
}