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:com.adavr.http.Client.java

public CookieStore getCookieStore() {
    return (CookieStore) localContext.getAttribute(ClientContext.COOKIE_STORE);
}

From source file:com.uwindsor.elgg.project.http.AsyncHttpClient.java

/**
 * Sets an optional CookieStore to use when making requests
 * // ww  w  . j  ava 2  s.  com
 * @param cookieStore
 *            The CookieStore implementation to use, usually an instance of {@link PersistentCookieStore}
 */
public void setCookieStore(CookieStore cookieStore) {

    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:org.openrdf.http.client.SparqlSession.java

public SparqlSession(HttpClient client, ExecutorService executor) {
    this.httpClient = client;
    this.httpContext = new BasicHttpContext();
    this.executor = executor;
    valueFactory = SimpleValueFactory.getInstance();
    params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    CookieStore cookieStore = new BasicCookieStore();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

    // parser used for processing server response data should be lenient
    parserConfig.addNonFatalError(BasicParserSettings.VERIFY_DATATYPE_VALUES);
    parserConfig.addNonFatalError(BasicParserSettings.VERIFY_LANGUAGE_TAGS);
}

From source file:org.opendatakit.aggregate.externalservice.AbstractExternalService.java

protected HttpResponse sendHttpRequest(String method, String url, HttpEntity entity,
        List<NameValuePair> qparams, CallingContext cc) throws IOException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);

    // setup client
    HttpClientFactory factory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
    HttpClient client = factory.createHttpClient(httpParams);

    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    // redirect limit is set to some unreasonably high number
    // resets of the socket cause a retry up to MAX_REDIRECTS times,
    // so we should be careful not to set this too high...
    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 32);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // context holds authentication state machine, so it cannot be
    // shared across independent activities.
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

    HttpUriRequest request = null;//from   w ww .j av  a2  s . c om
    if (entity == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("No body supplied for POST, PATCH or PUT request");
    } else if (entity != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("Body was supplied for GET or DELETE request");
    }

    URI nakedUri;
    try {
        nakedUri = new URI(url);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException(e);
    }

    if (qparams == null) {
        qparams = new ArrayList<NameValuePair>();
    }
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, HtmlConsts.UTF8_ENCODE), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new IllegalStateException(e1);
    }
    System.out.println(uri.toString());

    if (GET.equals(method)) {
        HttpGet get = new HttpGet(uri);
        request = get;
    } else if (DELETE.equals(method)) {
        HttpDelete delete = new HttpDelete(uri);
        request = delete;
    } else if (PATCH.equals(method)) {
        HttpPatch patch = new HttpPatch(uri);
        patch.setEntity(entity);
        request = patch;
    } else if (POST.equals(method)) {
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);
        request = post;
    } else if (PUT.equals(method)) {
        HttpPut put = new HttpPut(uri);
        put.setEntity(entity);
        request = put;
    } else {
        throw new IllegalStateException("Unexpected request method");
    }

    HttpResponse resp = client.execute(request);
    return resp;
}

From source file:org.vietspider.net.client.impl.AnonymousHttpClient.java

@Override
protected HttpContext createHttpContext() {
    HttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
    context.setAttribute(ClientContext.COOKIE_STORE, getCookieStore());
    context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
    return context;
}

From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.ServiceToAPIExecutor.java

/**
 * Update the APIM DB for the published API.
 *
 * @param resource/*from w  ww .  j a  v a  2 s  . c  om*/
 * @param serviceName
 */
private boolean publishDataToAPIM(Resource resource, String serviceName) throws GovernanceException {

    boolean valid = true;

    if (apimEndpoint == null || apimUsername == null || apimPassword == null || apimEnv == null) {
        throw new GovernanceException(ExecutorConstants.APIM_LOGIN_UNDEFINED);
    }

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    //  APIUtils apiUtils = new APIUtils();
    APIUtils.authenticateAPIM(httpContext, apimEndpoint, apimUsername, apimPassword);
    String addAPIendpoint = apimEndpoint + Constants.APIM_ENDPOINT;

    try {
        // create a post request to addAPI.
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(addAPIendpoint);

        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        String[] endPoints = artifact.getAttributes(Constants.ENDPOINTS_ENTRY);
        if (endPoints == null || endPoints.length == 0) {
            String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore";
            throw new GovernanceException(msg);
        }
        List<String> endPointsList = Arrays.asList(endPoints);
        if (endPointsList == null) {
            String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore";
            throw new GovernanceException(msg);
        }

        addParameters(params, resource, serviceName);
        LOG.info(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE));
        ResponseAPIM responseAPIM = APIUtils.callAPIMToPublishAPI(httpclient, httppost, params, httpContext);

        if (responseAPIM.getError().equalsIgnoreCase(Constants.TRUE_CONSTANT)) {
            LOG.error(responseAPIM.getMessage());
            throw new GovernanceException("Error occurred while adding the api to API Manager.");
        }

    } catch (Exception e) {
        throw new GovernanceException(e.getMessage(), e);
    }
    return valid;
}

