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

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

Introduction

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

Prototype

boolean isPersistent();

Source Link

Document

Returns false if the cookie should be discarded at the end of the "session"; true otherwise.

Usage

From source file:com.nineash.hutsync.client.NetworkUtilities.java

/**
 * Connects to the SampleSync test server, authenticates the provided
 * username and password./*from   w w w .j a va  2s.c  o m*/
 *
 * @param username The server account username
 * @param password The server account password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String password, Context context) {
    try {
        final HttpResponse resp;
        final HttpResponse init_resp;
        final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        DefaultHttpClient hClient = getHttpClient(context);
        final HttpPost init_post = new HttpPost(BASE_URL);
        final int first_cookies;
        final ArrayList<SerializableCookie> saveCooks = new ArrayList<SerializableCookie>();
        BasicCookieStore bcs = new BasicCookieStore();

        params.add(new BasicNameValuePair(PARAM_USERNAME, username));
        params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
        params.add(new BasicNameValuePair(PARAM_REMEMBER, "yes"));

        init_resp = hClient.execute(init_post);
        String respString = EntityUtils.toString(init_resp.getEntity());

        List<Cookie> cookies = hClient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            Log.e(TAG, "No cookies gathered first time round");
        }
        first_cookies = cookies.size();
        if (first_cookies != 2) {
            Log.e(TAG, "Should be two cookie to start off with");
        }

        Document doc = Jsoup.parse(respString);
        Elements hiddens = doc.select("div.homepage input[type=hidden]");

        for (Element hidden : hiddens) {
            params.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value")));
        }

        final HttpEntity entity;
        try {
            entity = new UrlEncodedFormEntity(params);
        } catch (final UnsupportedEncodingException e) {
            // this should never happen.
            throw new IllegalStateException(e);
        }
        Log.i(TAG, "Authenticating to: " + AUTH_URI);
        final HttpPost post = new HttpPost(AUTH_URI);
        post.addHeader(entity.getContentType());
        post.setEntity(entity);
        resp = hClient.execute(post);
        String authToken = null;
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //set authtoken here

            cookies = hClient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                Log.e(TAG, "No cookies gathered");
            } else {
                if (cookies.size() == first_cookies + 2) { //we get two new cookies when we log in
                    for (int i = 0; i < cookies.size(); i++) {
                        Cookie cur_cookie = cookies.get(i);
                        if (cur_cookie.isPersistent()) {
                            saveCooks.add(new SerializableCookie(cur_cookie));
                        }
                    }
                    authToken = toString(saveCooks);
                }
            }

        }
        if ((authToken != null) && (authToken.length() > 0)) {
            Log.v(TAG, "Successful authentication");
            return authToken;
        } else {
            Log.e(TAG, "Error authenticating" + resp.getStatusLine());
            return null;
        }
    } catch (final IOException e) {
        Log.e(TAG, "IOException when getting authtoken", e);
        return null;
    } finally {
        Log.v(TAG, "getAuthtoken completing");
    }
}

From source file:org.geometerplus.zlibrary.ui.android.network.SQLiteCookieDatabase.java

@Override
protected void saveCookies(List<Cookie> cookies) {
    for (Cookie c : cookies) {
        if (!c.isPersistent()) {
            continue;
        }/* w  w w . j  av a 2  s . c  om*/
        SQLiteUtil.bindString(myInsertStatement, 1, c.getDomain());
        SQLiteUtil.bindString(myInsertStatement, 2, c.getPath());
        SQLiteUtil.bindString(myInsertStatement, 3, c.getName());
        SQLiteUtil.bindString(myInsertStatement, 4, c.getValue());
        SQLiteUtil.bindDate(myInsertStatement, 5, c.getExpiryDate());
        myInsertStatement.bindLong(6, c.isSecure() ? 1 : 0);
        final long id = myInsertStatement.executeInsert();
        myDeletePortsStatement.bindLong(1, id);
        myDeletePortsStatement.execute();
        if (c.getPorts() != null) {
            myInsertPortsStatement.bindLong(1, id);
            for (int port : c.getPorts()) {
                myInsertPortsStatement.bindLong(2, port);
                myInsertPortsStatement.execute();
            }
        }
    }
}

From source file:cn.com.loopj.android.http.PersistentCookieStore.java

@Override
public void addCookie(Cookie cookie) {
    if (omitNonPersistentCookies && !cookie.isPersistent())
        return;/*from  ww  w . j av  a  2 s  .  c o m*/
    String name = cookie.getName() + cookie.getDomain();

    // Save cookie into local store, or remove if expired
    if (!cookie.isExpired(new Date())) {
        cookies.put(name, cookie);
    } else {
        cookies.remove(name);
    }

    // Save cookie into persistent store
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
    prefsWriter.commit();
}

From source file:gr.ellak.ma.emergencyroad.PersistentCookieStore.java

@Override
public void addCookie(Cookie cookie) {
    if (omitNonPersistentCookies && !cookie.isPersistent())
        return;//w  ww.j av a  2  s.  c o m
    String name = cookie.getName() + cookie.getDomain();

    // Save cookie into local store, or remove if expired
    if (!cookie.isExpired(new Date())) {
        cookies.put(name, cookie);
    } else {
        cookies.remove(name);
    }

    // Save cookie into persistent store
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
    prefsWriter.apply();
}

