Example usage for org.apache.http.cookie Cookie getValue

List of usage examples for org.apache.http.cookie Cookie getValue

Introduction

In this page you can find the example usage for org.apache.http.cookie Cookie getValue.

Prototype

String getValue();

Source Link

Document

Returns the value.

Usage

From source file:com.normalexception.app.rx8club.html.LoginFactory.java

/**
 * Log in to the forum/*from  w w  w  . j a  v  a  2  s . c om*/
 * @return   True if the login was successful, false if else
 * @throws NoSuchAlgorithmException
 * @throws ClientProtocolException
 * @throws IOException
 */
public boolean login() throws NoSuchAlgorithmException, ClientProtocolException, IOException {
    if (UserProfile.getInstance().getUsername() == null || password == null)
        return false;

    httpclient = getClient();
    HttpPost httpost = ClientUtils.getHttpPost(WebUrls.loginUrl);

    if (!isInitialized)
        initializeClientInformation();

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(
            new BasicNameValuePair(VBulletinKeys.UserName.getValue(), UserProfile.getInstance().getUsername()));
    nvps.add(new BasicNameValuePair(VBulletinKeys.Password.getValue(), this.password));
    nvps.add(new BasicNameValuePair(VBulletinKeys.PasswordUtf.getValue(), this.password));
    nvps.add(new BasicNameValuePair(VBulletinKeys.CookieUser.getValue(), "1"));
    nvps.add(new BasicNameValuePair(VBulletinKeys.Do.getValue(), "login"));

    httpost.setEntity(new UrlEncodedFormEntity(nvps));

    try {
        HttpResponse response = httpclient.execute(httpost, getHttpContext());
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            List<Cookie> cookies = cookieStore.getCookies();
            boolean val = response.getStatusLine().getStatusCode() != HttpStatus.SC_BAD_REQUEST;
            Log.d(TAG, "Login status code: " + response.getStatusLine().getStatusCode());
            //httpost.releaseConnection();

            for (Cookie cookie : cookies)
                if (cookie.getName().equals(VBulletinKeys.CheckLoginStatus.getValue())
                        && cookie.getValue().toLowerCase(Locale.US).equals("yes"))
                    isLoggedIn = true;

            isGuestMode = !isLoggedIn;
            return val && isLoggedIn;
        }
    } catch (Exception e) {
        Log.e(TAG, "HTTP Response based error!", e);
    }

    return false;
}

From source file:com.grendelscan.commons.http.apache_overrides.serializable.SerializableBasicCookie.java

public SerializableBasicCookie(final Cookie cookie) {
    cookieVersion = cookie.getVersion();
    cookieExpiryDate = cookie.getExpiryDate();
    cookiePath = cookie.getPath();/*from  ww w .ja v a  2  s  .c  om*/
    name = cookie.getName();
    value = cookie.getValue();
    cookieComment = cookie.getComment();
    cookieDomain = cookie.getDomain();
    isSecure = cookie.isSecure();
    ports = cookie.getPorts();

    try {
        if (cookie instanceof BasicClientCookie2) {
            BasicClientCookie2 b2c = (BasicClientCookie2) cookie;
            discard = b2c.getClass().getField("discard").getBoolean(b2c);
        }
        if (cookie instanceof BasicClientCookie) {
            BasicClientCookie bCookie = (BasicClientCookie) cookie;
            Field field = bCookie.getClass().getDeclaredField("attribs");
            field.setAccessible(true);
            attribs = (HashMap) field.get(bCookie);
        }
    } catch (Exception e) {
        System.err.println(e.toString());
        e.printStackTrace();
    } finally {
        if (attribs == null) {
            attribs = new HashMap<String, String>();
        }
    }
}

From source file:org.jboss.as.test.integration.web.formauth.FormAuthUnitTestCase.java

/**
 * Test that a bad login is redirected to the errors.jsp and that the
 * session j_exception is not null./*w  w  w .j a va  2  s  .c om*/
 */
