Example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore

List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore.

Prototype

public BasicCookieStore() 

Source Link

Usage

From source file:org.coronastreet.gpxconverter.StravaForm.java

public void upload() {
    //httpClient = new DefaultHttpClient();
    httpClient = HttpClientBuilder.create().build();
    localContext = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    if (doLogin()) {
        //log("Ok....logged in...");
        try {//  w  w w  . ja  v  a  2 s  .c om
            // Have to fetch the form to get the CSRF Token
            HttpGet get = new HttpGet(uploadFormURL);
            HttpResponse formResponse = httpClient.execute(get, localContext);
            //log("Fetched the upload form...: " + formResponse.getStatusLine());
            org.jsoup.nodes.Document doc = Jsoup.parse(EntityUtils.toString(formResponse.getEntity()));
            String csrftoken, csrfparam;
            Elements metalinksParam = doc.select("meta[name=csrf-param]");
            if (!metalinksParam.isEmpty()) {
                csrfparam = metalinksParam.first().attr("content");
            } else {
                csrfparam = null;
                log("Missing csrf-param?");
            }
            Elements metalinksToken = doc.select("meta[name=csrf-token]");
            if (!metalinksToken.isEmpty()) {
                csrftoken = metalinksToken.first().attr("content");
            } else {
                csrftoken = null;
                log("Missing csrf-token?");
            }

            HttpPost request = new HttpPost(uploadURL);
            request.setHeader("X-CSRF-Token", csrftoken);

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            entity.addPart("method", new StringBody("post"));
            entity.addPart("new_uploader", new StringBody("1"));
            entity.addPart(csrfparam, new StringBody(csrftoken));
            entity.addPart("files[]",
                    new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx"));

            // Need to do this bit because without it you can't disable chunked encoding, and Strava doesn't support chunked.
            ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
            entity.writeTo(bArrOS);
            bArrOS.flush();
            ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
            bArrOS.close();

            bArrEntity.setChunked(false);
            bArrEntity.setContentEncoding(entity.getContentEncoding());
            bArrEntity.setContentType(entity.getContentType());

            request.setEntity(bArrEntity);

            HttpResponse response = httpClient.execute(request, localContext);

            if (response.getStatusLine().getStatusCode() != 200) {
                log("Failed to Upload");
                HttpEntity en = response.getEntity();
                if (en != null) {
                    String output = EntityUtils.toString(en);
                    log(output);
                }
            } else {
                HttpEntity ent = response.getEntity();
                if (ent != null) {
                    String output = EntityUtils.toString(ent);
                    //log(output);
                    JSONObject userInfo = new JSONArray(output).getJSONObject(0);
                    //log("Object: " + userInfo.toString());

                    if (userInfo.get("workflow").equals("Error")) {
                        log("Upload Error: " + userInfo.get("error"));
                    } else {
                        log("Successful Uploaded. ID is " + userInfo.get("id"));
                    }
                }
            }
            httpClient.close();
        } catch (Exception ex) {
            log("Exception? " + ex.getMessage());
            ex.printStackTrace();
            // handle exception here
        }
    } else {
        log("Failed to upload!");
    }
}

From source file:org.debux.webmotion.test.ActionMiscIT.java

@Test
public void cookieManagerRead() throws IOException, URISyntaxException {
    URI uri = createRequest("/cookie/read").addParameter("secured", "false").build();

    HttpGet request = new HttpGet(uri);

    DefaultHttpClient client = new DefaultHttpClient();
    CookieStore cookieStore = new BasicCookieStore();
    client.setCookieStore(cookieStore);/*from   w  ww. j a  v  a  2 s .  c  o m*/

    BasicClientCookie initialCookie = new BasicClientCookie("name", "test");
    initialCookie.setVersion(1);
    initialCookie.setDomain("localhost");
    initialCookie.setPath("/webmotion-test/test/cookie");
    cookieStore.addCookie(initialCookie);

    HttpResponse response = client.execute(request);

    HttpEntity entity = response.getEntity();
    InputStream content = entity.getContent();
    String result = IOUtils.toString(content);
    AssertJUnit.assertTrue(result, result.contains("Value = test"));
}

From source file:org.debux.webmotion.test.ActionMiscIT.java

@Test
public void cookieManagerObjectRemove() throws IOException, URISyntaxException {
    URI uri = createRequest("/cookie/object/remove").build();

    HttpGet request = new HttpGet(uri);

    DefaultHttpClient client = new DefaultHttpClient();
    CookieStore cookieStore = new BasicCookieStore();
    client.setCookieStore(cookieStore);/*from ww w.  j  a va  2 s.c  o  m*/

    BasicClientCookie initialCookie = new BasicClientCookie("user_cookie", "{}");
    initialCookie.setVersion(1);
    initialCookie.setDomain("localhost");
    initialCookie.setPath("/webmotion-test/test/cookie/object");
    cookieStore.addCookie(initialCookie);

    client.execute(request);

    List<Cookie> cookies = cookieStore.getCookies();
    for (Cookie cookie : cookies) {
        String name = cookie.getName();
        if ("user_cookie".equals(name)) {
            throw new RuntimeException("Invalid cookie");
        }
    }
}

From source file:org.debux.webmotion.test.ActionMiscIT.java

@Test
public void cookieManagerObjectRead() throws IOException, URISyntaxException {
    URI uri = createRequest("/cookie/object/read").build();

    HttpGet request = new HttpGet(uri);

    DefaultHttpClient client = new DefaultHttpClient();
    CookieStore cookieStore = new BasicCookieStore();
    client.setCookieStore(cookieStore);//from w  w  w.j ava 2  s.com

    BasicClientCookie initialCookie = new BasicClientCookie("user_cookie", "{\\\"value\\\":\\\"test\\\"}");
    initialCookie.setVersion(1);
    initialCookie.setDomain("localhost");
    initialCookie.setPath("/webmotion-test/test/cookie/object");
    cookieStore.addCookie(initialCookie);

    HttpResponse response = client.execute(request);

    HttpEntity entity = response.getEntity();
    InputStream content = entity.getContent();
    String result = IOUtils.toString(content);
    AssertJUnit.assertTrue(result, result.contains("Current value = test"));
}

From source file:org.everit.authentication.http.form.ecm.tests.FormAuthenticationServletTestComponent.java

@Test
@TestDuringDevelopment//from ww  w .j  a v  a2  s .  co  m
public void testAccessHelloPage() throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    hello(httpContext, defaultResourceId);
    login(httpContext, USERNAME, WRONG_PASSWORD, loginFailedUrl);
    login(httpContext, USERNAME, PASSWORD, loginSuccessUrl);
    hello(httpContext, authenticatedResourceId);
}