From source file:org.everit.osgi.authentication.http.session.tests.SessionAuthenticationTestComponent.java

@Test
public void testAccessHelloPage() throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    long sessionResourceId = hello(httpContext, authenticationContext.getDefaultResourceId());
    sessionResourceId = hello(httpContext, sessionResourceId);
    sessionResourceId = hello(httpContext, sessionResourceId);
    logoutPost(httpContext);//from   w ww  .ja v  a 2 s .  c  o m

    sessionResourceId = hello(httpContext, authenticationContext.getDefaultResourceId());
    sessionResourceId = hello(httpContext, sessionResourceId);
    hello(httpContext, sessionResourceId);
    logoutGet(httpContext);

    hello(httpContext, authenticationContext.getDefaultResourceId());
}

From source file:com.ryan.ryanreader.cache.CacheDownload.java

private void downloadGet(final HttpClient httpClient) {

    httpGet = new HttpGet(initiator.url);
    if (initiator.isJson)
        httpGet.setHeader("Accept-Encoding", "gzip");

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

    final HttpResponse response;
    final StatusLine status;

    try {/* w  ww.ja v  a 2  s .  c om*/
        if (cancelled) {
            notifyAllOnFailure(RequestFailureType.CANCELLED, null, null, "Cancelled");
            return;
        }
        response = httpClient.execute(httpGet, localContext);
        status = response.getStatusLine();

    } catch (Throwable t) {
        t.printStackTrace();
        notifyAllOnFailure(RequestFailureType.CONNECTION, t, null, "Unable to open a connection");
        return;
    }

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

    if (cancelled) {
        notifyAllOnFailure(RequestFailureType.CANCELLED, null, null, "Cancelled");
        return;
    }

    final HttpEntity entity = response.getEntity();

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

    final InputStream is;

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

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

    final long contentLength = entity.getContentLength();

    if (initiator.isJson) {

        final InputStream bis;

        if (initiator.cache) {
            final CachingInputStream cis = new CachingInputStream(is, cacheOs,
                    new CachingInputStream.BytesReadListener() {
                        public void onBytesRead(final long total) {
                            notifyAllOnProgress(total, contentLength);
                        }
                    });

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

        final JsonValue value;

        try {
            value = new JsonValue(bis);
            value.buildInNewThread();

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

        synchronized (this) {
            this.value = value;
            notifyAllOnJsonParseStarted(value, RRTime.utcCurrentTimeMillis(), session);
        }

        try {
            value.join();

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

        success = true;

    } else {

        if (!initiator.cache) {
            BugReportActivity.handleGlobalError(initiator.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);
                notifyAllOnProgress(totalBytesRead, contentLength);
            }

            cacheOs.flush();
            cacheOs.close();
            success = true;

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

From source file:pl.openrnd.connection.rest.ConnectionHandler.java

private void createCookieIfNotSet() {
    synchronized (mCookieLock) {
        if (!hasCookie()) {
            mCookieStore = new PersistentCookieStore(mApplicationContext);
            mHttpContext = new BasicHttpContext();
            mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);
        }/*from   ww w.  j a  v  a 2  s  .  com*/
    }
}

From source file:cn.caimatou.canting.utils.http.asynchttp.AsyncHttpClient.java

/**
 * Sets an optional CookieStore to use when making requests
 * @param cookieStore The CookieStore implementation to use, usually an instance of {@link PersistentCookieStore}
 *///from  ww  w.  jav  a 2  s. co  m
public void setCookieStore(CookieStore cookieStore) {
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}