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:it.fabaris.wfp.application.Collect.java

/**
 * Shared HttpContext so a user doesn't have to re-enter login information
 * @return/* w  w  w  .  j av a  2 s.  c o  m*/
 */
public synchronized HttpContext getHttpContext() {
    if (localContext == null) {
        /**
         *  set up one context for all HTTP requests so that authentication
         *  and cookies can be retained.
         */
        localContext = new SyncBasicHttpContext(new BasicHttpContext());

        /**
         *  establish a local cookie store for this attempt at downloading...
         */
        CookieStore cookieStore = new BasicCookieStore();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        /**
         *  and establish a credentials provider.  Default is 7 minutes.
         *  CredentialsProvider credsProvider = new AgingCredentialsProvider(7 * 60 * 1000);
         *  localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
         */
    }
    return localContext;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * CookieStore per AccountName to prevent mixing of the sessions.
 * //from ww w.  j  a  v  a2s  . c o  m
 * @param accountName
 *            accountName or null (default)
 * @return
 */
private static HttpContext createHttpContext(String accountName, String authtoken) {
    BasicHttpContext ctx = new BasicHttpContext();
    CookieStore store;
    synchronized (CL_LOCK) {
        store = COOKIES.get(accountName);
        if (store == null) {
            store = new BasicCookieStore();
            COOKIES.put(accountName, store);
        }
    }
    ctx.setAttribute(ClientContext.COOKIE_STORE, store);

    if (authtoken != null) {
        boolean add = true;
        for (Cookie cookie : store.getCookies()) {
            if (COOKIE_SESSION_NAME.equals(cookie.getName())) {
                if (authtoken.equals(cookie.getValue())) {
                    add = false;
                }
                break;
            }
        }
        if (add) {
            BasicClientCookie sessionCookie = new BasicClientCookie(COOKIE_SESSION_NAME, authtoken);
            sessionCookie.setSecure(true);
            store.addCookie(sessionCookie);
        }
    }

    return ctx;
}

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

/**
 * Deletes API from the API Manager/*from   ww w  .  j av a 2s .  c  o  m*/
 *
 * @param api API Generic artifact.
 * @return    True if successfully deleted.
 */
private boolean deleteFromAPIManager(GenericArtifact api) throws RegistryException {
    if (apimEndpoint == null || apimUsername == null || apimPassword == null) {
        throw new RuntimeException(ExecutorConstants.APIM_LOGIN_UNDEFINED);
    }

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

    Utils.authenticateAPIM(httpContext, apimEndpoint, apimUsername, apimPassword);
    String removeEndpoint = apimEndpoint + ExecutorConstants.APIM_REMOVE_URL;

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

        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair(ExecutorConstants.API_ACTION, ExecutorConstants.API_REMOVE_ACTION));
        params.add(new BasicNameValuePair(ExecutorConstants.API_NAME,
                api.getAttribute(ExecutorConstants.SERVICE_NAME)));
        params.add(new BasicNameValuePair(ExecutorConstants.API_PROVIDER, apimUsername));
        params.add(new BasicNameValuePair(ExecutorConstants.API_VERSION,
                api.getAttribute(ExecutorConstants.SERVICE_VERSION)));

        httppost.setEntity(new UrlEncodedFormEntity(params, ExecutorConstants.DEFAULT_CHAR_ENCODING));

        HttpResponse response = httpclient.execute(httppost, httpContext);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

    } catch (ClientProtocolException e) {
        throw new RegistryException(ExecutorConstants.APIM_POST_REQ_FAIL, e);
    } catch (UnsupportedEncodingException e) {
        throw new RegistryException(ExecutorConstants.ENCODING_FAIL, e);
    } catch (IOException e) {
        throw new RegistryException(ExecutorConstants.APIM_POST_REQ_FAIL, e);
    }

    return true;
}

From source file:net.emphased.vkclient.VkClient.java

protected HttpContext getHttpContext(CookieStore cookieStore) {
    HttpContext result = _httpContextFactory.create();
    result.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    return result;
}

From source file:org.everit.authentication.http.session.ecm.tests.SessionAuthenticationComponentTest.java

@Test
@TestDuringDevelopment//  w  ww.j  a  va 2  s .  c  o m
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);

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

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

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

