List of usage examples for org.springframework.http HttpHeaders set
@Override public void set(String headerName, @Nullable String headerValue)
From source file:net.longfalcon.newsj.service.TraktService.java
/** * call text search web service// w ww. j a v a 2 s .co m * @param name * @param type Possible values: movie , show , episode , person , list . * @return */ protected TraktResult[] searchByName(String name, String type) { try { String traktApiUrl = config.getTraktApiUrl(); String traktAppId = config.getTraktAppId(); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set("Content-type", "application/json"); httpHeaders.set("trakt-api-key", traktAppId); httpHeaders.set("trakt-api-version", "2"); HttpEntity<?> requestEntity = new HttpEntity(httpHeaders); UriComponents uriComponents = UriComponentsBuilder.fromUriString(traktApiUrl + "/search") .queryParam("query", name).queryParam("type", type).build(); ResponseEntity<TraktResult[]> responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.GET, requestEntity, TraktResult[].class); HttpStatus statusCode = responseEntity.getStatusCode(); if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) { return responseEntity.getBody(); } else { _log.error(String.format("Trakt Search request: \n%s\n failed with HTTP code %s : %s", uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase())); return null; } } catch (Exception e) { _log.error(e.toString(), e); } return null; }
From source file:net.longfalcon.newsj.service.TraktService.java
public TraktEpisodeResult getEpisode(long traktId, int season, int episode) { try {/*from w w w . j a v a 2s .c o m*/ String traktApiUrl = config.getTraktApiUrl(); String traktAppId = config.getTraktAppId(); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set("Content-type", "application/json"); httpHeaders.set("trakt-api-key", traktAppId); httpHeaders.set("trakt-api-version", "2"); HttpEntity<?> requestEntity = new HttpEntity(httpHeaders); UriComponents uriComponents = UriComponentsBuilder .fromUriString( traktApiUrl + "/shows/" + traktId + "/seasons/" + season + "/episodes/" + episode) .queryParam("extended", "full").build(); ResponseEntity<TraktEpisodeResult> responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.GET, requestEntity, TraktEpisodeResult.class); HttpStatus statusCode = responseEntity.getStatusCode(); if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) { return responseEntity.getBody(); } else { _log.error(String.format("Trakt Search request: \n%s\n failed with HTTP code %s : %s", uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase())); return null; } } catch (Exception e) { _log.error(e.toString(), e); } return null; }
From source file:org.apache.geode.management.internal.web.controllers.ShellCommandsController.java
private ResponseEntity<InputStreamResource> getJsonResponse(String result) { HttpHeaders respHeaders = new HttpHeaders(); try {/* w w w.j av a2 s. c o m*/ InputStreamResource isr = new InputStreamResource(toInputStream(result, "UTF-8")); respHeaders.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); return new ResponseEntity<>(isr, respHeaders, HttpStatus.OK); } catch (Exception e) { throw new RuntimeException("IO Error writing file to output stream", e); } }
From source file:org.apache.geode.management.internal.web.controllers.ShellCommandsController.java
private ResponseEntity<InputStreamResource> getFileDownloadResponse(CommandResult commandResult) { HttpHeaders respHeaders = new HttpHeaders(); Path filePath = commandResult.getFileToDownload(); try {/* ww w . j a v a 2 s .c om*/ InputStreamResource isr = new InputStreamResource(new FileInputStream(filePath.toFile())); respHeaders.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE); return new ResponseEntity<>(isr, respHeaders, HttpStatus.OK); } catch (Exception e) { throw new RuntimeException("IO Error writing file to output stream", e); } finally { FileUtils.deleteQuietly(filePath.toFile()); } }
From source file:org.apache.servicecomb.demo.springmvc.client.SpringmvcClient.java
public static void run() { testConfigurationDuplicate();/* w w w . j a v a 2 s. c o m*/ templateUrlWithServiceName.setRequestFactory(new UrlWithServiceNameClientHttpRequestFactory()); restTemplate = RestTemplateBuilder.create(); templateUrlWithProviderPrefix .setRequestFactory(new UrlWithProviderPrefixClientHttpRequestFactory("/pojo/rest")); controller = BeanUtils.getBean("controller"); String prefix = "cse://springmvc"; try { // this test class is intended for retry hanging issue JAV-127 templateUrlWithServiceName.getForObject(prefix + "/controller/sayhi?name=throwexception", String.class); TestMgr.check("true", "false"); } catch (Exception e) { TestMgr.check("true", "true"); } CodeFirstRestTemplateSpringmvc codeFirstClient = BeanUtils.getContext() .getBean(CodeFirstRestTemplateSpringmvc.class); codeFirstClient.testCodeFirst(restTemplate, "springmvc", "/codeFirstSpringmvc/"); codeFirstClient.testCodeFirst(templateUrlWithProviderPrefix, "springmvc", "/pojo/rest/codeFirstSpringmvc/"); String microserviceName = "springmvc"; for (String transport : DemoConst.transports) { CseContext.getInstance().getConsumerProviderManager().setTransport(microserviceName, transport); TestMgr.setMsg(microserviceName, transport); testController(templateUrlWithServiceName, microserviceName); testController(); testRequiredBody(templateUrlWithServiceName, microserviceName); testSpringMvcDefaultValues(templateUrlWithServiceName, microserviceName); testSpringMvcDefaultValuesJavaPrimitive(templateUrlWithServiceName, microserviceName); } HttpHeaders headers = new HttpHeaders(); headers.set("Accept-Encoding", "gzip"); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<String> entityCompress = restTemplate.exchange( prefix + "/codeFirstSpringmvc/sayhi/compressed/{name}/v2", HttpMethod.GET, entity, String.class, "Test"); TestMgr.check( "Test sayhi compressed:This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text,This is a big text!", entityCompress.getBody()); // if server response is compressed, the content-length header will be removed , so can't check this. // the transfer-encoding header will be missing when the server is set to not compressed if (entityCompress.getHeaders().get("transfer-encoding") != null) { TestMgr.check("chunked", entityCompress.getHeaders().get("transfer-encoding").get(0)); } //0.5.0 later version metrics integration test @SuppressWarnings("unchecked") Map<String, Double> metrics = restTemplate.getForObject(prefix + "/metrics", Map.class); // TestMgr.check(true, metrics.get("jvm(name=heapUsed,statistic=gauge)") != 0); TestMgr.check(true, metrics.size() > 0); TestMgr.check(true, metrics.get( "servicecomb.invocation(operation=springmvc.codeFirst.saySomething,role=PRODUCER,stage=total,statistic=count,status=200,transport=highway)") >= 0); //prometheus integration test try { String content = restTemplate.getForObject("cse://springmvc/codeFirstSpringmvc/prometheusForTest", String.class); TestMgr.check(true, content.contains("servicecomb_invocation{operation=\"springmvc.codeFirst.addDate")); TestMgr.check(true, content.contains("servicecomb_invocation{operation=\"springmvc.codeFirst.sayHello")); TestMgr.check(true, content.contains("servicecomb_invocation{operation=\"springmvc.codeFirst.fallbackFromCache")); TestMgr.check(true, content.contains("servicecomb_invocation{operation=\"springmvc.codeFirst.isTrue")); TestMgr.check(true, content.contains("servicecomb_invocation{operation=\"springmvc.codeFirst.add")); TestMgr.check(true, content.contains("servicecomb_invocation{operation=\"springmvc.codeFirst.sayHi2")); TestMgr.check(true, content.contains("servicecomb_invocation{operation=\"springmvc.codeFirst.saySomething")); String[] metricLines = content.split("\n"); if (metricLines.length > 0) { for (String metricLine : metricLines) { if (!metricLine.startsWith("#")) { String[] metricKeyAndValue = metricLine.split(" "); if (!metricKeyAndValue[0].startsWith("jvm")) { if (Double.parseDouble(metricKeyAndValue[1]) < 0) { TestMgr.check("true", "false"); break; } } } } } else { TestMgr.check("true", "false"); } } catch (Exception e) { TestMgr.check("true", "false"); } }
From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java
@Test public void ableToSetCustomHeader() { HttpHeaders headers = new HttpHeaders(); headers.set("name", "world"); HttpEntity<?> requestEntity = new HttpEntity<>(headers); ResponseEntity<String> result = restTemplate.exchange(controllerUrl + "sayhei", GET, requestEntity, String.class); assertThat(jsonOf(result.getBody(), String.class), is("hei world")); ListenableFuture<ResponseEntity<String>> listenableFuture = asyncRestTemplate .exchange(controllerUrl + "sayhei", GET, requestEntity, String.class); // ResponseEntity<String> responseEntity = listenableFuture.get(); listenableFuture.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() { @Override/*from ww w .j a v a 2 s .c o m*/ public void onFailure(Throwable ex) { } @Override public void onSuccess(ResponseEntity<String> result) { assertThat(jsonOf(result.getBody(), String.class), is("hei world")); } }); }
From source file:org.cloudfoundry.identity.uaa.api.common.impl.UaaConnectionHelper.java
/** * Do an HTTP PUT with SCIM features. SCIM requires PUT requests of a SCIM object have the version of the object set * as the <code>If-Match</code> request header. * * @param uri the URI of the endpoint (relative to the base URL set in the constructor) * @param body the request body//from ww w.j a v a 2 s .co m * @param responseType the object type to be returned * @param uriVariables any uri variables * @return the response body * @see #exchange(HttpMethod, HttpHeaders, Object, String, ParameterizedTypeReference, Object...) */ public <RequestType extends ScimCore, ResponseType> ResponseType putScimObject(String uri, RequestType body, ParameterizedTypeReference<ResponseType> responseType, Object... uriVariables) { HttpHeaders headers = new HttpHeaders(); headers.set("if-match", String.valueOf(body.getMeta().getVersion())); return exchange(HttpMethod.PUT, headers, body, uri, responseType, uriVariables); }
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(/* www . ja va2 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:org.cloudfoundry.identity.uaa.integration.CheckTokenEndpointIntegrationTests.java
@Test public void testTokenKey() { HttpHeaders headers = new HttpHeaders(); ClientCredentialsResourceDetails resource = testAccounts.getClientCredentialsResource("app", null, "app", "appclientsecret"); headers.set("Authorization", testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret())); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); @SuppressWarnings("rawtypes") ResponseEntity<Map> response = serverRunning.getForObject("/token_key", Map.class, headers); assertEquals(HttpStatus.OK, response.getStatusCode()); @SuppressWarnings("unchecked") Map<String, String> map = response.getBody(); assertNotNull(map.get("alg")); assertNotNull(map.get("value")); }
From source file:org.cloudfoundry.identity.uaa.integration.CheckTokenEndpointIntegrationTests.java
@Test public void testForbidden() throws Exception { MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("token", "FOO"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Basic " + new String(Base64.encode("cf:".getBytes("UTF-8")))); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); @SuppressWarnings("rawtypes") ResponseEntity<Map> response = serverRunning.postForMap("/check_token", formData, headers); assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); @SuppressWarnings("unchecked") Map<String, String> map = response.getBody(); assertTrue(map.containsKey("error")); }