Java Code Examples for org.apache.http.impl.cookie.BasicClientCookie#setPath()

The following examples show how to use org.apache.http.impl.cookie.BasicClientCookie#setPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RealmsAPI.java    From FishingBot with GNU General Public License v3.0 6 votes vote down vote up
public RealmsAPI(AuthData authData) {
    BasicCookieStore cookies = new BasicCookieStore();

    BasicClientCookie sidCookie = new BasicClientCookie("sid", String.join(":", "token", authData.getAccessToken(), authData.getProfile()));
    BasicClientCookie userCookie = new BasicClientCookie("user", authData.getUsername());
    BasicClientCookie versionCookie = new BasicClientCookie("version", ProtocolConstants.getVersionString(FishingBot.getInstance().getServerProtocol()));

    sidCookie.setDomain(".pc.realms.minecraft.net");
    userCookie.setDomain(".pc.realms.minecraft.net");
    versionCookie.setDomain(".pc.realms.minecraft.net");

    sidCookie.setPath("/");
    userCookie.setPath("/");
    versionCookie.setPath("/");

    cookies.addCookie(sidCookie);
    cookies.addCookie(userCookie);
    cookies.addCookie(versionCookie);

    client = HttpClientBuilder.create()
            .setDefaultCookieStore(cookies)
            .build();
}
 
Example 2
Source File: BasicHttpSolrClientTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException,
IOException {
  BasicClientCookie cookie = new BasicClientCookie(cookieName, cookieValue);
  cookie.setVersion(0);
  cookie.setPath("/");
  cookie.setDomain(jetty.getBaseUrl().getHost());

  CookieStore cookieStore = new BasicCookieStore();
  CookieSpec cookieSpec = new SolrPortAwareCookieSpecFactory().create(context);
 // CookieSpec cookieSpec = registry.lookup(policy).create(context);
  // Add the cookies to the request
  List<Header> headers = cookieSpec.formatCookies(Collections.singletonList(cookie));
  for (Header header : headers) {
    request.addHeader(header);
  }
  context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
}
 
Example 3
Source File: ZdsHttp.java    From zest-writer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Authentication with google account
 * @param cookies cookies list keys from google auth
 * @param login username associated to zds login
 * @param id user id on ZdS associated to login
 */
public void authToGoogle(List<HttpCookie> cookies, String login, String id) {
    if(login != null && id != null) {
        this.login = login;
        this.idUser = id;
        log.info("L'identifiant de l'utilisateur " + this.login + " est : " + idUser);
        cookieStore = new BasicCookieStore();
        for(HttpCookie cookie:cookies) {
            BasicClientCookie c = new BasicClientCookie(cookie.getName(), cookie.getValue());
            c.setDomain(cookie.getDomain());
            c.setPath(cookie.getPath());
            c.setSecure(cookie.getSecure());
            c.setVersion(cookie.getVersion());
            c.setComment(cookie.getComment());
            cookieStore.addCookie(c);
        }
        context.setCookieStore(cookieStore);
        this.authenticated = true;
    }
    else {
        log.debug("Le login de l'utilisateur n'a pas pu être trouvé");
    }
}
 
Example 4
Source File: HttpClient.java    From utils with Apache License 2.0 6 votes vote down vote up
public void setCookies(Map<String, String> cookies, String domain, String path) {
    if (null == cookies || cookies.isEmpty()) {
        return;
    }

    for (String key : cookies.keySet()) {
        BasicClientCookie cookie = new BasicClientCookie(key, cookies.get(key));
        if (domain.startsWith(HTTP_PRO)) {
            domain = domain.substring(HTTP_PRO.length());
        }
        if (domain.startsWith(HTTPS_PRO)) {
            domain = domain.substring(HTTPS_PRO.length());
        }
        cookie.setDomain(domain);
        if (StringUtils.isBlank(path)) {
            cookie.setPath("/");
        } else {
            cookie.setPath(path);
        }
        cookieStore.addCookie(cookie);
    }
}
 
Example 5
Source File: ApacheHttpClient.java    From karate with MIT License 6 votes vote down vote up
@Override
protected void buildCookie(com.intuit.karate.http.Cookie c) {
    BasicClientCookie cookie = new BasicClientCookie(c.getName(), c.getValue());
    for (Entry<String, String> entry : c.entrySet()) {
        switch (entry.getKey()) {
            case DOMAIN:
                cookie.setDomain(entry.getValue());
                break;
            case PATH:
                cookie.setPath(entry.getValue());
                break;
        }
    }
    if (cookie.getDomain() == null) {
        cookie.setDomain(uriBuilder.getHost());
    }
    cookieStore.addCookie(cookie);
}
 
