Example usage for org.apache.http.client.protocol ClientContext COOKIE_STORE

List of usage examples for org.apache.http.client.protocol ClientContext COOKIE_STORE

Introduction

In this page you can find the example usage for org.apache.http.client.protocol ClientContext COOKIE_STORE.

Prototype

String COOKIE_STORE

To view the source code for org.apache.http.client.protocol ClientContext COOKIE_STORE.

Click Source Link

Document

Attribute name of a org.apache.http.client.CookieStore object that represents the actual cookie store.

Usage

From source file:org.lol.reddit.cache.CacheDownload.java

private void performDownload(final HttpClient httpClient, final HttpRequestBase httpRequest) {

    if (mInitiator.isJson)
        httpRequest.setHeader("Accept-Encoding", "gzip");

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, mInitiator.getCookies());

    final HttpResponse response;
    final StatusLine status;

    try {/* w  w  w  .ja  v a2 s.c o  m*/
        if (mCancelled) {
            mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled");
            return;
        }
        response = httpClient.execute(httpRequest, localContext);
        status = response.getStatusLine();

    } catch (Throwable t) {

        if (t.getCause() != null && t.getCause() instanceof RedirectException
                && httpRequest.getURI().getHost().endsWith("reddit.com")) {

            mInitiator.notifyFailure(RequestFailureType.REDDIT_REDIRECT, t, null,
                    "Unable to open a connection");
        } else {
            mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "Unable to open a connection");
        }
        return;
    }

    if (status.getStatusCode() != 200) {
        mInitiator.notifyFailure(RequestFailureType.REQUEST, null, status,
                String.format("HTTP error %d (%s)", status.getStatusCode(), status.getReasonPhrase()));
        return;
    }

    if (mCancelled) {
        mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled");
        return;
    }

    final HttpEntity entity = response.getEntity();

    if (entity == null) {
        mInitiator.notifyFailure(RequestFailureType.CONNECTION, null, status,
                "Did not receive a valid HTTP response");
        return;
    }

    final InputStream is;

    final String mimetype;
    try {
        is = entity.getContent();
        mimetype = entity.getContentType() == null ? null : entity.getContentType().getValue();
    } catch (Throwable t) {
        t.printStackTrace();
        mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, status, "Could not open an input stream");
        return;
    }

    final NotifyOutputStream cacheOs;
    final CacheManager.WritableCacheFile cacheFile;
    if (mInitiator.cache) {
        try {
            cacheFile = manager.openNewCacheFile(mInitiator, session, mimetype);
            cacheOs = cacheFile.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Could not access the local cache");
            return;
        }
    } else {
        cacheOs = null;
        cacheFile = null;
    }

    final long contentLength = entity.getContentLength();

    if (mInitiator.isJson) {

        final InputStream bis;

        if (mInitiator.cache) {

            bis = new BufferedInputStream(
                    new CachingInputStream(is, cacheOs, new CachingInputStream.BytesReadListener() {
                        public void onBytesRead(final long total) {
                            mInitiator.notifyProgress(total, contentLength);
                        }
                    }), 8 * 1024);

        } else {
            bis = new BufferedInputStream(is, 8 * 1024);
        }

        final JsonValue value;

        try {
            value = new JsonValue(bis);

            synchronized (this) {
                mInitiator.notifyJsonParseStarted(value, RRTime.utcCurrentTimeMillis(), session, false);
            }

            value.buildInThisThread();

        } catch (Throwable t) {
            t.printStackTrace();
            mInitiator.notifyFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream");
            return;
        }

        if (mInitiator.cache && cacheFile != null) {
            try {
                mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(),
                        session, false, mimetype);
            } catch (IOException e) {
                if (e.getMessage().contains("ENOSPC")) {
                    mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space");
                } else {
                    mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found");
                }
            }
        }

    } else {

        if (!mInitiator.cache) {
            BugReportActivity.handleGlobalError(mInitiator.context, "Cache disabled for non-JSON request");
            return;
        }

        try {
            final byte[] buf = new byte[8 * 1024];

            int bytesRead;
            long totalBytesRead = 0;
            while ((bytesRead = is.read(buf)) > 0) {
                totalBytesRead += bytesRead;
                cacheOs.write(buf, 0, bytesRead);
                mInitiator.notifyProgress(totalBytesRead, contentLength);
            }

            cacheOs.flush();
            cacheOs.close();

            try {
                mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(),
                        session, false, mimetype);
            } catch (IOException e) {
                if (e.getMessage().contains("ENOSPC")) {
                    mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space");
                } else {
                    mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found");
                }
            }

        } catch (IOException e) {

            if (e.getMessage() != null && e.getMessage().contains("ENOSPC")) {
                mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Out of disk space");

            } else {
                e.printStackTrace();
                mInitiator.notifyFailure(RequestFailureType.CONNECTION, e, null,
                        "The connection was interrupted");
            }

        } catch (Throwable t) {
            t.printStackTrace();
            mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "The connection was interrupted");
        }
    }
}