From source file:com.android.yijiang.kzx.http.PersistentCookieStore.java

@Override
public void addCookie(Cookie cookie) {
    if (omitNonPersistentCookies && !cookie.isPersistent())
        return;// w  ww.  java  2  s  .  c o m
    //        String name = cookie.getName() + cookie.getDomain();
    String name = cookie.getName();
    // Save cookie into local store, or remove if expired
    if (!cookie.isExpired(new Date())) {
        cookies.put(name, cookie);
    } else {
        cookies.remove(name);
    }

    // Save cookie into persistent store
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
    prefsWriter.commit();
}

From source file:com.couchbase.lite.support.PersistentCookieStore.java

@Override
public void addCookie(Cookie cookie) {

    if (omitNonPersistentCookies && !cookie.isPersistent())
        return;/*from   ww  w  .  ja va 2  s . c  o m*/
    String name = cookie.getName() + cookie.getDomain();

    // Do we already have this cookie?  If so, don't bother.
    if (cookies.containsKey(name) && cookies.get(name).equals(cookie)) {
        return;
    }

    // Save cookie into local store, or remove if expired
    if (!cookie.isExpired(new Date())) {
        cookies.put(name, cookie);
    } else {
        cookies.remove(name);
    }

    String encodedCookie = encodeCookie(new SerializableCookie(cookie));
    Map<String, Object> cookiesDoc = getDb().getExistingLocalDocument(COOKIE_LOCAL_DOC_NAME);
    if (cookiesDoc == null) {
        cookiesDoc = new HashMap<String, Object>();
    }

    Log.v(Log.TAG_SYNC, "Saving cookie: %s w/ encoded value: %s", name, encodedCookie);

    cookiesDoc.put(name, encodedCookie);

    try {
        getDb().putLocalDocument(COOKIE_LOCAL_DOC_NAME, cookiesDoc);
    } catch (CouchbaseLiteException e) {
        Log.e(Log.TAG_SYNC, "Exception saving local doc", e);
        throw new RuntimeException(e);
    }

}

From source file:com.blazeroni.reddit.http.PersistentCookieStore.java

@Override
public void addCookie(Cookie cookie) {
    String name = cookie.getName();

    Date expiryDate = cookie.getExpiryDate();
    if (Log.DEBUG) {
        Log.debug("cookie value: " + cookie.getValue());
        Log.debug("Expiry date: " + (expiryDate == null ? "no expiry date" : expiryDate.toLocaleString()));
        Log.debug("persistent: " + cookie.isPersistent());
        Log.debug("Cookie class: " + cookie.getClass().getCanonicalName());
    }//from   w  w  w .java2 s .  c  o m

    // Save cookie into local store
    this.cookies.put(name, cookie);

    // Save cookie into persistent store
    SharedPreferences.Editor prefsWriter = this.cookiePrefs.edit();
    prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", this.cookies.keySet()));
    prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
    prefsWriter.commit();

}

From source file:org.jboss.as.test.integration.web.cookie.CookieUnitTestCase.java

