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.radicaldynamic.groupinform.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  om
 */
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.mpower.mintel.android.application.MIntel.java

/**
 * Shared HttpContext so a user doesn't have to re-enter login information
 * /*from ww  w  .j  a v a  2s .c o m*/
 * @return
 */
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 BasicCredentialsProvider();
        localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    }
    return localContext;
}

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

@Test(groups = "wso2.greg", description = "Add Schema without name", dependsOnMethods = "addNoteTestCase")
public void getNoteTestCase() throws Exception {
    Thread.sleep(60000);// www.  j ava2 s.c o m
    String session_id = authenticateJaggeryAPI();
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpClient client = new DefaultHttpClient();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("https").setHost("localhost:10343").setPath("/publisher/apis/assets")
            .setParameter("type", "note").setParameter("q",
                    "overview_resourcepath\":\"/_system/governance/trunk/soapservices/4.5.0/SOAPService1\"");
    URI uri = builder.build();
    HttpGet httpget = new HttpGet(uri);
    HttpResponse response = client.execute(httpget);
    assertEquals("OK", response.getStatusLine().getReasonPhrase());
}

From source file:com.lazerycode.selenium.filedownloader.FileDownloader.java

/**
 * Perform the file/image download./*  w  w  w .  ja v  a2  s  . c om*/
 *
 * @param element
 * @param attribute
 * @return
 * @throws IOException
 * @throws NullPointerException
 */
private String downloader(WebElement element, String attribute, String Filename)
        throws IOException, NullPointerException, URISyntaxException {
    String fileToDownloadLocation = element.getAttribute(attribute);
    if (fileToDownloadLocation.trim().equals(""))
        throw new NullPointerException("The element you have specified does not link to anything!");

    URL fileToDownload = new URL(fileToDownloadLocation);
    //changed by Raul
    File downloadedFile = new File(Filename);
    //+ " fileToDownload.getFile().replaceFirst("/|\\\\", "").replace("?", ""));

    if (downloadedFile.canWrite() == false)
        downloadedFile.setWritable(true);

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();

    //LOG.info("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState);
    if (this.mimicWebDriverCookieState) {
        localContext.setAttribute(ClientContext.COOKIE_STORE,
                mimicCookieState(this.driver.manage().getCookies()));
    }

    HttpGet httpget = new HttpGet(fileToDownload.toURI());
    HttpParams httpRequestParameters = httpget.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
    httpget.setParams(httpRequestParameters);

    // LOG.info("Sending GET request for: " + httpget.getURI());
    HttpResponse response = client.execute(httpget, localContext);
    this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
    //LOG.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt);
    //LOG.info("Downloading file: " + downloadedFile.getName());
    FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
    response.getEntity().getContent().close();

    String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
    // LOG.info("File downloaded to '" + downloadedFileAbsolutePath + "'");

    return downloadedFileAbsolutePath;
}

From source file:com.bright.json.JSonRequestor.java

public static String doRequest(String jsonReq, String myURL, List<Cookie> cookies) {
    try {/*from   w  w  w  . j  a va 2  s  .c  o  m*/

        /* HttpClient httpclient = new DefaultHttpClient(); */

        HttpClient httpclient = getNewHttpClient();
        CookieStore cookieStore = new BasicCookieStore();
        Cookie[] cookiearray = cookies.toArray(new Cookie[0]);
        cookieStore.addCookie(cookiearray[0]);
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        /* httpclient = WebClientDevWrapper.wrapClient(httpclient); */

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 1000);
        HttpConnectionParams.setSoTimeout(params, 1000);
        HttpPost httppost = new HttpPost(myURL);
        StringEntity stringEntity = new StringEntity(jsonReq);
        stringEntity.setContentType("application/json");
        httppost.setEntity(stringEntity);

        System.out.println("executing request " + httppost.getRequestLine()
                + System.getProperty("line.separator") + jsonReq);

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

        System.out.println(response + "\n");
        for (Cookie c : ((AbstractHttpClient) httpclient).getCookieStore().getCookies()) {
            System.out.println("\n Cookie: " + c.toString() + "\n");
        }

        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println("Chunked?: " + resEntity.isChunked());
            String message = new String(EntityUtils.toString(resEntity));
            System.out.println(message);
            return message;
        }
        EntityUtils.consume(resEntity);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return null;

}

From source file:org.openlmis.UiUtils.HttpClient.java

