private String getKeyFromConfigServer(RestTemplate keyUriRestTemplate) throws CertificateException { // Load available UAA servers discoveryClient.getServices(); HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders()); String content = keyUriRestTemplate .exchange("http://config/api/token_key", HttpMethod.GET, request, String.class).getBody(); if (StringUtils.isBlank(content)) { throw new CertificateException("Received empty certificate from config."); } InputStream fin = new ByteArrayInputStream(content.getBytes()); CertificateFactory f = CertificateFactory.getInstance(Constants.CERTIFICATE); X509Certificate certificate = (X509Certificate)f.generateCertificate(fin); PublicKey pk = certificate.getPublicKey(); return String.format(Constants.PUBLIC_KEY, new String(Base64.encode(pk.getEncoded()))); }
/** * Endpoint to transform an uploaded file into a valid or error json response * * @return Valid json or error json content */ @GetMapping(value = "/unprocessed-files", headers = {"Accept=" + Constants.V1_API_ACCEPT}) public ResponseEntity<List<UnprocessedCpcFileData>> getUnprocessedCpcPlusFiles() { API_LOG.info("CPC+ unprocessed files request received"); if (blockCpcPlusApi()) { API_LOG.info(BLOCKED_BY_FEATURE_FLAG); return new ResponseEntity<>(null, null, HttpStatus.FORBIDDEN); } List<UnprocessedCpcFileData> unprocessedCpcFileDataList = cpcFileService.getUnprocessedCpcPlusFiles(); API_LOG.info("CPC+ unprocessed files request succeeded"); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); return new ResponseEntity<>(unprocessedCpcFileDataList, httpHeaders, HttpStatus.OK); }
/** * Exemple : * curl -v -X GET -H "Content-Type: application/json" 'http://localhost:8080/wsrest/nfc/cnousCardId?authToken=123456&csn=123456789abcde' */ @RequestMapping(value = "/cnousCardId", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") @ResponseBody public ResponseEntity<Long> getCnousCardId(@RequestParam String authToken, @RequestParam String csn) { log.debug("getCnousCardId with csn = " + csn); HttpHeaders responseHeaders = new HttpHeaders(); String eppnInit = clientJWSController.getEppnInit(authToken); if(eppnInit == null) { log.info("Bad authotoken : " + authToken); return new ResponseEntity<Long>(new Long(-1), responseHeaders, HttpStatus.FORBIDDEN); } Card card = Card.findCardsByCsn(csn).getSingleResult(); String cnousCardId = cardIdsService.generateCardId(card.getId(), "crous"); log.debug("cnousCardId for csn " + csn + " = " + cnousCardId); return new ResponseEntity<Long>(Long.valueOf(cnousCardId), responseHeaders, HttpStatus.OK); }
private void assertRequestHeaders(HttpHeaders actualHeaders, Object requestObject, Map<String, Matcher<? super List<String>>> additionalExpectedHeaders) { Map<String, Matcher<? super List<String>>> expectedHeaders = new HashMap<>(); if (requestObject != null && requestObject instanceof HttpEntity) { HttpEntity httpEntity = (HttpEntity) requestObject; HttpHeaders headers = httpEntity.getHeaders(); Map<String, Matcher<List<String>>> stringMatcherMap = Maps.transformValues(headers, new Function<List<String>, Matcher<List<String>>>() { @Override public Matcher<List<String>> apply(List<String> input) { return is(input); } }); expectedHeaders.putAll(stringMatcherMap); } expectedHeaders.putAll(additionalExpectedHeaders); Set<String> headerNames = expectedHeaders.keySet(); for (String headerName : headerNames) { Matcher<? super List<String>> headerValuesMatcher = expectedHeaders.get(headerName); assertThat(format("Contains header %s", headerName), actualHeaders.containsKey(headerName), is(true)); assertThat(format("'%s' header value fails assertion", headerName), actualHeaders.get(headerName), headerValuesMatcher); } }
@Override public boolean createNewUser(String u, String p) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ObjectMapper mapper=ObjectMapperPool.getMapper(); String json=""; try { json = mapper.writeValueAsString(new LoginRequest(u, p, fingerPrint.getFingerPrint())); HttpEntity<String> entity = new HttpEntity<String>(json, headers); ResponseEntity<String> response=restTemplate.postForEntity(serverPath.concat(Constants.CREATE_USER_SUFFIX), entity, String.class); CreateUserResponse resp=mapper.readValue(response.getBody(), CreateUserResponse.class); logger.debug("Got create user response {}",resp.getStatus()); return resp.isResult(); } catch (Exception e) { logger.error("Parse exception", e); } return false; }
public Mono<User> callSSOProvider(String accessToken, SSOProvider ssoProvider) { SSOProperties.SSOValues keys = ssoProperties.getProviders().get(ssoProvider); return WebClient.builder() .build() .get() .uri(keys.getProfileUrl()) .header(HttpHeaders.AUTHORIZATION, OAuth2AccessToken.BEARER_TYPE + " " + accessToken) .exchange() .flatMap(resp -> resp.bodyToMono(Map.class)) .flatMap(body -> { if(Integer.valueOf(401).equals(body.get("status"))){ return Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED, body.get("message").toString())); } else { return Mono.just(body); } }) .map(values -> new TokenService.UserSSO(values, keys)) .map(userSSO -> { User user = new User(); user.setIdSSO(ssoProvider.toString() + "#" + userSSO.id); user.setFirstName(userSSO.firstName); user.setLastName(userSSO.lastName); return user; }); }
/** * * * <p><b>200</b> - Success * @param model The model parameter * @throws RestClientException if an error occurs while attempting to invoke the API */ public void apiAuthorizationLoginPost(LoginModel model) throws RestClientException { Object postBody = model; String path = UriComponentsBuilder.fromPath("/api/authorization/login").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { "application/json-patch+json", "application/json", "text/json", "application/_*+json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); }
@ApiOperation(value = "getOrganisationByName", nickname = "getOrganisationByName") @RequestMapping(value = "/CISConnector/getOrganisationByName/{organisation}", method = RequestMethod.GET) @ApiImplicitParams({ @ApiImplicitParam(name = "organisation", value = "the Organisation name", required = true, dataType = "String", paramType = "path") }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = ResponseEntity.class), @ApiResponse(code = 400, message = "Bad Request", response = ResponseEntity.class), @ApiResponse(code = 500, message = "Failure", response = ResponseEntity.class)}) public ResponseEntity<Organisation> getOrganisationByName(@PathVariable String organisation) throws CISCommunicationException { log.info("--> getOrganisationByName: " + organisation); Organisation organisationRes = null; try { organisationRes = connector.getOrganisationByName(organisation); } catch (CISCommunicationException e) { log.error("Error executing the request: Communication Error" , e); organisationRes = null; } HttpHeaders responseHeaders = new HttpHeaders(); log.info("getOrganisationByName -->"); return new ResponseEntity<Organisation>(organisationRes, responseHeaders, HttpStatus.OK); }
@Override public Map<String, String> getSecurityQuestions(final String username) { final PasswordManagementProperties.Rest rest = passwordManagementProperties.getRest(); if (StringUtils.isBlank(rest.getEndpointUrlSecurityQuestions())) { return null; } final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.put("username", Arrays.asList(username)); final HttpEntity<String> entity = new HttpEntity<>(headers); final ResponseEntity<Map> result = restTemplate.exchange(rest.getEndpointUrlSecurityQuestions(), HttpMethod.GET, entity, Map.class); if (result.getStatusCodeValue() == HttpStatus.OK.value() && result.hasBody()) { return result.getBody(); } return null; }
public static HttpHeaders generatePaginationHttpHeaders(Page page, String baseUrl) { HttpHeaders headers = new HttpHeaders(); headers.add("X-Total-Count", Long.toString(page.getTotalElements())); String link = ""; if ((page.getNumber() + 1) < page.getTotalPages()) { link = "<" + generateUri(baseUrl, page.getNumber() + 1, page.getSize()) + ">; rel=\"next\","; } // prev link if ((page.getNumber()) > 0) { link += "<" + generateUri(baseUrl, page.getNumber() - 1, page.getSize()) + ">; rel=\"prev\","; } // last and first link int lastPage = 0; if (page.getTotalPages() > 0) { lastPage = page.getTotalPages() - 1; } link += "<" + generateUri(baseUrl, lastPage, page.getSize()) + ">; rel=\"last\","; link += "<" + generateUri(baseUrl, 0, page.getSize()) + ">; rel=\"first\""; headers.add(HttpHeaders.LINK, link); return headers; }
@RequestMapping(value = "/noauth/activate", params = { "activateToken" }, method = RequestMethod.GET) public ResponseEntity<String> checkActivateToken( @RequestParam(value = "activateToken") String activateToken) { HttpHeaders headers = new HttpHeaders(); HttpStatus responseStatus; UserCredentials userCredentials = userService.findUserCredentialsByActivateToken(activateToken); if (userCredentials != null) { String createPasswordURI = "/login/createPassword"; try { URI location = new URI(createPasswordURI + "?activateToken=" + activateToken); headers.setLocation(location); responseStatus = HttpStatus.SEE_OTHER; } catch (URISyntaxException e) { log.error("Unable to create URI with address [{}]", createPasswordURI); responseStatus = HttpStatus.BAD_REQUEST; } } else { responseStatus = HttpStatus.CONFLICT; } return new ResponseEntity<>(headers, responseStatus); }
private HttpEntity<MultiValueMap<String, String>> buildResponseEntity( Submission submission, HttpHeaders headers) { logger.debug("Building response entity"); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); try { map.add("test_output", new ObjectMapper().writeValueAsString( submission.getTestOutput())); } catch (JsonProcessingException ex) { logger.debug("POJO deserialization failed"); } map.add("stdout", submission.getStdout()); map.add("stderr", submission.getStderr()); map.add("validations", submission.getValidations()); map.add("vm_log", submission.getVmLog()); map.add("token", submission.getId().toString()); map.add("status", submission.getStatus().toString()); map.add("exit_code", submission.getExitCode().toString()); return new HttpEntity<>(map, headers); }
@Test @WithMockUser public void createPostWithMockUser() throws Exception { Post _data = Post.builder().title("my first post").content("my content of my post").build(); given(this.postService.createPost(any(PostForm.class))) .willReturn(_data); MvcResult result = this.mockMvc .perform( post("/posts") .content(objectMapper.writeValueAsString(PostForm.builder().title("my first post").content("my content of my post").build())) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isCreated()) .andExpect(header().string(HttpHeaders.LOCATION, containsString("/posts"))) .andReturn(); log.debug("mvc result::" + result.getResponse().getContentAsString()); verify(this.postService, times(1)).createPost(any(PostForm.class)); }
private static QueryResponse q(Query query, Token token) throws QueryExecutionBotException{ final String ENTITY_URI_RESOURCE = String.format(QUERY_RESOURCE, Bot.API_URL); QueryResponseParser parser = new QueryResponseParser(); QueryResponse response = null; HttpHeaders headers = HttpClient.getDevHeaders(token); HttpEntity<Query> request = new HttpEntity<>(query, headers); if(isValidQuery(query)) { initializeQueryDefaults(query); try { ResponseEntity<String> entityResponse = HttpClient.post(ENTITY_URI_RESOURCE, request); log.debug("Entity response -> {}", entityResponse); if(entityResponse.getStatusCode().is2xxSuccessful()){ log.info("Query executed suscessfull"); response = parser.parse(entityResponse); } } catch (EntityParserException e) { throw new QueryExecutionBotException("Error on execute query", e); } } return response; }
@RequestMapping(value="/delete/{id}" ,produces=MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<String> delete(@PathVariable("id") long id){ logger.info( "delete("+id+")..." ); ResponseEntity<String> responseEntity = null; try { this.talkerService.delete(id); HttpHeaders responseHeaders = new HttpHeaders(); String talkerJson = new ObjectMapper().writeValueAsString("Delete["+id+"] OK"); responseEntity = new ResponseEntity<String>(talkerJson, responseHeaders, HttpStatus.OK); } catch (Exception e) { logger.error(e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); } return responseEntity; }
@Override public HttpHeaders getMultipartHeaders(String paramOrFileName) { String contentType = getMultipartContentType(paramOrFileName); if (contentType != null) { HttpHeaders headers = new HttpHeaders(); headers.add(CONTENT_TYPE, contentType); return headers; } else { return null; } }
@Test public void testCorsFilterDeactivated() throws Exception { props.getCors().setAllowedOrigins(null); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); }
@Override public HttpHeaders getRequestHeaders() { HttpHeaders headers = new HttpHeaders(); Enumeration<String> headerNames = getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); headers.put(headerName, Collections.list(getHeaders(headerName))); } return headers; }
@RequestMapping("getGod/{id}") public @ResponseBody ResponseEntity<String> getGod(@PathVariable("id") int id, HttpServletRequest request, HttpServletResponse response){ String json; try{ God god = Backend.getGodDao().getFullGod(id); if(showLogic(god) && god != null){ JsonHelper help = new JsonHelper(god.toOneFiveJsonString()); // should in theory work for every type of searchable list... addListToHelper("npcs", App.toListSearchable(god.getNpcs()), help); addListToHelper("events", App.toListSearchable(god.getEvents()), help); addListToHelper("regions", App.toListSearchable(god.getRegions()), help); addListToHelper("pantheon", App.toListSearchable(Backend.getGodDao().getPantheon(god)), help); json = help.getString(); }else { throw new Exception("This npc is not showable."); } } catch(Exception e){ e.printStackTrace(); json = "{\"Message\":\"" + e.getLocalizedMessage() + "\"}"; } HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "application/json"); return new ResponseEntity<String>(json, headers, HttpStatus.CREATED); }
/** * Add the given headers to the given HTTP request. * @param httpRequest the request to add the headers to * @param headers the headers to add */ static void addHeaders(HttpUriRequest httpRequest, HttpHeaders headers) { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); if (!headerName.equalsIgnoreCase(HTTP.CONTENT_LEN) && !headerName.equalsIgnoreCase(HTTP.TRANSFER_ENCODING)) { for (String headerValue : entry.getValue()) { httpRequest.addHeader(headerName, headerValue); } } } }
private void writeHeaders(HttpHeaders headers) { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); for (String headerValue : entry.getValue()) { this.connection.addRequestProperty(headerName, headerValue); } } }
public void testAddResult() { String json = "{\n" + " \"numberOfTimes\": 336,\n" + " \"createdDate\": 1488962733399,\n" + " \"type\": 1,\n" + " \"resultFor\": 1488962733399,\n" + " \"prizes\": [\n" + " {\n" + " \"prizeInfo\": \"1000\",\n" + " \"items\": [\n" + " {\n" + " \"word\": \"abc\",\n" + " \"code\": \"123456\"\n" + " }\n" + " ]\n" + " },\n" + " {\n" + " \"prizeInfo\": \"500\",\n" + " \"items\": [\n" + " {\n" + " \"word\": \"def\",\n" + " \"code\": \"112233\"\n" + " },\n" + " {\n" + " \"word\": \"ghi\",\n" + " \"code\": \"223344\"\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + "}"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", "opensezmi"); HttpEntity request = new HttpEntity(json, headers); ResponseEntity<String> response = this.restTemplate .exchange("/lottery/add", HttpMethod.POST, request, String.class); Assert.assertTrue(response.getStatusCodeValue() == 200); }
@RequestMapping(value = "/pedido/", method = RequestMethod.POST) public ResponseEntity<String> salvarPedido(@RequestBody Pedido pedido, UriComponentsBuilder ucBuilder) { logger.info("Criando pedido : {}", pedido); pedidoservice.salvar(pedido); HttpHeaders headers = new HttpHeaders(); headers.setLocation(ucBuilder.path("/pedido/{id}").buildAndExpand(pedido.getId()).toUri()); return new ResponseEntity<String>(headers, HttpStatus.CREATED); }
/** * GET /users : get all users. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and with body all users * @throws URISyntaxException if the pagination headers couldn't be generated */ @GetMapping("/users") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity<List<ManagedUserVM>> getAllUsers(@ApiParam Pageable pageable) throws URISyntaxException { Page<User> page = userRepository.findAll(pageable); List<ManagedUserVM> managedUserVMs = page.getContent().stream() .map(ManagedUserVM::new) .collect(Collectors.toList()); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users"); return new ResponseEntity<>(managedUserVMs, headers, HttpStatus.OK); }
@ApiOperation("refresh token") @RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET) public ResponseEntity<TokenRes> refreshAndGetAuthenticationToken(HttpServletRequest request) { String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); String username = jwtTokenUtil.getUsernameFromToken(authorization); return ResponseEntity.ok(new TokenRes(jwtTokenUtil.generateToken(username))); }
/** * GET /users : get all users. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and with body all users */ @GetMapping("/users") @Timed public ResponseEntity<List<UserDTO>> getAllUsers(@ApiParam Pageable pageable) { final Page<UserDTO> page = userService.getAllManagedUsers(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); }
@Test public void accessProtectedResourceByJwtToken() throws JsonParseException, JsonMappingException, IOException, InvalidJwtException { ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/client", String.class); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class); String responseText = response.getBody(); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class); String accessToken = (String) jwtMap.get("access_token"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + accessToken); JwtContext jwtContext = jwtConsumer.process(accessToken); logJWTClaims(jwtContext); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals("trusted-app", response.getBody()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/trusted_client", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals("[{\"authority\":\"ROLE_TRUSTED_CLIENT\"}]", response.getBody()); }
@Override public void encode(Object requestBody, Type bodyType, RequestTemplate request) throws EncodeException { if (requestBody != null) { Class<?> requestType = requestBody.getClass(); Collection<String> contentTypes = request.headers().get(HttpHeaders.CONTENT_TYPE); MediaType requestContentType = null; if (contentTypes != null && !contentTypes.isEmpty()) { String type = contentTypes.iterator().next(); requestContentType = MediaType.valueOf(type); } for (HttpMessageConverter<?> messageConverter : this.messageConverters.getObject().getConverters()) { if (messageConverter.canWrite(requestType, requestContentType)) { FeignOutputMessage outputMessage = new FeignOutputMessage(request); try { @SuppressWarnings("unchecked") HttpMessageConverter<Object> copy = (HttpMessageConverter<Object>) messageConverter; copy.write(requestBody, requestContentType, outputMessage); } catch (IOException ex) { throw new EncodeException("Error converting request body", ex); } request.headers(null); request.headers(FeignUtils.getHeaders(outputMessage.getHeaders())); request.body(outputMessage.getOutputStream().toByteArray(), Charset.forName("UTF-8")); // TODO: return; } } String message = "Could not write request: no suitable HttpMessageConverter " + "found for request type [" + requestType.getName() + "]"; if (requestContentType != null) { message += " and content type [" + requestContentType + "]"; } throw new EncodeException(message); } }
@Test public void testCorsFilterDeactivated2() throws Exception { props.getCors().setAllowedOrigins(new ArrayList<>()); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); }
public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) { log.error("Entity creation failed, {}", defaultMessage); HttpHeaders headers = new HttpHeaders(); headers.add("X-blogApp-error", "error." + errorKey); headers.add("X-blogApp-params", entityName); return headers; }
@Test public void requestHeaders_withStaticHeader() { RequestHeaders requestHeaders = getBasic("header1", "headerBasicValue"); HttpHeaders httpHeaders = requestHeaders.encode(new Object[]{}); Assertions.assertThat(httpHeaders) .containsExactly(new SimpleEntry<>("header1", singletonList("headerBasicValue"))); }
@Override protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException { byte[] bytes = this.bufferedOutput.toByteArray(); if (headers.getContentLength() == -1) { headers.setContentLength(bytes.length); } ClientHttpResponse result = executeInternal(headers, bytes); this.bufferedOutput = null; return result; }
@RequestMapping(value = "/produto/", method = RequestMethod.POST) public ResponseEntity<String> salvarProduto(@RequestBody Produto produto, UriComponentsBuilder ucBuilder) { logger.info("Criando produto : {}", produto); produtoService.salvar(produto); HttpHeaders headers = new HttpHeaders(); headers.setLocation(ucBuilder.path("/produto/{id}").buildAndExpand(produto.getId()).toUri()); return new ResponseEntity<String>(headers, HttpStatus.CREATED); }
@RequestMapping(value= "/{classId}/results", method = RequestMethod.POST) public ResponseEntity<?> postResult(JwtAuthenticationToken token, @PathVariable final String classId, @RequestBody Result result) { UserContext userContext = (UserContext) token.getPrincipal(); Result savedResult = this.resultService.save(userContext.getTenantId(), userContext.getOrgId(), classId, result); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(ServletUriComponentsBuilder .fromCurrentRequest().path("/{id}") .buildAndExpand(savedResult.getSourcedId()).toUri()); return new ResponseEntity<>(savedResult, httpHeaders, HttpStatus.CREATED); }
private InputStream asInputStream(String url) { String targetUrl = url.replace(".webp", ".png"); HttpHeaders headers = new HttpHeaders(); // workaround to go through CloudFlare :^) headers.add("User-Agent", Constants.USER_AGENT); try { ResponseEntity<Resource> responseEntity = restTemplate.exchange(targetUrl, HttpMethod.GET, new HttpEntity<>(headers), Resource.class); return responseEntity.getBody().getInputStream(); } catch (IOException | RestClientException e) { log.warn("Could not get {} as InputStream", e); return null; } }
private HttpEntity<Object> validationRequest(String authorization) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.add(AUTHORIZATION, authorization); return new HttpEntity<>(headers); }
private ResponseEntity<Map<String, String>> getResponse(String requestEntity) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_XML); HttpEntity<String> httpEntity = new HttpEntity<>(requestEntity, httpHeaders); return restTemplate.exchange( URL, HttpMethod.POST, httpEntity, ParameterizedTypeReference.forType(Map.class) ); }
/** * GET /users : get all users. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and with body all users * @throws URISyntaxException if the pagination headers couldnt be generated */ @RequestMapping(value = "/users", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed @Transactional(readOnly = true) public ResponseEntity<List<ManagedUserDTO>> getAllUsers(Pageable pageable) throws URISyntaxException { Page<User> page = userRepository.findAll(pageable); List<ManagedUserDTO> managedUserDTOs = page.getContent().stream() .map(ManagedUserDTO::new) .collect(Collectors.toList()); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users"); return new ResponseEntity<>(managedUserDTOs, headers, HttpStatus.OK); }
private HttpHeaders createHeaders() { HttpHeaders httpHeaders = new HttpHeaders(); List<MediaType> mediaTypeList = new ArrayList<>(); mediaTypeList.add((MediaType.APPLICATION_JSON)); httpHeaders.setAccept(mediaTypeList); httpHeaders.setContentType(MediaType.APPLICATION_JSON); httpHeaders.set(HttpHeaders.CONNECTION, "Close"); return httpHeaders; }