/**
 * Update the APIM DB for the published API.
 * /* w  w  w  .  j a  v a  2  s  .  c o m*/
 * @param service
 * @param serviceName
 */
private void publishDataToAPIM(Service service, String serviceName) {

    if (apimEndpoint == null || apimUsername == null || apimPassword == null) {
        String msg = "APIManager endpoint URL or credentials are not defined";
        log.error(msg);
        throw new RuntimeException(msg + "API Publish might fail");
    }

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

    authenticateAPIM(httpContext);
    String addAPIendpoint = apimEndpoint + "publisher/site/blocks/item-add/ajax/add.jag";

    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>();

        if (service.getAttachedEndpoints().length == 0) {
            String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore.Publishing at gateway might fail";
            log.warn(msg);
        }

        if (service.getAttachedEndpoints().length > 0) {
            params.add(new BasicNameValuePair(API_ENDPOINT, service.getAttachedEndpoints()[0].getUrl()));
        }
        params.add(new BasicNameValuePair(API_ACTION, API_ADD_ACTION));
        params.add(new BasicNameValuePair(API_NAME, serviceName));
        params.add(new BasicNameValuePair(API_CONTEXT, serviceName));
        params.add(new BasicNameValuePair(API_VERSION, service.getAttribute(SERVICE_VERSION)));
        params.add(new BasicNameValuePair("API_PROVIDER",
                CarbonContext.getThreadLocalCarbonContext().getUsername()));
        params.add(new BasicNameValuePair(API_TIER, defaultTier));
        params.add(new BasicNameValuePair(API_URI_PATTERN, DEFAULT_URI_PATTERN));
        params.add(new BasicNameValuePair(API_URI_HTTP_METHOD, DEFAULT_HTTP_VERB));
        params.add(new BasicNameValuePair(API_URI_AUTH_TYPE, DEFAULT_AUTH_TYPE));
        params.add(new BasicNameValuePair(API_VISIBLITY, DEFAULT_VISIBILITY));
        params.add(new BasicNameValuePair(API_THROTTLING_TIER, apiThrottlingTier));

        for (int i = 0; i < service.getAttachedWsdls().length; i++) {
            String wsdlPath = service.getAttachedWsdls()[0].getPath();
            if (wsdlPath != null && wsdlPath.toLowerCase().startsWith("http")) {
                params.add(new BasicNameValuePair(API_WSDL, wsdlPath));
            }
        }

        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        HttpResponse response = httpclient.execute(httppost, httpContext);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

    } catch (Exception e) {
        log.error("Error in updating APIM DB", e);
    }
    // after publishing update the lifecycle status
    //updateStatus(service, serviceName, httpContext);
}

From source file:cn.xdf.thinkutils.http.HttpUtils.java

public HttpUtils configCookieStore(CookieStore cookieStore) {
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    return this;
}

From source file:org.ofbiz.testtools.seleniumxml.RemoteRequest.java