@Test
@Ignore
@OperateOnDeployment("form-auth.war")
public void testFormAuthException() throws Exception {
    log.info("+++ testFormAuthException");

    URL url = new URL(baseURLNoAuth + "restricted/SecuredServlet");
    HttpGet httpget = new HttpGet(url.toURI());

    log.info("Executing request " + httpget.getRequestLine());
    HttpResponse response = httpclient.execute(httpget);

    int statusCode = response.getStatusLine().getStatusCode();
    Header[] errorHeaders = response.getHeaders("X-NoJException");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    HttpEntity entity = response.getEntity();
    if ((entity != null) && (entity.getContentLength() > 0)) {
        String body = EntityUtils.toString(entity);
        assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);
    } else {
        fail("Empty body in response");
    }

    String sessionID = null;
    for (Cookie k : httpclient.getCookieStore().getCookies()) {
        if (k.getName().equalsIgnoreCase("JSESSIONID"))
            sessionID = k.getValue();
    }
    log.info("Saw JSESSIONID=" + sessionID);

    // Submit the login form
    HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check");
    formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html");

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("j_username", "baduser"));
    formparams.add(new BasicNameValuePair("j_password", "badpass"));
    formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));

    log.info("Executing request " + formPost.getRequestLine());
    HttpResponse postResponse = httpclient.execute(formPost);

    statusCode = postResponse.getStatusLine().getStatusCode();
    errorHeaders = postResponse.getHeaders("X-NoJException");
    assertTrue("Should see HTTP_OK. Got " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is not null", errorHeaders.length != 0);
    log.debug("Saw X-JException, " + Arrays.toString(errorHeaders));
}

From source file:org.jboss.as.test.integration.web.formauth.FormAuthUnitTestCase.java

public HttpPost doSecureGetWithLogin(String path, String username, String password) throws Exception {
    log.info("+++ doSecureGetWithLogin : " + path);

    URL url = new URL(baseURLNoAuth + path);
    HttpGet httpget = new HttpGet(url.toURI());

    log.info("Executing request " + httpget.getRequestLine());
    HttpResponse response = httpclient.execute(httpget);

    int statusCode = response.getStatusLine().getStatusCode();
    Header[] errorHeaders = response.getHeaders("X-NoJException");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    HttpEntity entity = response.getEntity();
    if ((entity != null) && (entity.getContentLength() > 0)) {
        String body = EntityUtils.toString(entity);
        assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);
    } else {//from w  ww .  j a  v a 2 s . co m
        fail("Empty body in response");
    }

    String sessionID = null;
    for (Cookie k : httpclient.getCookieStore().getCookies()) {
        if (k.getName().equalsIgnoreCase("JSESSIONID"))
            sessionID = k.getValue();
    }
    log.info("Saw JSESSIONID=" + sessionID);

    // Submit the login form
    HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check");
    formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html");

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("j_username", username));
    formparams.add(new BasicNameValuePair("j_password", password));
    formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));

    log.info("Executing request " + formPost.getRequestLine());
    HttpResponse postResponse = httpclient.execute(formPost);

    statusCode = postResponse.getStatusLine().getStatusCode();
    errorHeaders = postResponse.getHeaders("X-NoJException");
    assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode,
            statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
    EntityUtils.consume(postResponse.getEntity());

    // Follow the redirect to the SecureServlet
    Header location = postResponse.getFirstHeader("Location");
    URL indexURI = new URL(location.getValue());
    HttpGet war1Index = new HttpGet(url.toURI());

    log.info("Executing request " + war1Index.getRequestLine());
    HttpResponse war1Response = httpclient.execute(war1Index);

    statusCode = war1Response.getStatusLine().getStatusCode();
    errorHeaders = war1Response.getHeaders("X-NoJException");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    HttpEntity war1Entity = war1Response.getEntity();
    if ((war1Entity != null) && (entity.getContentLength() > 0)) {
        String body = EntityUtils.toString(war1Entity);
        if (body.indexOf("j_security_check") > 0)
            fail("Get of " + indexURI + " redirected to login page");
    } else {
        fail("Empty body in response");
    }

    return formPost;
}

