List of usage examples for org.springframework.http HttpHeaders setAccept
public void setAccept(List<MediaType> acceptableMediaTypes)
From source file:org.cloudfoundry.identity.uaa.integration.AuthorizationCodeGrantIntegrationTests.java
@Test public void testSuccessfulAuthorizationCodeFlow() throws Exception { HttpHeaders headers = new HttpHeaders(); // TODO: should be able to handle just TEXT_HTML headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL)); AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource(); 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(), headers); assertEquals(HttpStatus.FOUND, result.getStatusCode()); String location = result.getHeaders().getLocation().toString(); if (result.getHeaders().containsKey("Set-Cookie")) { String cookie = result.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); }/* w ww .ja v a 2 s .com*/ ResponseEntity<String> response = serverRunning.getForString(location, headers); // should be directed to the login screen... assertTrue(response.getBody().contains("/login.do")); assertTrue(response.getBody().contains("auth_key")); assertTrue(response.getBody().contains("password")); MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("auth_key", testAccounts.getUserName()); formData.add("password", testAccounts.getPassword()); // Should be redirected to the original URL, but now authenticated result = serverRunning.postForResponse("/login.do", headers, formData); assertEquals(HttpStatus.FOUND, result.getStatusCode()); if (result.getHeaders().containsKey("Set-Cookie")) { String cookie = result.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); } response = serverRunning.getForString(result.getHeaders().getLocation().toString(), headers); if (response.getStatusCode() == HttpStatus.OK) { // The grant access page should be returned assertTrue(response.getBody().contains("Do you authorize")); formData.clear(); formData.add("user_oauth_approval", "true"); result = serverRunning.postForResponse("/oauth/authorize", headers, 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", "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") Map<String, String> body = tokenResponse.getBody(); Jwt token = JwtHelper.decode(body.get("access_token")); assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\"")); assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\"")); }
From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.FetchReservationsToDate.java
/** * Method, where all reservations to specified date are read from server. * All heavy lifting is made here./*from www . j av a2s .c om*/ * * @param params only one TimeContainer parameter is allowed here - specifies day, month and year * @return list of fetched reservations */ @Override protected List<Reservation> doInBackground(TimeContainer... params) { SharedPreferences credentials = getCredentials(); String username = credentials.getString("username", null); String password = credentials.getString("password", null); String url = credentials.getString("url", null) + Values.SERVICE_RESERVATION; if (params.length == 1) { TimeContainer time = params[0]; url = url + time.getDay() + "-" + time.getMonth() + "-" + time.getYear(); } else { Log.e(TAG, "Invalid params count! There must be one TimeContainer instance"); setState(ERROR, "Invalid params count! There must be one TimeContainer instance"); return Collections.emptyList(); } setState(RUNNING, R.string.working_ws_msg); // Populate the HTTP Basic Authentication header with the username and // password HttpAuthentication authHeader = new HttpBasicAuthentication(username, password); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAuthorization(authHeader); requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML)); SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory(); // Create a new RestTemplate instance RestTemplate restTemplate = new RestTemplate(factory); restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter()); try { // Make the network request Log.d(TAG, url); ResponseEntity<ReservationList> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), ReservationList.class); ReservationList body = response.getBody(); if (body != null) { return body.getReservations(); } } catch (Exception e) { Log.e(TAG, e.getLocalizedMessage(), e); setState(ERROR, e); } finally { setState(DONE); } return Collections.emptyList(); }
From source file:org.cloudfoundry.identity.uaa.login.integration.AuthorizationCodeGrantIntegrationTests.java
@Test public void testSuccessfulAuthorizationCodeFlow() throws Exception { HttpHeaders headers = new HttpHeaders(); // TODO: should be able to handle just TEXT_HTML headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL)); AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource(); 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(), headers); assertEquals(HttpStatus.FOUND, result.getStatusCode()); String location = result.getHeaders().getLocation().toString(); if (result.getHeaders().containsKey("Set-Cookie")) { String cookie = result.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); }/*ww w .j a v a2 s . c o m*/ ResponseEntity<String> response = serverRunning.getForString(location, headers); // should be directed to the login screen... String body = response.getBody(); assertTrue(body.contains("/login.do")); assertTrue(body.contains("username")); assertTrue(body.contains("password")); MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("username", testAccounts.getUserName()); formData.add("password", testAccounts.getPassword()); // Should be redirected to the original URL, but now authenticated result = serverRunning.postForResponse("/login.do", headers, formData); assertEquals(HttpStatus.FOUND, result.getStatusCode()); if (result.getHeaders().containsKey("Set-Cookie")) { String cookie = result.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); } response = serverRunning.getForString(result.getHeaders().getLocation().toString(), headers); if (response.getStatusCode() == HttpStatus.OK) { body = response.getBody(); // The grant access page should be returned assertTrue(body.contains("Application Authorization")); // Forms should have the right action assertTrue(body.matches("(?s).*\\saction=\"\\S*oauth/authorize\".*")); formData.clear(); formData.add("user_oauth_approval", "true"); result = serverRunning.postForResponse("/oauth/authorize", headers, 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=.+")); assertFalse("Location should not contain cookie: " + location, location.matches(resource.getPreEstablishedRedirectUri() + ".*cookie=.+")); formData.clear(); formData.add("client_id", resource.getClientId()); formData.add("redirect_uri", resource.getPreEstablishedRedirectUri()); formData.add("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()); }
From source file:cz.muni.fi.mushroomhunter.restclient.LocationCreateSwingWorker.java
@Override protected Void doInBackground() throws Exception { LocationDto locationDto = new LocationDto(); locationDto.setName(restClient.getTfLocationName().getText()); locationDto.setDescription(restClient.getTfLocationDescription().getText()); locationDto.setNearCity(restClient.getTfLocationNearCity().getText()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); List<MediaType> mediaTypeList = new ArrayList<>(); mediaTypeList.add(MediaType.ALL);//from w ww .j a va2 s .com headers.setAccept(mediaTypeList); ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(locationDto); RestTemplate restTemplate = new RestTemplate(); String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD; byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); headers.add("Authorization", "Basic " + base64Creds); HttpEntity request = new HttpEntity(json, headers); Long[] result = restTemplate.postForObject(RestClient.SERVER_URL + "pa165/rest/location", request, Long[].class); RestClient.getLocationIDs().add(result[0]); return null; }
From source file:com.github.ibm.domino.client.BaseClient.java
protected HttpEntity<String> getHttpEntity() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM)); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(headers); }
From source file:spring.AbstractAuthorizationCodeProviderTests.java
@Test @Ignore("TODO")/*from ww w . ja va 2s.c o m*/ public void testInvalidScopeInAuthorizationRequest() throws Exception { HttpHeaders headers = getAuthenticatedHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); String scope = "bogus"; String redirectUri = "http://anywhere?key=value"; String clientId = "my-client-with-registered-redirect"; UriBuilder uri = http.buildUri(authorizePath()).queryParam("response_type", "code") .queryParam("state", "mystateid").queryParam("scope", scope); if (clientId != null) { uri.queryParam("client_id", clientId); } if (redirectUri != null) { uri.queryParam("redirect_uri", redirectUri); } ResponseEntity<String> response = http.getForString(uri.pattern(), headers, uri.params()); assertEquals(HttpStatus.FOUND, response.getStatusCode()); String location = response.getHeaders().getLocation().toString(); assertTrue(location.startsWith("http://anywhere")); assertTrue(location.contains("error=invalid_scope")); assertFalse(location.contains("redirect_uri=")); }
From source file:org.cloudfoundry.identity.uaa.integration.ClientAdminEndpointsIntegrationTests.java
public HttpHeaders getAuthenticatedHeaders(OAuth2AccessToken token) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", "Bearer " + token.getValue()); return headers; }
From source file:org.cloudfoundry.identity.uaa.integration.ClientInfoEndpointIntegrationTests.java
@Test public void testImplicitClientInfo() throws Exception { HttpHeaders headers = new HttpHeaders(); ImplicitResourceDetails app = testAccounts.getDefaultImplicitResource(); headers.set("Authorization", testAccounts.getAuthorizationHeader(app.getClientId(), "")); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); @SuppressWarnings("rawtypes") ResponseEntity<Map> response = serverRunning.getForObject("/clientinfo", Map.class, headers); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals(app.getClientId(), response.getBody().get("client_id")); }
From source file:org.cloudfoundry.identity.uaa.integration.NativeApplicationIntegrationTests.java
/** * tests a happy-day flow of the Resource Owner Password Credentials grant type. (formerly native application * profile)./*w w w. j a v a 2 s . c o m*/ */ @Test public void testHappyDay() throws Exception { MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("grant_type", "password"); formData.add("username", resource.getUsername()); formData.add("password", resource.getPassword()); formData.add("scope", "cloud_controller.read"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret())); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); ResponseEntity<String> response = serverRunning.postForString("/oauth/token", formData, headers); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals("no-store", response.getHeaders().getFirst("Cache-Control")); }
From source file:cz.muni.fi.mushroomhunter.restclient.LocationUpdateSwingWorker.java
@Override protected Integer doInBackground() throws Exception { DefaultTableModel model = (DefaultTableModel) restClient.getTblLocation().getModel(); int selectedRow = restClient.getTblLocation().getSelectedRow(); String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD; byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); List<MediaType> mediaTypeList = new ArrayList<>(); mediaTypeList.add(MediaType.ALL);//from w w w. j a v a2s . c om headers.setAccept(mediaTypeList); headers.add("Authorization", "Basic " + base64Creds); HttpEntity request = new HttpEntity<>(headers); ResponseEntity<LocationDto> responseEntity = restTemplate.exchange( RestClient.SERVER_URL + "pa165/rest/location/" + RestClient.getLocationIDs().get(selectedRow), HttpMethod.GET, request, LocationDto.class); LocationDto locationDto = responseEntity.getBody(); locationDto.setName(restClient.getTfLocationName().getText()); locationDto.setDescription(restClient.getTfLocationDescription().getText()); locationDto.setNearCity(restClient.getTfLocationNearCity().getText()); ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(locationDto); request = new HttpEntity(json, headers); restTemplate.exchange(RestClient.SERVER_URL + "pa165/rest/location", HttpMethod.PUT, request, LocationDto.class); return selectedRow; }