@Test
public void testCookieRetrievedCorrectly() throws Exception {
    log.info("testCookieRetrievedCorrectly()");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieServlet"));

    // assert that we are able to hit servlet successfully
    int postStatusCode = response.getStatusLine().getStatusCode();
    Header[] postErrorHeaders = response.getHeaders("X-Exception");
    assertTrue("Wrong response code: " + postStatusCode, postStatusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-Exception(" + Arrays.toString(postErrorHeaders) + ") is null", postErrorHeaders.length == 0);

    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    assertTrue("Sever did not set expired cookie on client", checkNoExpiredCookie(cookies));

    for (Cookie cookie : cookies) {
        log.info("Cookie : " + cookie);
        String cookieName = cookie.getName();
        String cookieValue = cookie.getValue();

        if (cookieName.equals("simpleCookie")) {
            assertTrue("cookie value should be jboss", cookieValue.equals("jboss"));
            assertEquals("cookie path", "/jbosstest-cookie", cookie.getPath());
            assertEquals("cookie persistence", false, cookie.isPersistent());
        } else if (cookieName.equals("withSpace")) {
            assertEquals("should be no quote in cookie with space", cookieValue.indexOf("\""), -1);
        } else if (cookieName.equals("comment")) {
            log.info("comment in cookie: " + cookie.getComment());
            // RFC2109:Note that there is no Comment attribute in the Cookie request header
            // corresponding to the one in the Set-Cookie response header. The user
            // agent does not return the comment information to the origin server.

            assertTrue(cookie.getComment() == null);
        } else if (cookieName.equals("withComma")) {
            assertTrue("should contain a comma", cookieValue.indexOf(",") != -1);
        } else if (cookieName.equals("expireIn10Sec")) {
            Date now = new Date();
            log.info("will sleep for 5 seconds to see if cookie expires");
            assertTrue("cookies should not be expired by now",
                    !cookie.isExpired(new Date(now.getTime() + fiveSeconds)));
            log.info("will sleep for 5 more secs and it should expire");
            assertTrue("cookies should be expired by now",
                    cookie.isExpired(new Date(now.getTime() + 2 * fiveSeconds)));
        }// w  ww .  j  a v  a2s.c om
    }
}

From source file:com.intuit.karate.http.apache.ApacheHttpClient.java

@Override
protected HttpResponse makeHttpRequest(HttpEntity entity, long startTime) {
    if (entity != null) {
        requestBuilder.setEntity(entity);
        requestBuilder.setHeader(entity.getContentType());
    }//from w  ww.  jav a 2s . co m
    HttpUriRequest httpRequest = requestBuilder.build();
    CloseableHttpClient client = clientBuilder.build();
    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute(URI_CONTEXT_KEY, getRequestUri());
    CloseableHttpResponse httpResponse;
    byte[] bytes;
    try {
        httpResponse = client.execute(httpRequest, context);
        HttpEntity responseEntity = httpResponse.getEntity();
        InputStream is = responseEntity.getContent();
        bytes = IOUtils.toByteArray(is);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    long responseTime = getResponseTime(startTime);
    HttpResponse response = new HttpResponse();
    response.setTime(responseTime);
    response.setUri(getRequestUri());
    response.setBody(bytes);
    response.setStatus(httpResponse.getStatusLine().getStatusCode());
    for (Cookie c : cookieStore.getCookies()) {
        com.intuit.karate.http.Cookie cookie = new com.intuit.karate.http.Cookie(c.getName(), c.getValue());
        cookie.put(DOMAIN, c.getDomain());
        cookie.put(PATH, c.getPath());
        if (c.getExpiryDate() != null) {
            cookie.put(EXPIRES, c.getExpiryDate().getTime() + "");
        }
        cookie.put(PERSISTENT, c.isPersistent() + "");
        cookie.put(SECURE, c.isSecure() + "");
        response.addCookie(cookie);
    }
    for (Header header : httpResponse.getAllHeaders()) {
        response.addHeader(header.getName(), header.getValue());
    }
    return response;
}

From source file:com.ruuhkis.cookies.CookieSQLSource.java

/**
 * Updates cookie if it already exists else adds new cookie tot the table
 * @param cookie//from   www . java2  s . co m
 */

public void addCookie(Cookie cookie) {
    long cookieId = -1;

    Cursor cursor = db.query(CookieSQLHelper.COOKIE_TABLE_NAME, null, CookieSQLHelper.COLUMN_NAME + "=?",
            new String[] { cookie.getName() }, null, null, null);

    ContentValues cookieValues = new ContentValues();
    cookieValues.put(CookieSQLHelper.COLUMN_COMMENT, cookie.getComment());
    cookieValues.put(CookieSQLHelper.COLUMN_COMMENT_URL, cookie.getCommentURL());
    cookieValues.put(CookieSQLHelper.COLUMN_DOMAIN, cookie.getDomain());
    Date date = cookie.getExpiryDate();
    cookieValues.put(CookieSQLHelper.COLUMN_EXPIRY_DATE, date != null ? date.getTime() : -1);
    cookieValues.put(CookieSQLHelper.COLUMN_NAME, cookie.getName());
    cookieValues.put(CookieSQLHelper.COLUMN_PATH, cookie.getPath());

    cookieValues.put(CookieSQLHelper.COLUMN_PERSISTENT, cookie.isPersistent() ? 1 : 0);
    cookieValues.put(CookieSQLHelper.COLUMN_SECURE, cookie.isSecure() ? 1 : 0);
    cookieValues.put(CookieSQLHelper.COLUMN_VALUE, cookie.getValue());
    cookieValues.put(CookieSQLHelper.COLUMN_VERSION, cookie.getVersion());

    if (cursor.moveToFirst()) {
        cookieId = cursor.getLong(cursor.getColumnIndex(CookieSQLHelper.COLUMN_COOKIE_ID));
        db.update(CookieSQLHelper.COOKIE_TABLE_NAME, cookieValues, CookieSQLHelper.COLUMN_ID + "=?",
                new String[] { Long.toString(cookieId) });
        db.delete(CookieSQLHelper.PORT_TABLE_NAME, CookieSQLHelper.COLUMN_COOKIE_ID + "=?",
                new String[] { Long.toString(cookieId) });
    } else {
        cookieId = db.insert(CookieSQLHelper.COOKIE_TABLE_NAME, null, cookieValues);
    }

    if (cookieId != -1) {

        int[] ports = cookie.getPorts();
        if (ports != null) {
            for (int i = 0; i < ports.length; i++) {
                ContentValues portValues = new ContentValues();
                portValues.put(CookieSQLHelper.COLUMN_COOKIE_ID, cookieId);
                portValues.put(CookieSQLHelper.COLUMN_PORT, ports[i]);
                db.insert(CookieSQLHelper.PORT_TABLE_NAME, null, portValues);
            }
        }
    } else {
        Log.e(TAG, "id = -1");
    }
    cursor.close();
}