From source file:org.thomnichols.android.gmarks.BookmarksQueryService.java

public void login(String user, String passwd) {
    try {/*from  www.j a v a 2 s.co  m*/
        List<NameValuePair> queryParams = new ArrayList<NameValuePair>();
        queryParams.add(new BasicNameValuePair("service", "bookmarks"));
        queryParams.add(new BasicNameValuePair("passive", "true"));
        queryParams.add(new BasicNameValuePair("nui", "1"));
        queryParams.add(new BasicNameValuePair("continue", "https://www.google.com/bookmarks/l"));
        queryParams.add(new BasicNameValuePair("followup", "https://www.google.com/bookmarks/l"));
        HttpGet get = new HttpGet(
                "https://www.google.com/accounts/ServiceLogin?" + URLEncodedUtils.format(queryParams, "UTF-8"));
        HttpResponse resp = http.execute(get, this.ctx);
        // this just gets the cookie but I can ignore it...

        if (resp.getStatusLine().getStatusCode() != 200)
            throw new RuntimeException(
                    "Invalid status code for ServiceLogin " + resp.getStatusLine().getStatusCode());
        resp.getEntity().consumeContent();

        String galx = null;
        for (Cookie c : cookieStore.getCookies())
            if (c.getName().equals("GALX"))
                galx = c.getValue();

        if (galx == null)
            throw new RuntimeException("GALX cookie not found!");

        HttpPost loginMethod = new HttpPost("https://www.google.com/accounts/ServiceLoginAuth");
        // post parameters:
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("Email", user));
        nvps.add(new BasicNameValuePair("Passwd", passwd));
        nvps.add(new BasicNameValuePair("PersistentCookie", "yes"));
        nvps.add(new BasicNameValuePair("GALX", galx));
        nvps.add(new BasicNameValuePair("continue", "https://www.google.com/bookmarks/l"));
        loginMethod.setEntity(new UrlEncodedFormEntity(nvps));
        resp = http.execute(loginMethod, this.ctx);

        if (resp.getStatusLine().getStatusCode() != 302)
            throw new RuntimeException(
                    "Unexpected status code for ServiceLoginAuth" + resp.getStatusLine().getStatusCode());
        resp.getEntity().consumeContent();

        Header checkCookieLocation = resp.getFirstHeader("Location");
        if (checkCookieLocation == null)
            throw new RuntimeException("Missing checkCookie redirect location!");

        // CheckCookie:
        get = new HttpGet(checkCookieLocation.getValue());
        resp = http.execute(get, this.ctx);

        if (resp.getStatusLine().getStatusCode() != 302)
            throw new RuntimeException(
                    "Unexpected status code for CheckCookie" + resp.getStatusLine().getStatusCode());
        resp.getEntity().consumeContent();

        this.authInitialized = true;
        Log.i(TAG, "Final redirect location: " + resp.getFirstHeader("Location").getValue());
        Log.i(TAG, "Logged in.");
    } catch (IOException ex) {
        Log.e(TAG, "Error during login", ex);
        throw new RuntimeException("IOException during login", ex);
    }
}

From source file:com.revo.deployr.client.core.impl.RClientImpl.java

public RUser login(RAuthentication rAuthentication, boolean disableautosave)
        throws RClientException, RSecurityException {

    RCall rCall = null;//from  ww  w  .  j ava 2s. c  om

    if (rAuthentication instanceof RBasicAuthentication) {

        RBasicAuthentication basic = (RBasicAuthentication) rAuthentication;
        rCall = new LoginCall(basic.getUsername(), basic.getPassword(), disableautosave);
    }

    RCoreResult rResult = processCall(rCall);

    Map<String, String> identity = rResult.getIdentity();
    Map<String, Integer> limits = rResult.getLimits();

    //
    // Store cookie from response header, we no longer return this value in
    // the DeployR response markup as of `8.0.5`
    //
    CookieStore cookieStore = httpClient.getCookieStore();
    Cookie cookie = cookieStore.getCookies().get(0);
    this.httpcookie = (cookie != null ? cookie.getValue() : null);

    //
    // - Store `X-XSRF-TOKEN` from `/r/uer/login` for future authenticated 
    //   requests
    //         
    for (Header header : rResult.getHeaders()) {
        if (header.getName().equals(XSRF_HEADER)) {
            this.csrf = header.getValue();
        }
    }

    RUserDetails userDetails = REntityUtil.getUserDetails(identity, limits, csrf);

    liveContext = new RLiveContext(this, serverurl, httpcookie);

    return new RUserImpl(userDetails, liveContext);
}