From source file:mixedserver.protocol.jsonrpc.client.HTTPSession.java

public HTTPSession(URI uri) {
    this.uri = uri;
    attributes = new Hashtable();

    cookieStore = new BasicCookieStore();
    localContext = new BasicHttpContext();

    // /* w w  w. j  av a 2 s .  c o  m*/
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:com.vanda.beivandalibnetwork.utils.HttpUtils.java

/**
 * Cookie/*from w  w w  .ja v a2s .  c  om*/
 * 
 * @param setAsCurrentContext
 *            ??true?CURRENT_CONTEXT
 * @return
 */
public static HttpContext cookieContext(boolean setAsCurrentContext) {
    if (getCookieStore(CURRENT_CONTEXT) != null)
        return CURRENT_CONTEXT;

    CookieStore store = new BasicCookieStore();
    HttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.COOKIE_STORE, store);
    if (setAsCurrentContext)
        CURRENT_CONTEXT = context;
    return context;
}

From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java

/**
 * The method to publish API to external WSO2 Store
 * @param api      API/*  w w  w.j  av  a  2 s . co m*/
 * @param store    Store
 * @return   published/not
 */

public boolean publishToStore(API api, APIStore store) throws APIManagementException {
    boolean published = false;

    if (store.getEndpoint() == null || store.getUsername() == null || store.getPassword() == null) {
        String msg = "External APIStore endpoint URL or credentials are not defined. "
                + "Cannot proceed with publishing API to the APIStore - " + store.getDisplayName();
        throw new APIManagementException(msg);
    } else {
        CookieStore cookieStore = new BasicCookieStore();
        HttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        boolean authenticated = authenticateAPIM(store, httpContext);
        if (authenticated) { //First try to login to store
            boolean added = addAPIToStore(api, store.getEndpoint(), store.getUsername(), httpContext,
                    store.getDisplayName());
            if (added) { //If API creation success,then try publishing the API
                published = publishAPIToStore(api.getId(), store.getEndpoint(), store.getUsername(),
                        httpContext, store.getDisplayName());
            }
            logoutFromExternalStore(store, httpContext);
        }
    }
    return published;
}

From source file:org.ovirt.engine.sdk.web.HttpProxy.java

/**
 * Generates peer hit context//from   w  ww  .j  a  va 2s .c om
 * 
 * @return {@link BasicHttpContext}
 */
private BasicHttpContext getContext() {
    BasicHttpContext context = new BasicHttpContext();
    if (this.persistentAuth && StringUtils.isNulOrEmpty(this.sessionid)) {
        context.setAttribute(ClientContext.COOKIE_STORE, this.pool.getCookieStore());
    }
    return context;
}

From source file:de.stkl.gbgvertretungsplan.sync.SyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from  w w  w  . j a v a 2 s .c  om*/
    //android.os.Debug.waitForDebugger();
    reportStatus(Sync.SYNC_STATUS.START);

    String username = account.name;
    String password = mAccountManager.getPassword(account);

    AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null);

    CookieStore cookies = new BasicCookieStore();
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookies);

    boolean error = false;

    try {
        String dataTypeS = mAccountManager.getUserData(account,
                de.stkl.gbgvertretungsplan.values.Account.PROP_TYPE);
        int dataType = dataTypeS == null ? 0 : Integer.valueOf(dataTypeS);

        if (!mComInterface.login(httpClient, localContext, username, password, dataType))
            throw new LoginException();

        // 4. request and save pages (today + tomorrow)
        requestAndSaveDay(httpClient, localContext, 0, dataType); // today
        requestAndSaveDay(httpClient, localContext, 1, dataType); // and tomorrow

        if (!logout(httpClient, localContext))
            throw new CommunicationInterface.LogoutException();

    } catch (IOException e) {
        error = true;
    } catch (CommunicationInterface.CommunicationException e) {
        ErrorReporter.reportError(e, mContext);
        error = true;
    } catch (CommunicationInterface.ParsingException e) {
        ErrorReporter.reportError(e, mContext);
        error = true;
    } catch (LoginException e) {
        error = true;
    } catch (CommunicationInterface.LogoutException e) {
        ErrorReporter.reportError(e, mContext);
        error = true;
        // generic exceptions like NullPointerException should also indicate a failed Sync
    } catch (Exception e) {
        error = true;
    } finally {
        if (error)
            reportStatus(Sync.SYNC_STATUS.ERROR);
        else
            reportStatus(Sync.SYNC_STATUS.OK);
        httpClient.close();
    }
}

From source file:com.ryan.ryanreader.account.RedditAccount.java