Example 6
Source File: FetcherFactory.java    From ache with Apache License 2.0 6 votes vote down vote up
public static ConcurrentCookieJar createApacheCookieStore(HttpDownloaderConfig config) {
    List<HttpDownloaderConfig.Cookie> cookies = config.getCookies();
    if (cookies == null) {
        return null;
    }
    ConcurrentCookieJar store = new ConcurrentCookieJar();
    for (HttpDownloaderConfig.Cookie cookie : cookies) {
        String[] values = cookie.cookie.split("; ");
        for (int i = 0; i < values.length; i++) {
            String[] kv = values[i].split("=", 2);
            BasicClientCookie cc = new BasicClientCookie(kv[0], kv[1]);
            cc.setPath(cookie.path);
            cc.setDomain(cookie.domain);
            store.addCookie(cc);
        }
    }
    return store;
}
 
Example 7
Source File: SerializableCookie.java    From Libraries-for-Android-Developers with MIT License 5 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    String name = (String) in.readObject();
    String value = (String) in.readObject();
    clientCookie = new BasicClientCookie(name, value);
    clientCookie.setComment((String) in.readObject());
    clientCookie.setDomain((String) in.readObject());
    clientCookie.setExpiryDate((Date) in.readObject());
    clientCookie.setPath((String) in.readObject());
    clientCookie.setVersion(in.readInt());
    clientCookie.setSecure(in.readBoolean());
}
 
Example 8
Source File: SerializableCookie.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    String name = (String) in.readObject();
    String value = (String) in.readObject();
    clientCookie = new BasicClientCookie(name, value);
    clientCookie.setComment((String) in.readObject());
    clientCookie.setDomain((String) in.readObject());
    clientCookie.setExpiryDate((Date) in.readObject());
    clientCookie.setPath((String) in.readObject());
    clientCookie.setVersion(in.readInt());
    clientCookie.setSecure(in.readBoolean());
}
 
Example 9
Source File: SerializableCookie.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    String name = (String) in.readObject();
    String value = (String) in.readObject();
    clientCookie = new BasicClientCookie(name, value);
    clientCookie.setComment((String) in.readObject());
    clientCookie.setDomain((String) in.readObject());
    clientCookie.setExpiryDate((Date) in.readObject());
    clientCookie.setPath((String) in.readObject());
    clientCookie.setVersion(in.readInt());
    clientCookie.setSecure(in.readBoolean());
}
 
Example 10
Source File: CloseableClientProviderTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGetHttpClientWithTrustStoreWithCookies() throws ZaasConfigurationException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("apimlAuthenticationToken", "token");
    cookie.setDomain(configProperties.getApimlHost());
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

    assertNotNull(httpsClientProvider.getHttpsClientWithTrustStore(cookieStore));
}
 
Example 11
Source File: BitShareAccount.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
private void initialize() throws Exception {
    httpContext = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    
    //Force to use en language
    BasicClientCookie cookie = new BasicClientCookie("language_selection", "EN");
    cookie.setDomain(".bitshare.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

    //NULogger.getLogger().info("Getting startup cookies & link from BitShare.com");
    //responseString = NUHttpClientUtils.getData("http://bitshare.com", httpContext);
}
 
Example 12
Source File: MyCookieDBManager.java    From Huochexing12306 with Apache License 2.0 5 votes vote down vote up
public List<Cookie> getAllCookies() {
	List<Cookie> cookies = new ArrayList<Cookie>();

	Cursor cursor = db
			.query(TABLE_NAME, null, null, null, null, null, null);

	for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
		String name = cursor.getString(cursor.getColumnIndex(Column.NAME));
		String value = cursor
				.getString(cursor.getColumnIndex(Column.VALUE));

		BasicClientCookie cookie = new BasicClientCookie(name, value);

		cookie.setComment(cursor.getString(cursor
				.getColumnIndex(Column.COMMENT)));
		cookie.setDomain(cursor.getString(cursor
				.getColumnIndex(Column.DOMAIN)));
		long expireTime = cursor.getLong(cursor
				.getColumnIndex(Column.EXPIRY_DATE));
		if (expireTime != 0) {
			cookie.setExpiryDate(new Date(expireTime));
		}
		cookie.setPath(cursor.getString(cursor.getColumnIndex(Column.PATH)));
		cookie.setSecure(cursor.getInt(cursor.getColumnIndex(Column.SECURE)) == 1);
		cookie.setVersion(cursor.getInt(cursor
				.getColumnIndex(Column.VERSION)));

		cookies.add(cookie);
	}

	cursor.close();

	return cookies;
}
 