From source file:org.everit.osgi.authentication.http.form.tests.FormAuthenticationServletTestComponent.java

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

    hello(httpContext, defaultResourceId);
    login(httpContext, USERNAME, WRONG_PASSWORD, loginFailedUrl);
    login(httpContext, USERNAME, PASSWORD, loginSuccessUrl);
    hello(httpContext, authenticatedResourceId);
}

From source file:org.exoplatform.utils.ExoConnectionUtils.java

public static void setCookieStore(CookieStore cookieStore, ArrayList<String> list) {
    cookieStore = new BasicCookieStore();
    for (String cookieStr : list) {
        String[] keyValue = cookieStr.split("=");
        String key = keyValue[0];
        String value = "";
        if (keyValue.length > 1)
            value = keyValue[1];//from w  w  w .  jav  a 2s. c  o m
        cookieStore.addCookie(new BasicClientCookie(key, value));
    }
}

From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java

/**
 * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers
 * many opportunities for customization. By default, <a href=
 * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html">
 * SystemDefaultHttpClient</a> is used if available, otherwise it falls back
 * to://w  ww . j a v  a2s .  c o m
 * 
 * <pre>
 * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams)
 * </pre>
 * 
 * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case,
 * it should be thread-safe.
 */
protected HttpClient createHttpClient(HttpParams hcParams) {
    try {

        String negotiateURL = getConfigParam("negotiate.url");
        String negotiateSPN = getConfigParam("negotiate.spn");
        if (negotiateURL != null && negotiateSPN != null) {
            System.out.println("negotiate url:" + negotiateURL);
            System.out.println("negotiate spn:" + negotiateSPN);
            // initialize the Windows security Context to get the negotiate
            // client token
            IWindowsSecurityContext clientContext = null;
            IWindowsCredentialsHandle clientCredentials = null;
            clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN);
            clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE);
            clientCredentials.initialize();
            String username = WindowsAccountImpl.getCurrentUsername();
            System.out.println("credentials for user " + username + " get prepared");
            byte[] token = clientContext.getToken();
            // encode the token with Base64 to be able to add it to the http
            // header
            String clientToken = Base64.encodeBase64String(token);
            System.out.println("clientToken" + clientToken);
            // if there is only a negotiate url the rest of the
            // authorization is based on cookies
            // so we need to support them.
            CookieStore cookieStore = new BasicCookieStore();
            RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
            HttpClientContext context = HttpClientContext.create();
            proxyContext = context;
            context.setCookieStore(cookieStore);
            HttpClient httpClient = HttpClients.custom().disableRedirectHandling()
                    .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

            // first we need to act as a normal browser to get a http 401
            // with negotiate header
            doActAsBrowser = true;
            HttpGet browserHttpGet = new HttpGet(negotiateURL);
            addBrowserHeader(browserHttpGet);
            HttpResponse rep = httpClient.execute(browserHttpGet, context);

            if (rep.getStatusLine().getStatusCode() == 401) {
                System.out.println("negotiate requested - sending negotiate client token");
                HttpGet negotiateHttpGet = new HttpGet(negotiateURL);
                addBrowserHeader(negotiateHttpGet);
                negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken);
                HttpResponse response = httpClient.execute(negotiateHttpGet, context);
                System.out.println(
                        "http result code of negotiate request:" + response.getStatusLine().getStatusCode());
                // now the url needs to be called periodically to keep the
                // cookie and connection alive
                String refreshTimeString = getConfigParam("negotiate.refreshtime");
                long refreshTime = 1000000;
                if (refreshTimeString != null) {
                    refreshTime = Long.parseLong(refreshTimeString);
                }
                HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL);
                thread.start();
                List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies();
                cookieString = "";
                int size = cookies.size() - 1;
                for (int i = 0; i < cookies.size(); i++) {
                    cookieString += cookies.get(i).getName();
                    cookieString += "=";
                    cookieString += cookies.get(i).getValue();
                    if (i != size)
                        cookieString += "; ";
                }
            } else {
                System.out.println("No negotiate requested");
            }
        } else {
            if (!WinHttpClients.isWinAuthAvailable()) {
                System.out.println("Integrated Win auth is not supported!!!");
            } else {
                HttpClientBuilder builder = WinHttpClients.custom();
                Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                        .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                        .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();
                builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
                String username = getConfigParam("user");
                String password = getConfigParam("password");
                String domain = getConfigParam("domain");
                String host = getConfigParam("host");
                if (username != null) {
                    NTCredentials cred = new NTCredentials(username, password, host, domain);
                    CredentialsProvider credsProvider = new WindowsCredentialsProvider(
                            new SystemDefaultCredentialsProvider());
                    credsProvider.setCredentials(AuthScope.ANY, cred);
                    builder.setDefaultCredentialsProvider(credsProvider);
                }
                builder.disableCookieManagement();
                builder.disableRedirectHandling();
                return builder.build();
            }

            // as of HttpComponents v4.2, this class is better since it uses
            // System
            // Properties:
            Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient");
            Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class);
            return (HttpClient) constructor.newInstance(hcParams);
        }
    } catch (ClassNotFoundException e) {
        // no problem; use v4.1 below
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Fallback on using older client:
    return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams);
}

