List of usage examples for org.springframework.http HttpHeaders set
@Override public void set(String headerName, @Nullable String headerValue)
From source file:io.github.microcks.web.ResourceController.java
@RequestMapping(value = "/resources/{serviceId}/{resourceType}", method = RequestMethod.GET) public ResponseEntity<byte[]> getServiceResource(@PathVariable("serviceId") String serviceId, @PathVariable("resourceType") String resourceType, HttpServletResponse response) { log.info("Requesting {} resource for service {}", resourceType, serviceId); Service service = serviceRepository.findOne(serviceId); if (service != null && ServiceType.GENERIC_REST.equals(service.getType())) { // Prepare HttpHeaders. InputStream stream = null; String resource = findResource(service); HttpHeaders headers = new HttpHeaders(); // Get the correct template depending on resource type. if (SWAGGER_20.equals(resourceType)) { org.springframework.core.io.Resource template = new ClassPathResource("templates/swagger-2.0.json"); try { stream = template.getInputStream(); } catch (IOException e) { log.error("IOException while reading swagger-2.0.json template", e); }//from w ww . j a v a2 s . c om headers.setContentType(MediaType.APPLICATION_JSON); } else if (OPENAPI_30.equals(resourceType)) { org.springframework.core.io.Resource template = new ClassPathResource("templates/openapi-3.0.yaml"); try { stream = template.getInputStream(); } catch (IOException e) { log.error("IOException while reading openapi-3.0.yaml template", e); } headers.set("Content-Type", "text/yaml"); } // Now process the stream, replacing patterns by value. if (stream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringWriter writer = new StringWriter(); try (Stream<String> lines = reader.lines()) { lines.map(line -> replaceInLine(line, service, resource)) .forEach(line -> writer.write(line + "\n")); } return new ResponseEntity<>(writer.toString().getBytes(), headers, HttpStatus.OK); } } return new ResponseEntity<>(HttpStatus.BAD_REQUEST); }
From source file:com.blogspot.sgdev.blog.GrantByAuthorizationCodeProviderTest.java
@Test public void getJwtTokenByAuthorizationCode() throws JsonParseException, JsonMappingException, IOException, URISyntaxException { String redirectUrl = "http://localhost:" + port + "/resources/user"; ResponseEntity<String> response = new TestRestTemplate("user", "password").postForEntity( "http://localhost:" + port + "/oauth/authorize?response_type=code&client_id=normal-app&redirect_uri={redirectUrl}", null, String.class, redirectUrl); assertEquals(HttpStatus.OK, response.getStatusCode()); List<String> setCookie = response.getHeaders().get("Set-Cookie"); String jSessionIdCookie = setCookie.get(0); String cookieValue = jSessionIdCookie.split(";")[0]; HttpHeaders headers = new HttpHeaders(); headers.add("Cookie", cookieValue); response = new TestRestTemplate("user", "password").postForEntity("http://localhost:" + port + "oauth/authorize?response_type=code&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize", new HttpEntity<Void>(headers), String.class, redirectUrl); assertEquals(HttpStatus.FOUND, response.getStatusCode()); assertNull(response.getBody());//w w w . j a v a 2s . c om String location = response.getHeaders().get("Location").get(0); URI locationURI = new URI(location); String query = locationURI.getQuery(); location = "http://localhost:" + port + "/oauth/token?" + query + "&grant_type=authorization_code&client_id=normal-app&redirect_uri={redirectUrl}"; response = new TestRestTemplate("normal-app", "").postForEntity(location, new HttpEntity<Void>(new HttpHeaders()), String.class, redirectUrl); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(response.getBody(), HashMap.class); String accessToken = (String) jwtMap.get("access_token"); headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + accessToken); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/client", HttpMethod.GET, new HttpEntity<String>(null, headers), String.class); assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/user", HttpMethod.GET, new HttpEntity<String>(null, headers), String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<String>(null, headers), String.class); assertEquals("user", response.getBody()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<String>(null, headers), String.class); assertEquals("[{\"authority\":\"ROLE_USER\"}]", response.getBody()); }
From source file:org.cloudfoundry.identity.uaa.login.feature.OpenIdTokenGrantsIT.java
private void doOpenIdHybridFlowIdTokenAndCode(Set<String> responseTypes, String responseTypeMatcher) throws Exception { HttpHeaders headers = new HttpHeaders(); // TODO: should be able to handle just TEXT_HTML headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL)); StringBuilder responseType = new StringBuilder(); Iterator<String> rTypes = responseTypes.iterator(); while (rTypes.hasNext()) { String type = rTypes.next(); responseType.append(type);/*from w w w. jav a2 s .c o m*/ if (rTypes.hasNext()) { responseType.append(" "); } } String state = new RandomValueStringGenerator().generate(); String clientId = "app"; String clientSecret = "appclientsecret"; String redirectUri = "http://anywhere.com"; String uri = loginUrl + "/oauth/authorize?response_type={response_type}&" + "state={state}&client_id={client_id}&redirect_uri={redirect_uri}"; ResponseEntity<Void> result = restOperations.exchange(uri, HttpMethod.GET, new HttpEntity<>(null, headers), Void.class, responseType, state, clientId, redirectUri); assertEquals(HttpStatus.FOUND, result.getStatusCode()); String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8"); if (result.getHeaders().containsKey("Set-Cookie")) { String cookie = result.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); } ResponseEntity<String> response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); // should be directed to the login screen... assertTrue(response.getBody().contains("/login.do")); assertTrue(response.getBody().contains("username")); assertTrue(response.getBody().contains("password")); MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", user.getUserName()); formData.add("password", "secret"); // Should be redirected to the original URL, but now authenticated result = restOperations.exchange(loginUrl + "/login.do", HttpMethod.POST, new HttpEntity<>(formData, headers), Void.class); assertEquals(HttpStatus.FOUND, result.getStatusCode()); if (result.getHeaders().containsKey("Set-Cookie")) { String cookie = result.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); } location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8"); response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); if (response.getStatusCode() == HttpStatus.OK) { // The grant access page should be returned assertTrue(response.getBody().contains("You can change your approval of permissions")); formData.clear(); formData.add("user_oauth_approval", "true"); result = restOperations.exchange(loginUrl + "/oauth/authorize", HttpMethod.POST, new HttpEntity<>(formData, headers), Void.class); assertEquals(HttpStatus.FOUND, result.getStatusCode()); location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8"); } else { // Token cached so no need for second approval assertEquals(HttpStatus.FOUND, response.getStatusCode()); location = UriUtils.decode(response.getHeaders().getLocation().toString(), "UTF-8"); } assertTrue("Wrong location: " + location, location.matches(redirectUri + responseTypeMatcher.toString())); formData.clear(); formData.add("client_id", clientId); formData.add("redirect_uri", redirectUri); formData.add("grant_type", "authorization_code"); formData.add("code", location.split("code=")[1].split("&")[0]); HttpHeaders tokenHeaders = new HttpHeaders(); String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes())); tokenHeaders.set("Authorization", basicDigestHeaderValue); @SuppressWarnings("rawtypes") ResponseEntity<Map> tokenResponse = restOperations.exchange(loginUrl + "/oauth/token", HttpMethod.POST, new HttpEntity<>(formData, tokenHeaders), Map.class); 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:org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.java
private String doGetFileByRange(String urlPath, Object app, String instance, String filePath, int start, int end, String range) { boolean supportsRanges; try {/*from w ww . java 2s. c o m*/ supportsRanges = getRestTemplate().execute(getUrl(urlPath), HttpMethod.HEAD, new RequestCallback() { public void doWithRequest(ClientHttpRequest request) throws IOException { request.getHeaders().set("Range", "bytes=0-"); } }, new ResponseExtractor<Boolean>() { public Boolean extractData(ClientHttpResponse response) throws IOException { return response.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT); } }, app, instance, filePath); } catch (CloudFoundryException e) { if (e.getStatusCode().equals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)) { // must be a 0 byte file return ""; } else { throw e; } } HttpHeaders headers = new HttpHeaders(); if (supportsRanges) { headers.set("Range", range); } HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers); ResponseEntity<String> responseEntity = getRestTemplate().exchange(getUrl(urlPath), HttpMethod.GET, requestEntity, String.class, app, instance, filePath); String response = responseEntity.getBody(); boolean partialFile = false; if (responseEntity.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT)) { partialFile = true; } if (!partialFile && response != null) { if (start == -1) { return response.substring(response.length() - end); } else { if (start >= response.length()) { if (response.length() == 0) { return ""; } throw new CloudFoundryException(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE, "The starting position " + start + " is past the end of the file content."); } if (end != -1) { if (end >= response.length()) { end = response.length() - 1; } return response.substring(start, end + 1); } else { return response.substring(start); } } } return response; }
From source file:net.paslavsky.springrest.HttpHeadersHelper.java
public HttpHeaders getHttpHeaders(Map<String, Integer> headerParameters, Object[] arguments) { HttpHeaders headers = new HttpHeaders(); for (String headerName : headerParameters.keySet()) { Object headerValue = arguments[headerParameters.get(headerName)]; if (headerValue != null) { if (ACCEPT.equalsIgnoreCase(headerName)) { headers.setAccept(toList(headerValue, MediaType.class)); } else if (ACCEPT_CHARSET.equalsIgnoreCase(headerName)) { headers.setAcceptCharset(toList(headerValue, Charset.class)); } else if (ALLOW.equalsIgnoreCase(headerName)) { headers.setAllow(toSet(headerValue, HttpMethod.class)); } else if (CONNECTION.equalsIgnoreCase(headerName)) { headers.setConnection(toList(headerValue, String.class)); } else if (CONTENT_DISPOSITION.equalsIgnoreCase(headerName)) { setContentDisposition(headers, headerName, headerValue); } else if (CONTENT_LENGTH.equalsIgnoreCase(headerName)) { headers.setContentLength(toLong(headerValue)); } else if (CONTENT_TYPE.equalsIgnoreCase(headerName)) { headers.setContentType(toMediaType(headerValue)); } else if (DATE.equalsIgnoreCase(headerName)) { headers.setDate(toLong(headerValue)); } else if (ETAG.equalsIgnoreCase(headerName)) { headers.setETag(toString(headerValue)); } else if (EXPIRES.equalsIgnoreCase(headerName)) { headers.setExpires(toLong(headerValue)); } else if (IF_MODIFIED_SINCE.equalsIgnoreCase(headerName)) { headers.setIfModifiedSince(toLong(headerValue)); } else if (IF_NONE_MATCH.equalsIgnoreCase(headerName)) { headers.setIfNoneMatch(toList(headerValue, String.class)); } else if (LAST_MODIFIED.equalsIgnoreCase(headerName)) { headers.setLastModified(toLong(headerValue)); } else if (LOCATION.equalsIgnoreCase(headerName)) { headers.setLocation(toURI(headerValue)); } else if (ORIGIN.equalsIgnoreCase(headerName)) { headers.setOrigin(toString(headerValue)); } else if (PRAGMA.equalsIgnoreCase(headerName)) { headers.setPragma(toString(headerValue)); } else if (UPGRADE.equalsIgnoreCase(headerName)) { headers.setUpgrade(toString(headerValue)); } else if (headerValue instanceof String) { headers.set(headerName, (String) headerValue); } else if (headerValue instanceof String[]) { headers.put(headerName, Arrays.asList((String[]) headerValue)); } else if (instanceOf(headerValue, String.class)) { headers.put(headerName, toList(headerValue, String.class)); } else { headers.set(headerName, conversionService.convert(headerValue, String.class)); }/*from ww w.ja v a 2 s .c o m*/ } } return headers; }
From source file:com.jci.po.service.PoServiceImpl.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//from ww w . ja v a 2s.co m public BatchUpdateRes processErrorPos(PoDetailsReq request) throws InvalidKeyException, URISyntaxException, StorageException { LOG.info("starting processErrorPos request--->" + request); BatchUpdateRes res = new BatchUpdateRes(); String partitionKey = AzureUtils.getPoPartitionKey(request.getErpName()); BatchUpdateRes response = new BatchUpdateRes(); if (StringUtils.isBlank(partitionKey)) { res.setError(true); res.setMessage("Invalid request parameters !"); return res; } List<String> poList = request.getPoNo(); if (poList == null || poList.size() < 1) { res.setError(true); res.setMessage("Invalid request parameters !"); return res; } List<ServiceInstance> ffmsInstanceList = discoveryClient.getInstances(ffgenerationMSName); ServiceInstance ffmsInstance = ffmsInstanceList.get(0); LOG.info("Before calling from Flat File Generation Service: " + "http://" + ffmsInstance.getServiceId().toLowerCase() + ":" + Integer.toString(ffmsInstance.getPort()) + poPostURLResource + "?userName=" + request.getUserName() + "&globalId=" + request.getGlobalId() + "&comment=" + request.getComment()); // start new HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/json"); /* * Map<String, String> params = new HashMap<String, String>(); * params.put("userName", request.getUserName()); params.put("globalId", * request.getGlobalId()); params.put("comment", request.getComment()); */ HttpEntity entity = new HttpEntity(poList, headers); /* * HttpEntity<HashMap<String, String>> ffResponse = * restTemplate.exchange( * "http://api-gateway:8765/ffgenerator-service/postPOError", * HttpMethod.POST, entity, new * ParameterizedTypeReference<HashMap<String, String>>() { }); */ /* * HttpEntity<HashMap<String, String>> ffResponse = * restTemplate.exchange( * "http://ffgenerator-service:9200/postPOError?userName=" + * request.getUserName() + "&globalId=" + request.getGlobalId() + * "&comment=" + request.getComment(), HttpMethod.POST, entity, new * ParameterizedTypeReference<HashMap<String, String>>() { }); */ HttpEntity<FlatFileRes> ffResponse = restTemplate.exchange( "http://" + ffmsInstance.getServiceId().toLowerCase() + ":" + Integer.toString(ffmsInstance.getPort()) + poPostURLResource + "?userName=" + request.getUserName() + "&globalId=" + request.getGlobalId() + "&comment=" + request.getComment(), HttpMethod.POST, entity, new ParameterizedTypeReference<FlatFileRes>() { }); // client.processErrorPosFlatFiles(poList); FlatFileRes ffPos = ffResponse.getBody(); /*// Update status in DB boolean isUpdated = updateStatus(pkToSuccessList, request.getGlobalId(), request.getUserName(), request.getComment());*/ response = new BatchUpdateRes(); response.setGraphData(repo.getGraphData()); response.setSuccessList(ffPos.getSuccessList()); response.setErrorList(ffPos.getErrorList()); return response; }
From source file:de.appsolve.padelcampus.admin.controller.mail.AdminMailController.java
@RequestMapping(value = "export", method = POST) public HttpEntity<byte[]> exportEmails(@ModelAttribute("Model") Mail mail) { List<String> emails = new ArrayList<>(); for (EmailContact player : mail.getRecipients()) { emails.add(player.getEmailAddress()); }// ww w . jav a 2 s.c o m byte[] data = StringUtils.join(emails, ",").getBytes(StandardCharsets.UTF_8); HttpHeaders header = new HttpHeaders(); header.setContentType(new MediaType("text", "csv")); header.set("Content-Disposition", "attachment; filename=email-export.csv"); header.setContentLength(data.length); return new HttpEntity<>(data, header); }