public void runTest() {

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(defaultParameters, supportedSchemes);
    //  new SingleClientConnManager(getParams(), supportedSchemes);

    DefaultHttpClient client = new DefaultHttpClient(ccm, defaultParameters);
    client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    ////from  w ww  . java 2 s.  co m
    // We first try to login with the loginAs to set the session.
    // Then we call the remote service.
    //
    HttpEntity entity = null;
    ResponseHandler<String> responseHandler = null;
    try {
        BasicHttpContext localContext = new BasicHttpContext();
        // Create a local instance of cookie store
        CookieStore cookieStore = new BasicCookieStore();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        Header sessionHeader = null;

        if (this.loginAsUrl != null) {

            String loginAsUri = this.host + this.loginAsUrl;
            String loginAsParamString = "?" + this.loginAsUserParam + "&" + this.loginAsPasswordParam;

            HttpGet req2 = new HttpGet(loginAsUri + loginAsParamString);
            System.out.println("loginAsUrl:" + loginAsUri + loginAsParamString);

            req2.setHeader("Connection", "Keep-Alive");
            HttpResponse rsp = client.execute(req2, localContext);

            Header[] headers = rsp.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Header hdr = headers[i];
                String headerValue = hdr.getValue();
                if (headerValue.startsWith("JSESSIONID")) {
                    sessionHeader = hdr;
                }
                System.out.println("login: " + hdr.getName() + " : " + hdr.getValue());
            }
            List<Cookie> cookies = cookieStore.getCookies();
            System.out.println("cookies.size(): " + cookies.size());
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("Local cookie(0): " + cookies.get(i));
            }
        }
        //String paramString2 = "USERNAME=" + this.parent.getUserName()
        //                   + "&PASSWORD=" + this.parent.getPassword();
        //String thisUri2 = this.host + "/eng/control/login?" + paramString2;
        //HttpGet req2 = new HttpGet ( thisUri2 );
        //req2.setHeader("Connection","Keep-Alive");
        //HttpResponse rsp = client.execute(req2, localContext);

        //Header sessionHeader = null;
        //Header[] headers = rsp.getAllHeaders();
        //for (int i=0; i<headers.length; i++) {
        //    Header hdr = headers[i];
        //    String headerValue = hdr.getValue();
        //    if (headerValue.startsWith("JSESSIONID")) {
        //        sessionHeader = hdr;
        //    }
        //    System.out.println(headers[i]);
        //    System.out.println(hdr.getName() + " : " + hdr.getValue());
        //}

        //List<Cookie> cookies = cookieStore.getCookies();
        //System.out.println("cookies.size(): " + cookies.size());
        //for (int i = 0; i < cookies.size(); i++) {
        //    System.out.println("Local cookie(0): " + cookies.get(i));
        //}
        if (HttpHandleMode.equals(this.responseHandlerMode)) {

        } else {
            responseHandler = new JsonResponseHandler(this);
        }

        String paramString = urlEncodeArgs(this.inMap, false);

        String thisUri = null;
        if (sessionHeader != null) {
            String sessionHeaderValue = sessionHeader.getValue();
            int pos1 = sessionHeaderValue.indexOf("=");
            int pos2 = sessionHeaderValue.indexOf(";");
            String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2);
            thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString;
        } else {
            thisUri = this.host + this.requestUrl + "?" + paramString;
        }
        //String sessionHeaderValue = sessionHeader.getValue();
        //int pos1 = sessionHeaderValue.indexOf("=");
        //int pos2 = sessionHeaderValue.indexOf(";");
        //String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2);
        //System.out.println("sessionId: " + sessionId);
        //String thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?"  + paramString;
        //String thisUri = this.host + this.requestUrl + "?"  + paramString;
        System.out.println("thisUri: " + thisUri);

        HttpGet req = new HttpGet(thisUri);
        if (sessionHeader != null) {
            req.setHeader(sessionHeader);
        }

        String responseBody = client.execute(req, responseHandler, localContext);
        /*
        entity = rsp.getEntity();
                
        System.out.println("----------------------------------------");
        System.out.println(rsp.getStatusLine());
        Header[] headers = rsp.getAllHeaders();
        for (int i=0; i<headers.length; i++) {
        System.out.println(headers[i]);
        }
        System.out.println("----------------------------------------");
                
        if (entity != null) {
        System.out.println(EntityUtils.toString(rsp.getEntity()));
        }
        */
    } catch (HttpResponseException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        // If we could be sure that the stream of the entity has been
        // closed, we wouldn't need this code to release the connection.
        // However, EntityUtils.toString(...) can throw an exception.

        // if there is no entity, the connection is already released
        try {
            if (entity != null)
                entity.consumeContent(); // release connection gracefully
        } catch (IOException e) {
            System.out.println("in 'finally'  " + e.getMessage());
        }

    }
    return;
}

From source file:cn.com.dfc.pl.afinal.FinalHttp.java

public void configCookieStore(CookieStore cookieStore) {
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:com.lillicoder.newsblurry.net.BaseTask.java

/**
 * Gets an {@link HttpContext} instance configured for making
 * web requests. The returned context will have a cookie store
 * attached for persisting cookies created during the request.
 * @return {@link HttpContext} for use with web requests.
 *///from www.  java2s  .c o  m
protected HttpContext getRequestContext() {
    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new PreferenceCookieStore(this.getContext());
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    return context;
}