List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
From source file:org.cloudfoundry.identity.uaa.integration.CheckTokenEndpointIntegrationTests.java
@Test public void testDecodeToken() { AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource(); BasicCookieStore cookies = new BasicCookieStore(); URI uri = serverRunning.buildUri("/oauth/authorize").queryParam("response_type", "code") .queryParam("state", "mystateid").queryParam("client_id", resource.getClientId()) .queryParam("redirect_uri", resource.getPreEstablishedRedirectUri()).build(); ResponseEntity<Void> result = serverRunning.getForResponse(uri.toString(), getHeaders(cookies)); assertEquals(HttpStatus.FOUND, result.getStatusCode()); String location = result.getHeaders().getLocation().toString(); if (result.getHeaders().containsKey("Set-Cookie")) { for (String cookie : result.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie(// w ww . j a v a2 s .c o m new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } ResponseEntity<String> response = serverRunning.getForString(location, getHeaders(cookies)); if (response.getHeaders().containsKey("Set-Cookie")) { for (String cookie : response.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie( new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } // should be directed to the login screen... assertTrue(response.getBody().contains("/login.do")); assertTrue(response.getBody().contains("username")); assertTrue(response.getBody().contains("password")); String csrf = IntegrationTestUtils.extractCookieCsrf(response.getBody()); MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", testAccounts.getUserName()); formData.add("password", testAccounts.getPassword()); formData.add(DEFAULT_CSRF_COOKIE_NAME, csrf); // Should be redirected to the original URL, but now authenticated result = serverRunning.postForResponse("/login.do", getHeaders(cookies), formData); assertEquals(HttpStatus.FOUND, result.getStatusCode()); if (result.getHeaders().containsKey("Set-Cookie")) { for (String cookie : result.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie( new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } response = serverRunning.getForString(result.getHeaders().getLocation().toString(), getHeaders(cookies)); if (response.getHeaders().containsKey("Set-Cookie")) { for (String cookie : response.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie( new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } if (response.getStatusCode() == HttpStatus.OK) { // The grant access page should be returned assertTrue(response.getBody().contains("<h1>Application Authorization</h1>")); formData.clear(); formData.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody())); formData.add(USER_OAUTH_APPROVAL, "true"); result = serverRunning.postForResponse("/oauth/authorize", getHeaders(cookies), formData); assertEquals(HttpStatus.FOUND, result.getStatusCode()); location = result.getHeaders().getLocation().toString(); } else { // Token cached so no need for second approval assertEquals(HttpStatus.FOUND, response.getStatusCode()); location = response.getHeaders().getLocation().toString(); } assertTrue("Wrong location: " + location, location.matches(resource.getPreEstablishedRedirectUri() + ".*code=.+")); formData.clear(); formData.add("client_id", resource.getClientId()); formData.add("redirect_uri", resource.getPreEstablishedRedirectUri()); formData.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE); formData.add("code", location.split("code=")[1].split("&")[0]); HttpHeaders tokenHeaders = new HttpHeaders(); tokenHeaders.set("Authorization", testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret())); @SuppressWarnings("rawtypes") ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); @SuppressWarnings("unchecked") OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(tokenResponse.getBody()); HttpHeaders headers = new HttpHeaders(); formData = new LinkedMultiValueMap<String, String>(); headers.set("Authorization", testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret())); formData.add("token", accessToken.getValue()); tokenResponse = serverRunning.postForMap("/check_token", formData, headers); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); @SuppressWarnings("unchecked") Map<String, String> map = tokenResponse.getBody(); assertNotNull(map.get("iss")); assertEquals(testAccounts.getUserName(), map.get("user_name")); assertEquals(testAccounts.getEmail(), map.get("email")); // Test that Spring's default converter can create an auth from the response. Authentication auth = (new DefaultUserAuthenticationConverter()).extractAuthentication(map); }
From source file:com.nosideracing.rchipremote.JSON.java
public JSON() { cookieStore = new BasicCookieStore(); }
From source file:fr.treeptik.cloudunit.cli.rest.RestUtils.java
public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException { Map<String, String> response = new HashMap<String, String>(); CloseableHttpClient httpclient = HttpClients.createDefault(); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login"))); nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password"))); localContext = HttpClientContext.create(); localContext.setCookieStore(new BasicCookieStore()); HttpPost httpPost = new HttpPost(url); try {/*from ww w. j av a2s .co m*/ httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put("body", body); httpResponse.close(); } catch (Exception e) { authentificationUtils.getMap().clear(); throw new ManagerResponseException(e.getMessage(), e); } return response; }
From source file:cn.org.once.cstack.maven.plugin.utils.RestUtils.java
/** * @param url// www . j a v a 2s .c o m * @param parameters * @param log * @return * @throws MojoExecutionException */ public Map<String, String> connect(String url, Map<String, Object> parameters, Log log) throws MojoExecutionException { Map<String, String> response = new HashMap<String, String>(); CloseableHttpClient httpclient = HttpClients.createDefault(); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login"))); nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password"))); localContext = HttpClientContext.create(); localContext.setCookieStore(new BasicCookieStore()); HttpPost httpPost = new HttpPost(url); try { httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext); ResponseHandler<String> handler = new ResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put("body", body); httpResponse.close(); isConnected = true; log.info("Connection successful"); } catch (Exception e) { log.error("Connection failed! : " + e.getMessage()); isConnected = false; throw new MojoExecutionException( "Connection failed, please check your manager location or your credentials"); } return response; }
From source file:com.rivetlogic.crafter.social.listeners.CustomTrashEntryListener.java
private void init(long companyId) { try {/*from w w w. java 2s. c om*/ CrafterManager.init(); // add crafterAuthCookie to HTTP client client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); client.setCookieStore(new BasicCookieStore()); AuthenticationCookie authCookie = CrafterManager .getCrafterProfileCookie(PrefsPropsUtil.getString(companyId, CrafterConstants.PROFILE_ADMIN_KEY, GetterUtil.getString(PropsUtil.get(CrafterConstants.PROFILE_ADMIN_KEY), CrafterConstants.PROFILE_DEFAULT_USER))); BasicClientCookie cookie = new BasicClientCookie(AuthenticationCookie.COOKIE, authCookie.toCookieValue()); cookie.setDomain(CrafterConstants.CRAFTER_DOMAIN); cookie.setExpiryDate(authCookie.getProfileOutdatedAfter()); cookie.setPath(StringPool.SLASH); client.getCookieStore().addCookie(cookie); } catch (Exception e) { LOG.error(e.getMessage()); } }
From source file:org.sonar.runner.Main.java
Main(Exit exit, Cli cli, Conf conf, RunnerFactory runnerFactory) { this.exit = exit; this.cli = cli; this.conf = conf; this.runnerFactory = runnerFactory; // apache http client setup this.httpCookieStore = new BasicCookieStore(); this.globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build(); this.httpClientContext = HttpClientContext.create(); this.httpClientContext.setCookieStore(httpCookieStore); this.httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(globalConfig) .setDefaultCookieStore(httpCookieStore); }
From source file:edu.mit.scratch.ScratchProject.java
public boolean comment(final ScratchSession session, final String comment) throws ScratchProjectException { final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", session.getSessionID()); final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", session.getCSRFToken()); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); sessid.setDomain(".scratch.mit.edu"); sessid.setPath("/"); token.setDomain(".scratch.mit.edu"); token.setPath("/"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(lang);/* w w w . j a v a2s. c o m*/ cookieStore.addCookie(sessid); cookieStore.addCookie(token); cookieStore.addCookie(debug); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)" + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36") .setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final JSONObject obj = new JSONObject(); obj.put("content", comment); obj.put("parent_id", ""); obj.put("commentee_id", ""); final String strData = obj.toString(); HttpUriRequest update = null; try { update = RequestBuilder.post() .setUri("https://scratch.mit.edu/site-api/comments/project/" + this.getProjectID() + "/add/") .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") .addHeader("Referer", "https://scratch.mit.edu/projects/" + this.getProjectID() + "/") .addHeader("Origin", "https://scratch.mit.edu/") .addHeader("Accept-Encoding", "gzip, deflate, sdch") .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json") .addHeader("X-Requested-With", "XMLHttpRequest") .addHeader("Cookie", "scratchsessionsid=" + session.getSessionID() + "; scratchcsrftoken=" + session.getCSRFToken()) .addHeader("X-CSRFToken", session.getCSRFToken()).setEntity(new StringEntity(strData)).build(); } catch (final UnsupportedEncodingException e1) { e1.printStackTrace(); } try { resp = httpClient.execute(update); System.out.println("cmntadd:" + resp.getStatusLine()); final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); System.out.println("cmtline:" + result.toString()); } catch (final IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } return false; }
From source file:mobi.jenkinsci.ci.client.JenkinsFormAuthHttpClient.java
private HttpContext doFormLogin(final String formLoginUrl, final String baseUrlString, final String user, final String password, final String otp) throws IOException { final URL baseUrl = new URL(baseUrlString); final HttpContext httpContext = new BasicHttpContext(); final CookieStore cookieStore = new BasicCookieStore(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); final HttpPost postForm = getSSOLoginForm(formLoginUrl, baseUrlString, user, password, httpContext); final String redirectUrl = doSsoLogin(httpContext, postForm); doSsoRedirect(baseUrl, httpContext, redirectUrl, otp); return httpContext; }
From source file:com.bright.json.JSonRequestor.java
public static List<Cookie> doLogin(String user, String pass, String myURL) { try {/* w w w . ja v a 2 s. c o m*/ cmLogin loginReq = new cmLogin("login", user, pass); GsonBuilder builder = new GsonBuilder(); Gson g = builder.create(); String json = g.toJson(loginReq); /* HttpClient httpclient = new DefaultHttpClient(); */ HttpClient httpclient = getNewHttpClient(); CookieStore cookieStore = new BasicCookieStore(); 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(json); stringEntity.setContentType("application/json"); httppost.setEntity(stringEntity); System.out.println("executing request " + httppost.getRequestLine()); 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"); } List<Cookie> cookies = cookieStore.getCookies(); for (int i = 0; i < cookies.size(); i++) { System.out.println("Local cookie: " + cookies.get(i)); } 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 cookies; } EntityUtils.consume(resEntity); } catch (Exception e) { e.printStackTrace(); return null; } return null; }
From source file:org.callimachusproject.client.HttpUriClient.java
@Override protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException { HttpClientContext ctx;//from w w w . j a v a 2s . co m if (context == null) { ctx = HttpClientContext.create(); } else { ctx = HttpClientContext.adapt(context); } if (ctx.getCookieStore() == null) { ctx.setCookieStore(new BasicCookieStore()); } HttpResponse response = getDelegate().execute(target, request, ctx); if (response instanceof CloseableHttpResponse) { return (CloseableHttpResponse) response; } else { return new HttpUriResponse(getSystemId(ctx).toASCIIString(), response); } }