public static LoginResultPair login(final Context context, final String username, final String password,
        final HttpClient client) {

    // ???/*w  w w.  j  a v  a2s  .com*/
    final ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>(3);
    fields.add(new BasicNameValuePair("user", username));
    fields.add(new BasicNameValuePair("passwd", password));
    fields.add(new BasicNameValuePair("api_type", "json"));

    // TODO put somewhere else
    final HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context));
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO
    // remove
    // hardcoded
    // params,
    // put
    // in
    // network
    // prefs
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100);
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    params.setParameter(ClientPNames.MAX_REDIRECTS, 5);

    final HttpPost request = new HttpPost("https://ssl.reddit.com/api/login");
    request.setParams(params);

    try {
        request.setEntity(new UrlEncodedFormEntity(fields, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
        return new LoginResultPair(LoginResult.INTERNAL_ERROR);
    }

    final PersistentCookieStore cookies = new PersistentCookieStore();

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookies);

    final StatusLine status;
    final HttpEntity entity;
    try {
        final HttpResponse response = client.execute(request, localContext);
        status = response.getStatusLine();
        entity = response.getEntity();

    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    if (status.getStatusCode() != 200) {
        return new LoginResultPair(LoginResult.REQUEST_ERROR);
    }

    final JsonValue result;

    try {
        result = new JsonValue(entity.getContent());
        result.buildInThisThread();
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    final String modhash;

    try {

        // TODO use the more general reddit error finder
        final JsonBufferedArray errors = result.asObject().getObject("json").getArray("errors");
        errors.join();
        if (errors.getCurrentItemCount() != 0) {

            for (final JsonValue v : errors) {
                for (final JsonValue s : v.asArray()) {

                    // TODO handle unknown messages by concatenating all
                    // Reddit's strings

                    if (s.getType() == JsonValue.Type.STRING) {

                        Log.i("RR DEBUG ERROR", s.asString());

                        // lol, reddit api
                        if (s.asString().equalsIgnoreCase("WRONG_PASSWORD")
                                || s.asString().equalsIgnoreCase("invalid password")
                                || s.asString().equalsIgnoreCase("passwd"))
                            return new LoginResultPair(LoginResult.WRONG_PASSWORD);

                        if (s.asString().contains("too much")) // also
                            // "RATELIMIT",
                            // but
                            // that's
                            // not as
                            // descriptive
                            return new LoginResultPair(LoginResult.RATELIMIT, s.asString());
                    }
                }
            }

            return new LoginResultPair(LoginResult.UNKNOWN_REDDIT_ERROR);
        }

        final JsonBufferedObject data = result.asObject().getObject("json").getObject("data");

        modhash = data.getString("modhash");

    } catch (NullPointerException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (InterruptedException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    }

    return new LoginResultPair(LoginResult.SUCCESS, new RedditAccount(username, modhash, cookies, 0), null);
}

From source file:org.wso2.carbon.registry.notes.test.PublisherNotesTestCase.java

@Test(groups = "wso2.greg", description = "Add Schema without name", dependsOnMethods = "createSOAPService")
public void addNoteTestCase() throws Exception {
    String session_id = authenticateJaggeryAPI();
    String endPoint = "https://localhost:10343/publisher/apis/assets?type=note";

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(endPoint);
    post.setHeader("Cookie", "JSESSIONID=" + session_id);
    List nameValuePairs = new ArrayList(5);
    nameValuePairs.add(new BasicNameValuePair("overview_note", "note_one"));
    nameValuePairs.add(new BasicNameValuePair("overview_resourcepath",
            "/_system/governance/trunk/soapservices/4.5.0/SOAPService1"));
    nameValuePairs.add(new BasicNameValuePair("overview_visibility", "public"));
    nameValuePairs.add(new BasicNameValuePair("overview_note", "admin"));
    nameValuePairs.add(new BasicNameValuePair("overview_status", "open"));

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = client.execute(post);
    assertEquals("Created", response.getStatusLine().getReasonPhrase());
}

From source file:org.jspringbot.keyword.http.HTTPHelper.java

public void newSession() {
    LOG.info("Created New HTTP Session.");

    this.context = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    reset();//  w ww  .j a  v a  2 s  . c om
}

From source file:com.farmafene.commons.cas.LoginTGT.java

public void doLogout(Cookie cookie) {
    HttpResponse res = null;// w  w  w .j  a v  a2s  .  c  o m
    HttpClientFactory f = new HttpClientFactory();
    f.setLoginURL(getCasServerURL());
    DefaultHttpClient client = null;
    client = f.getClient();
    HttpContext localContext = new BasicHttpContext();
    BasicCookieStore cs = new BasicCookieStore();
    cs.addCookie(cookie);

    HttpPost post = new HttpPost(getURL("logout"));
    client.setCookieStore(cs);
    localContext.setAttribute(ClientContext.COOKIE_STORE, cs);
    try {
        res = client.execute(post, localContext);
        if (res.getStatusLine().getStatusCode() != 200) {
            AuriusAuthException ex = new AuriusAuthException("Error");
            logger.error("Excepcion en el login", ex);
            throw ex;
        }
    } catch (ClientProtocolException e) {
        AuriusAuthException ex = new AuriusAuthException("ClientProtocolException",
                AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    } catch (IOException e) {
        AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
}