Example 13
Source File: SerializableCookie.java    From Mobike with Apache License 2.0 5 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    String name = (String) in.readObject();
    String value = (String) in.readObject();
    clientCookie = new BasicClientCookie(name, value);
    clientCookie.setComment((String) in.readObject());
    clientCookie.setDomain((String) in.readObject());
    clientCookie.setExpiryDate((Date) in.readObject());
    clientCookie.setPath((String) in.readObject());
    clientCookie.setVersion(in.readInt());
    clientCookie.setSecure(in.readBoolean());
}
 
Example 14
Source File: PreferencesCookieStore.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    String name = (String) in.readObject();
    String value = (String) in.readObject();
    clientCookie = new BasicClientCookie(name, value);
    clientCookie.setComment((String) in.readObject());
    clientCookie.setDomain((String) in.readObject());
    clientCookie.setExpiryDate((Date) in.readObject());
    clientCookie.setPath((String) in.readObject());
    clientCookie.setVersion(in.readInt());
    clientCookie.setSecure(in.readBoolean());
}
 
Example 15
Source File: HttpClientCookieLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    final HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

    final HttpGet request = new HttpGet("http://www.github.com");

    response = (CloseableHttpResponse) client.execute(request);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
 
Example 16
Source File: CookieManager.java    From vividus with Apache License 2.0 5 votes vote down vote up
private static org.apache.http.cookie.Cookie createHttpClientCookie(Cookie seleniumCookie)
{
    BasicClientCookie httpClientCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
    httpClientCookie.setDomain(seleniumCookie.getDomain());
    httpClientCookie.setPath(seleniumCookie.getPath());
    httpClientCookie.setExpiryDate(seleniumCookie.getExpiry());
    httpClientCookie.setSecure(seleniumCookie.isSecure());
    httpClientCookie.setAttribute(ClientCookie.DOMAIN_ATTR, seleniumCookie.getDomain());
    httpClientCookie.setAttribute(ClientCookie.PATH_ATTR, seleniumCookie.getPath());
    return httpClientCookie;
}
 
Example 17
Source File: DefaultCookieManager.java    From esigate with Apache License 2.0 4 votes vote down vote up
protected static Cookie rewriteForBrowser(Cookie cookie, DriverRequest request) {
    String name = cookie.getName();
    // Rewrite name if JSESSIONID because it will interfere with current
    // server session
    if ("JSESSIONID".equalsIgnoreCase(name)) {
        name = "_" + name;
    }

    // Rewrite domain
    String domain =
            rewriteDomain(cookie.getDomain(), request.getBaseUrl().getHost(),
                    UriUtils.extractHostName(request.getOriginalRequest().getRequestLine().getUri()));

    // Rewrite path
    String originalPath = cookie.getPath();
    String requestPath = UriUtils.getPath(request.getOriginalRequest().getRequestLine().getUri());
    String path = originalPath;
    if (requestPath == null || !requestPath.startsWith(originalPath)) {
        path = "/";
    }

    // Rewrite secure
    boolean secure =
            (cookie.isSecure() && request.getOriginalRequest().getRequestLine().getUri().startsWith("https"));

    BasicClientCookie cookieToForward = new BasicClientCookie(name, cookie.getValue());
    if (domain != null) {
        cookieToForward.setDomain(domain);
    }
    cookieToForward.setPath(path);
    cookieToForward.setSecure(secure);
    cookieToForward.setComment(cookie.getComment());
    cookieToForward.setVersion(cookie.getVersion());
    cookieToForward.setExpiryDate(cookie.getExpiryDate());

    if (((BasicClientCookie) cookie).containsAttribute(CookieUtil.HTTP_ONLY_ATTR)) {
        cookieToForward.setAttribute(CookieUtil.HTTP_ONLY_ATTR, "");
    }

    if (LOG.isDebugEnabled()) {
        // Ensure .toString is only called if debug enabled.
        LOG.debug("Forwarding cookie {} -> {}", cookie.toString(), cookieToForward.toString());
    }
    return cookieToForward;
}
 