public void createContext() {
    this.httpClient = new DefaultHttpClient();
    CookieStore cookieStore = new BasicCookieStore();
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:org.wso2.carbon.appmgt.impl.publishers.WSO2ExternalAppStorePublisher.java

@Override
public void deleteFromStore(WebApp webApp, AppStore store) throws AppManagementException {
    if (log.isDebugEnabled()) {
        String msg = String.format("Deleting web app : %s from external store : %s ", webApp.getApiName(),
                store.getName());/*w w  w .  ja  v  a  2s.  c  o  m*/
        log.debug(msg);
    }

    validateStore(store);

    String storeEndpoint = store.getEndpoint();
    HttpClient httpClient = AppManagerUtil.getHttpClient(storeEndpoint);
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    loginToExternalStore(store, httpContext, httpClient);
    deleteFromExternalStore(webApp, store.getUsername(), storeEndpoint, httpContext);
    logoutFromExternalStore(storeEndpoint, httpContext, httpClient);
}

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

/**
 * @param lt//from  www  .j av a2 s . c o m
 * @param user
 * @param password
 * @return
 */
private Cookie doLoginCookie(LoginTicketContainer lt, String user, String password) {
    Cookie doLoginCookie = null;
    HttpResponse res = null;
    HttpClientFactory f = new HttpClientFactory();
    f.setLoginURL(getCasServerURL());
    DefaultHttpClient client = null;
    client = f.getClient();
    HttpContext localContext = new BasicHttpContext();
    BasicCookieStore cs = new BasicCookieStore();
    cs.addCookie(lt.getSessionCookie());
    HttpPost post = new HttpPost(getURL("login"));
    client.setCookieStore(cs);
    localContext.setAttribute(ClientContext.COOKIE_STORE, cs);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("lt", lt.getLoginTicket()));
    nameValuePairs.add(new BasicNameValuePair("execution", lt.getExecution()));
    nameValuePairs.add(new BasicNameValuePair("_eventId", "submit"));
    nameValuePairs.add(new BasicNameValuePair("username", user));
    nameValuePairs.add(new BasicNameValuePair("password", password));
    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        AuriusAuthException ex = new AuriusAuthException("UnsupportedEncodingException",
                AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    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;
    }
    if (client.getCookieStore().getCookies() != null) {
        for (Cookie c : client.getCookieStore().getCookies()) {
            if (getCasTGCName().equals(c.getName())) {
                doLoginCookie = c;
                break;
            }
        }
    }
    if (doLoginCookie == null) {
        throw new AuriusAuthException("No se ha logrado el login");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Obtenido: " + doLoginCookie);
    }
    return doLoginCookie;
}

From source file:io.vertigo.struts2.FileDownloader4Tests.java

/**
 * Perform the file/image download.//  w  ww .  j  a  v  a2s .  com
 *
 * @param element
 * @param attribute
 * @return downloadedFileAbsolutePath
 * @throws IOException
 * @throws NullPointerException
 */
private String downloader(final WebElement element, final String attribute)
        throws IOException, NullPointerException, URISyntaxException {
    final String fileToDownloadLocation = element.getAttribute(attribute);
    if (fileToDownloadLocation.trim().equals("")) {
        throw new NullPointerException("The element you have specified does not link to anything!");
    }

    final URL fileToDownload = new URL(fileToDownloadLocation);
    final File downloadedFile = new TempFile(localDownloadPath, "test");
    if (downloadedFile.canWrite() == false) {
        downloadedFile.setWritable(true);
    }

    try (final CloseableHttpClient client = HttpClientBuilder.create().build()) {
        final BasicHttpContext localContext = new BasicHttpContext();

        LOG.info("Mimic WebDriver cookie state: " + mimicWebDriverCookieState);
        if (mimicWebDriverCookieState) {
            localContext.setAttribute(ClientContext.COOKIE_STORE,
                    mimicCookieState(driver.manage().getCookies()));
        }

        final HttpGet httpget = new HttpGet(fileToDownload.toURI());
        final HttpParams httpRequestParameters = httpget.getParams();
        httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects);
        httpget.setParams(httpRequestParameters);

        LOG.info("Sending GET request for: " + httpget.getURI());
        try (final CloseableHttpResponse response = client.execute(httpget, localContext)) {
            httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
            LOG.info("HTTP GET request status: " + httpStatusOfLastDownloadAttempt);
            LOG.info("Downloading file: " + downloadedFile.getName());
            FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
            //response.getEntity().getContent().close();
        }
    }

    final String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
    LOG.info("File downloaded to '" + downloadedFileAbsolutePath + "'");

    return downloadedFileAbsolutePath;
}

From source file:com.dhenton9000.filedownloader.FileDownloader.java

private HttpResponse getHTTPResponse() throws IOException, NullPointerException {
    if (fileURI == null)
        throw new NullPointerException("No file URI specified");

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();

    //Clear down the local cookie store every time to make sure we don't have any left over cookies influencing the test
    localContext.setAttribute(ClientContext.COOKIE_STORE, null);

    LOG.info("Mimic WebDriver cookie state: " + mimicWebDriverCookieState);
    if (mimicWebDriverCookieState) {
        localContext.setAttribute(ClientContext.COOKIE_STORE, mimicCookieState(driver.manage().getCookies()));
    }//from   ww w  . j  a  v  a  2  s  .c  om

    HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod();
    requestMethod.setURI(fileURI);
    HttpParams httpRequestParameters = requestMethod.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects);
    requestMethod.setParams(httpRequestParameters);
    //TODO if post send map of variables, also need to add a post map setter

    LOG.info("Sending " + httpRequestMethod.toString() + " request for: " + fileURI);
    return client.execute(requestMethod, localContext);
}