From source file:com.machinepublishers.jbrowserdriver.CookieStore.java

/**
 * {@inheritDoc}// ww  w  .j  a  v  a 2 s .c  o  m
 */
@Override
public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
    final String reqHost = canonicalHost(uri.getHost());
    final String reqPath = canonicalPath(uri.getPath());
    final boolean reqSecure = isSecure(uri.getScheme());
    final boolean reqJavascript = isJavascript(uri.getScheme());
    StringBuilder builder = new StringBuilder();
    if (reqJavascript) {
        List<Cookie> list;
        synchronized (store) {
            store.clearExpired(new Date());
            list = store.getCookies();
        }
        for (Cookie cookie : list) {
            if ((!cookie.isSecure() || reqSecure) && reqHost.endsWith(canonicalHost(cookie.getDomain()))
                    && reqPath.startsWith(canonicalPath(cookie.getPath()))) {
                if (builder.length() > 0) {
                    builder.append(';');
                }
                builder.append(cookie.getName());
                builder.append('=');
                builder.append(cookie.getValue());
            }
        }
    }
    String cookies = builder.length() == 0 ? null : builder.toString();
    Map<String, List<String>> map;
    if (cookies != null) {
        map = new HashMap<String, List<String>>();
        map.put("Cookie", Arrays.asList(cookies));
    } else {
        map = Collections.emptyMap();
    }
    return map;
}

From source file:org.jboss.as.test.integration.web.formauth.FormAuthUnitTestCase.java

/**
 * Test that a post from an unsecured form to a secured servlet does not
 * loose its data during the redirct to the form login.
 *///from   w w  w . jav  a2s  . co  m
@Test
@OperateOnDeployment("form-auth.war")
public void testPostDataFormAuth() throws Exception {
    log.info("+++ testPostDataFormAuth");

    URL url = new URL(baseURLNoAuth + "unsecure_form.html");
    HttpGet httpget = new HttpGet(url.toURI());

    log.info("Executing request " + httpget.getRequestLine());
    HttpResponse response = httpclient.execute(httpget);

    int statusCode = response.getStatusLine().getStatusCode();
    Header[] errorHeaders = response.getHeaders("X-NoJException");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
    EntityUtils.consume(response.getEntity());

    // Submit the form to /restricted/SecuredPostServlet
    HttpPost restrictedPost = new HttpPost(baseURLNoAuth + "restricted/SecuredPostServlet");

    List<NameValuePair> restrictedParams = new ArrayList<NameValuePair>();
    restrictedParams.add(new BasicNameValuePair("checkParam", "123456"));
    restrictedPost.setEntity(new UrlEncodedFormEntity(restrictedParams, "UTF-8"));

    log.info("Executing request " + restrictedPost.getRequestLine());
    HttpResponse restrictedResponse = httpclient.execute(restrictedPost);

    statusCode = restrictedResponse.getStatusLine().getStatusCode();
    errorHeaders = restrictedResponse.getHeaders("X-NoJException");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    HttpEntity entity = restrictedResponse.getEntity();
    if ((entity != null) && (entity.getContentLength() > 0)) {
        String body = EntityUtils.toString(entity);
        assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);
    } else {
        fail("Empty body in response");
    }

    String sessionID = null;
    for (Cookie k : httpclient.getCookieStore().getCookies()) {
        if (k.getName().equalsIgnoreCase("JSESSIONID"))
            sessionID = k.getValue();
    }
    log.info("Saw JSESSIONID=" + sessionID);

    // Submit the login form
    HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check");
    formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html");

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("j_username", "user1"));
    formparams.add(new BasicNameValuePair("j_password", "password1"));
    formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));

    log.info("Executing request " + formPost.getRequestLine());
    HttpResponse postResponse = httpclient.execute(formPost);

    statusCode = postResponse.getStatusLine().getStatusCode();
    errorHeaders = postResponse.getHeaders("X-NoJException");
    assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode,
            statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
    EntityUtils.consume(postResponse.getEntity());

    // Follow the redirect to the SecureServlet
    Header location = postResponse.getFirstHeader("Location");
    URL indexURI = new URL(location.getValue());
    HttpGet war1Index = new HttpGet(url.toURI());

    log.info("Executing request " + war1Index.getRequestLine());
    HttpResponse war1Response = httpclient.execute(war1Index);

    statusCode = war1Response.getStatusLine().getStatusCode();
    errorHeaders = war1Response.getHeaders("X-NoJException");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    HttpEntity war1Entity = war1Response.getEntity();
    if ((war1Entity != null) && (entity.getContentLength() > 0)) {
        String body = EntityUtils.toString(war1Entity);
        if (body.indexOf("j_security_check") > 0)
            fail("Get of " + indexURI + " redirected to login page");
    } else {
        fail("Empty body in response");
    }
}