Example 18
Source File: HC4ExchangeFormAuthenticator.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
protected ResponseWrapper postLogonMethod(HttpClientAdapter httpClient, PostRequest logonMethod, String password) throws IOException {

        setAuthFormFields(logonMethod, httpClient, password);

        // add exchange 2010 PBack cookie in compatibility mode
        BasicClientCookie pBackCookie = new BasicClientCookie("PBack", "0");
        pBackCookie.setPath("/");
        pBackCookie.setDomain(httpClientAdapter.getHost());
        httpClient.addCookie(pBackCookie);

        ResponseWrapper resultRequest = httpClient.executeFollowRedirect(logonMethod);

        // test form based authentication
        checkFormLoginQueryString(resultRequest);

        // workaround for post logon script redirect
        if (!isAuthenticated(resultRequest)) {
            // try to get new method from script based redirection
            logonMethod = buildLogonMethod(httpClient, resultRequest);

            if (logonMethod != null) {
                if (otpPreAuthFound && otpPreAuthRetries < MAX_OTP_RETRIES) {
                    // A OTP pre-auth page has been found, it is needed to restart the login process.
                    // This applies to both the case the user entered a good OTP code (the usual login process
                    // takes place) and the case the user entered a wrong OTP code (another code will be asked to him).
                    // The user has up to MAX_OTP_RETRIES chances to input a valid OTP key.
                    return postLogonMethod(httpClient, logonMethod, password);
                }

                // if logonMethod is not null, try to follow redirection
                resultRequest = httpClient.executeFollowRedirect(logonMethod);

                checkFormLoginQueryString(resultRequest);
                // also check cookies
                if (!isAuthenticated(resultRequest)) {
                    throwAuthenticationFailed();
                }
            } else {
                // authentication failed
                throwAuthenticationFailed();
            }
        }

        // check for language selection form
        if ("/owa/languageselection.aspx".equals(resultRequest.getURI().getPath())) {
            // need to submit form
            resultRequest = submitLanguageSelectionForm(resultRequest.getURI(), resultRequest.getResponseBodyAsString());
        }
        return resultRequest;
    }
 
Example 19
Source File: AbstractResourceHttpUtils.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
public void addAuthenticationCookie(String authToken) {
  BasicClientCookie cookie = new BasicClientCookie("te_auth", authToken);
  cookie.setDomain(resourceHttpHost.getHostName());
  cookie.setPath("/");
  addCookie(cookie);
}
 
Example 20
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testTokenConcurrentRefresh() {
    RealmResource demoRealm = adminClient.realm("demo");
    RealmRepresentation demo = demoRealm.toRepresentation();

    demo.setAccessTokenLifespan(2);
    demo.setRevokeRefreshToken(true);
    demo.setRefreshTokenMaxReuse(0);

    demoRealm.update(demo);

    // Login
    tokenRefreshPage.navigateTo();
    assertTrue(testRealmLoginPage.form().isUsernamePresent());
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("[email protected]", "password");
    assertCurrentUrlEquals(tokenRefreshPage);

    setAdapterAndServerTimeOffset(5, tokenRefreshPage.toString());

    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie jsessionid = new BasicClientCookie("JSESSIONID", driver.manage().getCookieNamed("JSESSIONID").getValue());

    jsessionid.setDomain("localhost");
    jsessionid.setPath("/");
    cookieStore.addCookie(jsessionid);

    ExecutorService executor = Executors.newWorkStealingPool();
    CompletableFuture future = CompletableFuture.completedFuture(null);

    try {
        for (int i = 0; i < 5; i++) {
            future = CompletableFuture.allOf(future, CompletableFuture.runAsync(() -> {
                try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore)
                        .build()) {
                    HttpUriRequest request = new HttpGet(tokenRefreshPage.getInjectedUrl().toString());
                    try (CloseableHttpResponse httpResponse = client.execute(request)) {
                        assertTrue("Token not refreshed", EntityUtils.toString(httpResponse.getEntity()).contains("accessToken"));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }, executor));
        }
        
        future.join();
    } finally {
        executor.shutdownNow();
    }

    // Revert times
    setAdapterAndServerTimeOffset(0, tokenRefreshPage.toString());
}