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

The following examples show how to use org.apache.http.impl.cookie.BasicClientCookie#setDomain() . 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: AsyncHttpClient.java    From letv with Apache License 2.0 6 votes vote down vote up
public static CookieStore getuCookie() {
    CookieStore uCookie = new BasicCookieStore();
    try {
        String COOKIE_S_LINKDATA = LemallPlatform.getInstance().getCookieLinkdata();
        if (!TextUtils.isEmpty(COOKIE_S_LINKDATA)) {
            String[] cookies = COOKIE_S_LINKDATA.split("&");
            for (String item : cookies) {
                String[] keyValue = item.split(SearchCriteria.EQ);
                if (keyValue.length == 2) {
                    if (OtherUtil.isContainsChinese(keyValue[1])) {
                        keyValue[1] = URLEncoder.encode(keyValue[1], "UTF-8");
                    }
                    BasicClientCookie cookie = new BasicClientCookie(keyValue[0], keyValue[1]);
                    cookie.setVersion(0);
                    cookie.setDomain(".lemall.com");
                    cookie.setPath("/");
                    uCookie.addCookie(cookie);
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return uCookie;
}
 
Example 2
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 3
Source File: CookieConverter.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
/**
 * Converts Selenium cookie to Apache http client.
 * @param browserCookie selenium cookie.
 * @return http client format.
 */
protected ClientCookie convertCookie(Cookie browserCookie) {
    BasicClientCookie cookie = new BasicClientCookie(browserCookie.getName(), browserCookie.getValue());
    String domain = browserCookie.getDomain();
    if (domain != null && domain.startsWith(".")) {
        // http client does not like domains starting with '.', it always removes it when it receives them
        domain = domain.substring(1);
    }
    cookie.setDomain(domain);
    cookie.setPath(browserCookie.getPath());
    cookie.setExpiryDate(browserCookie.getExpiry());
    cookie.setSecure(browserCookie.isSecure());
    if (browserCookie.isHttpOnly()) {
        cookie.setAttribute("httponly", "");
    }
    return cookie;
}
 
Example 4
Source File: PreferencesCookieStore.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 5
Source File: CookiesPathTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleCookies() throws IOException {
    String requestURI = OAuthClient.AUTH_SERVER_ROOT + "/realms/foo/account";
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, 1);

    // create old cookie with wrong path
    BasicClientCookie wrongCookie = new BasicClientCookie(AuthenticationSessionManager.AUTH_SESSION_ID, AUTH_SESSION_VALUE);
    wrongCookie.setDomain(AUTH_SERVER_HOST);
    wrongCookie.setPath(OLD_COOKIE_PATH);
    wrongCookie.setExpiryDate(calendar.getTime());

    // obtain new cookies
    CookieStore cookieStore = getCorrectCookies(requestURI);
    cookieStore.addCookie(wrongCookie);

    Assert.assertThat(cookieStore.getCookies(), Matchers.hasSize(3));

    login(requestURI, cookieStore);

    // old cookie has been removed
    // now we have AUTH_SESSION_ID, KEYCLOAK_IDENTITY, KEYCLOAK_SESSION
    Assert.assertThat(cookieStore.getCookies().stream().map(org.apache.http.cookie.Cookie::getName).collect(Collectors.toList()), 
            Matchers.hasItems("AUTH_SESSION_ID", "KEYCLOAK_IDENTITY", "KEYCLOAK_SESSION"));

    // does each cookie's path end with "/"
    cookieStore.getCookies().stream().filter(c -> !"OAuth_Token_Request_State".equals(c.getName())).map(org.apache.http.cookie.Cookie::getPath).forEach(path ->Assert.assertThat(path, Matchers.endsWith("/")));

    // KEYCLOAK_SESSION should end by AUTH_SESSION_ID value
    String authSessionId = cookieStore.getCookies().stream().filter(c -> "AUTH_SESSION_ID".equals(c.getName())).findFirst().get().getValue();
    String KCSessionId = cookieStore.getCookies().stream().filter(c -> "KEYCLOAK_SESSION".equals(c.getName())).findFirst().get().getValue();
    String KCSessionSuffix = KCSessionId.split("/")[2];
    Assert.assertThat(authSessionId, Matchers.containsString(KCSessionSuffix));
}
 
Example 6
Source File: HttpClientCookieLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    instance = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

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

    response = instance.execute(request);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
 
Example 7
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 8
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 9
Source File: SolrPortAwareCookieSpecTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testDomainValidate1() throws Exception {
  final BasicClientCookie cookie = new BasicClientCookie("name", "value");
  final CookieOrigin origin = new CookieOrigin("somehost", 80, "/", false);
  final CookieAttributeHandler h = new SolrPortAwareCookieSpecFactory.PortAwareDomainHandler();

  cookie.setDomain("somehost");
  h.validate(cookie, origin);

  cookie.setDomain("otherhost");
  SolrTestCaseJ4.expectThrows(MalformedCookieException.class, () ->  h.validate(cookie, origin));
}
 
Example 10
Source File: SerializableCookie.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private void readObject(ObjectInputStream objectinputstream)
{
    b = new BasicClientCookie((String)objectinputstream.readObject(), (String)objectinputstream.readObject());
    b.setComment((String)objectinputstream.readObject());
    b.setDomain((String)objectinputstream.readObject());
    b.setExpiryDate((Date)objectinputstream.readObject());
    b.setPath((String)objectinputstream.readObject());
    b.setVersion(objectinputstream.readInt());
    b.setSecure(objectinputstream.readBoolean());
}
 
Example 11
Source File: SolrPortAwareCookieSpecTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testDomainMatch2() throws Exception {
  final BasicClientCookie cookie = new BasicClientCookie("name", "value");
  final CookieOrigin origin = new CookieOrigin("www.whatever.somedomain.com", 80, "/", false);
  final CookieAttributeHandler h = new SolrPortAwareCookieSpecFactory.PortAwareDomainHandler();

  cookie.setDomain(".somedomain.com");
  Assert.assertTrue(h.match(cookie, origin));
}
 
Example 12
Source File: SolrPortAwareCookieSpecTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testDomainHostPortValidate() throws Exception {
  final BasicClientCookie cookie = new BasicClientCookie("name", "value");
  final CookieOrigin origin = new CookieOrigin("somehost", 80, "/", false);
  final CookieAttributeHandler h = new SolrPortAwareCookieSpecFactory.PortAwareDomainHandler();

  cookie.setDomain("somehost:80");
  h.validate(cookie, origin);

  cookie.setDomain("somehost:1234");
  SolrTestCaseJ4.expectThrows(MalformedCookieException.class, () -> h.validate(cookie, origin));
}
 
Example 13
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 5 votes vote down vote up
/**
 *  It configures the cookie domain with the domain of the Apache CloudStack that is being accessed.
 *  The domain is extracted from {@link #url} variable.
 */
protected void configureDomainForCookie(BasicClientCookie cookie) {
    try {
        HttpHost httpHost = URIUtils.extractHost(new URI(url));
        String domain = httpHost.getHostName();
        cookie.setDomain(domain);
    } catch (URISyntaxException e) {
        throw new ApacheCloudStackClientRuntimeException(e);
    }
}
 
Example 14
Source File: SerializableCookie.java    From bither-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: 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 16
Source File: HcDownloader.java    From SeimiCrawler with Apache License 2.0 5 votes vote down vote up
@Override
public void addCookies(String url, List<SeimiCookie> seimiCookies) {
    if (seimiCookies==null||seimiCookies.size()<=0){
        return;
    }
    CookieStore cookieStore = crawlerModel.getCookieStore();
    for (SeimiCookie seimiCookie:seimiCookies){
        BasicClientCookie cookie = new BasicClientCookie(seimiCookie.getName(), seimiCookie.getValue());
        cookie.setPath(StringUtils.isNotBlank(seimiCookie.getPath())?seimiCookie.getPath():"/");
        cookie.setDomain(StringUtils.isNotBlank(seimiCookie.getDomain())?seimiCookie.getDomain():StrFormatUtil.getDodmain(url));
        cookieStore.addCookie(cookie);
    }
}
 
Example 17
Source File: MoveToAdapter.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * Send a moveTo call to a remote machine
 * 
 * @param place the four-tuple of the place we are heading to
 * @param agent the MobileAgent that is moving
 * @return status of operation including body if successful
 */
public EmissaryResponse outboundMoveTo(final String place, final IMobileAgent agent) {

    String url = null;

    // Move to actions can be load-balanced out to
    // a virtual IP address:port if so configured
    if (VIRTUAL_MOVETO_ADDR != null) {
        url = VIRTUAL_MOVETO_PROTOCOL + "://" + VIRTUAL_MOVETO_ADDR + "/";
    } else {
        url = KeyManipulator.getServiceHostURL(place);
    }
    url += CONTEXT + "/MoveTo.action";

    final HttpPost method = new HttpPost(url);
    method.setHeader("Content-type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
    final List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    nvps.add(new BasicNameValuePair(PLACE_NAME, place));
    nvps.add(new BasicNameValuePair(MOVE_ERROR_COUNT, Integer.toString(agent.getMoveErrorCount())));

    final DirectoryEntry[] iq = agent.getItineraryQueueItems();
    for (int j = 0; j < iq.length; j++) {
        nvps.add(new BasicNameValuePair(ITINERARY_ITEM, iq[j].getKey()));
    }

    try {
        // This is an 8859_1 String
        final String agentData = PayloadUtil.serializeToString(agent.getPayloadForTransport());
        nvps.add(new BasicNameValuePair(AGENT_SERIAL, agentData));
    } catch (IOException iox) {
        // TODO This will probably need looked at when redoing the moveTo
        logger.error("Cannot serialize agent data", iox);
        BasicHttpResponse response =
                new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Cannot serialize agent data");
        response.setEntity(EntityBuilder.create().setText("").setContentEncoding(MediaType.TEXT_PLAIN).build());
        return new EmissaryResponse(response);
    }

    method.setEntity(new UrlEncodedFormEntity(nvps, Charset.forName("8859_1")));

    // Add a cookie to the outbound header if we are posting
    // to the virtual IP for load balancing
    if (VIRTUAL_MOVETO_ADDR != null) {
        final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, KeyManipulator.getServiceClassname(place));
        cookie.setDomain(VIRTUAL_MOVETO_ADDR.substring(0, VIRTUAL_MOVETO_ADDR.indexOf(":")));
        cookie.setPath(COOKIE_PATH);
        return send(method, cookie);
    }
    return send(method);
}
 
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: 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;
}