From source file:com.google.sampling.experiential.android.lib.GoogleAccountLoginHelper.java

/**
 * Store a new Paco AppEngine server cookie.
 * This will only be used publicly when the other communications with the Paco server send us
 * back a new cookie instead of the existing cookie. 
 * /*from   w ww . j  a va2  s  .  c o  m*/
 * @param authCookie Cookie from logging into Paco AppEngine instance.
 */
public synchronized void storePacoAuthCookie(Cookie authCookie) {
    Editor editor = authTokenPreferences.edit();
    editor.putString("comment", authCookie.getComment());
    editor.putString("commentURL", authCookie.getCommentURL());
    editor.putString("domain", authCookie.getDomain());
    editor.putString("name", authCookie.getName());
    editor.putString("path", authCookie.getPath());
    editor.putString("value", authCookie.getValue());
    SimpleDateFormat df = new SimpleDateFormat(Constants.DATE_TIME_FORMAT);
    editor.putString("expiration", df.format(authCookie.getExpiryDate()));
    if (authCookie.getPorts() != null) {
        editor.putString("ports", stringify(authCookie.getPorts()));
    }
    editor.putInt("version", authCookie.getVersion());
    editor.commit();
}

From source file:com.radicaldynamic.groupinform.services.InformOnlineService.java

private void serializeSession() {
    // Attempt to serialize the session for later use
    if (Collect.getInstance().getInformOnlineState().getSession() instanceof CookieStore) {
        if (Collect.Log.DEBUG)
            Log.d(Collect.LOGTAG, t + "serializing session");

        try {/*w  w  w  .ja v  a 2 s. c  om*/
            InformOnlineSession session = new InformOnlineSession();

            Iterator<Cookie> cookies = Collect.getInstance().getInformOnlineState().getSession().getCookies()
                    .iterator();

            while (cookies.hasNext()) {
                Cookie c = cookies.next();
                session.getCookies().add(new InformOnlineSession(c.getDomain(), c.getExpiryDate(), c.getName(),
                        c.getPath(), c.getValue(), c.getVersion()));
            }

            FileOutputStream fos = new FileOutputStream(
                    new File(getCacheDir(), FileUtilsExtended.SESSION_CACHE_FILE));
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(session);
            out.close();
            fos.close();
        } catch (Exception e) {
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, t + "problem serializing session " + e.toString());
            e.printStackTrace();

            // Make sure that we don't leave a broken file hanging
            new File(getCacheDir(), FileUtilsExtended.SESSION_CACHE_FILE).delete();
        }
    } else {
        if (Collect.Log.DEBUG)
            Log.d(Collect.LOGTAG, t + "no session to serialize");
    }
}