From source file:org.nuxeo.ecm.automation.client.jaxrs.impl.HttpConnector.java

/**
 * @see #HttpConnector(HttpClient, long)
 * @since 5.7//from  w  ww  .jav  a 2  s.  c  o m
 */
public HttpConnector(HttpClient http, HttpContext ctx, int httpConnectionTimeout) {
    ctx.setAttribute(HttpClientContext.COOKIE_STORE, new BasicCookieStore());
    this.http = http;
    this.httpConnectionTimeout = httpConnectionTimeout;
    this.ctx = ctx;
}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Creates an Apache HTTP Client object, ignoring SSL Exceptions like self signed
 * certificates, and sets Auth. Scheme to Digest Auth.
 *
 * @param fboxUrl/*from   w w  w.  ja  v  a  2  s. co m*/
 *            the URL from config file of fbox to connect to
 * @return the ready-to-use httpclient for tr064 requests
 */
private synchronized CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);

    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth
    // cache. Digeste is standard for fbox auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    digestAuth.overrideParamter("realm", "HTTPS Access"); // known from fbox specification
    digestAuth.overrideParamter("nonce", ""); // never known at first request
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);

    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // accept self signed certs
        // dont verify hostname against cert CN
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null,
                new NoopHostnameVerifier());
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }

    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000)
            .setConnectionRequestTimeout(4000).build();

    // BUILDER
    // setup builder with parameters defined before
    hc = HttpClientBuilder.create().setSSLSocketFactory(sslsf) // set the SSL options which trust every self signed
            // cert
            .setDefaultCredentialsProvider(credp) // set auth options using digest
            .setDefaultRequestConfig(rc) // set the request config specifying timeout
            .build();

    return hc;
}