Java Code Examples for org.springframework.http.HttpHeaders

The following are top voted examples for showing how to use org.springframework.http.HttpHeaders. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: xm-ms-dashboard   File: MicroserviceSecurityConfiguration.java   Source Code and License 7 votes vote down vote up
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())));
}
 
Example 2
Project: qpp-conversion-tool   File: CpcFileControllerV1.java   Source Code and License 7 votes vote down vote up
/**
 * 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);
}
 
Example 3
Project: esup-sgc   File: WsRestEsupNfcController.java   Source Code and License 7 votes vote down vote up
/**
 * 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);	
}
 
Example 4
Project: esup-sgc   File: WsRestEsupNfcController.java   Source Code and License 6 votes vote down vote up
/**
 * Exemple :
 * curl --form "[email protected]/tmp/le-csv.txt" http://localhost:8080/wsrest/nfc/addCrousCsvFile?authToken=123456
 * @throws IOException 
 * @throws ParseException 
 */
@RequestMapping(value = "/addCrousCsvFile", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<String> addCrousCsvFile(@RequestParam String authToken, @RequestParam MultipartFile file, @RequestParam String csn) throws IOException, ParseException {
	HttpHeaders responseHeaders = new HttpHeaders();
	String eppnInit = clientJWSController.getEppnInit(authToken);
	if(eppnInit == null) {
		log.info("Bad authotoken : " + authToken);
		return new ResponseEntity<String>("bad authotoken", responseHeaders, HttpStatus.FORBIDDEN);
	}
	// sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?
	if(file != null) {
		String filename = file.getOriginalFilename();
		log.info("CrousSmartCardController retrieving file from rest call " + filename);
		InputStream stream = new  ByteArrayInputStream(file.getBytes());
		Card card = Card.findCard(csn);
		crousSmartCardService.consumeCsv(stream, false);
		cardEtatService.setCardEtat(card, Etat.ENCODED, null, null, false, true);
		if(appliConfigService.getEnableAuto()) {
			cardEtatService.setCardEtatAsync(card.getId(), Etat.ENABLED, null, null, false, false);
		}
		return new ResponseEntity<String>("OK", responseHeaders, HttpStatus.OK);
	}
	
	return new ResponseEntity<String>("KO", responseHeaders, HttpStatus.BAD_REQUEST);
}
 
Example 5
Project: sentry   File: UserResource.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 6
Project: pact-spring-mvc   File: ReturnExpect.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 7
Project: FolderSync   File: Auth.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 8
Project: Settings   File: AuthorizationApi.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * 
 * <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);
}
 
Example 9
Project: CommonInformationSpace   File: CISAdaptorConnectorRestController.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 10
Project: cas-5.1.0   File: RestPasswordManagementService.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 11
Project: spring-io   File: PaginationUtil.java   Source Code and License 6 votes vote down vote up
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;
    }
 
Example 12
Project: iotplatform   File: AuthController.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 13
Project: tdd-pingpong   File: FakeSandboxRestService.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 14
Project: spring-microservice-sample   File: ControllerTest.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 15
Project: botengine-ai   File: Engine.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 16
Project: bruxelas   File: TalkerRestController.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 17
Project: lams   File: DefaultMultipartHttpServletRequest.java   Source Code and License 5 votes vote down vote up
@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;
	}
}
 
Example 18
Project: TorgCRM-Server   File: WebConfigurerTest.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 19
Project: lams   File: AbstractMultipartHttpServletRequest.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 20
Project: fwm   File: Webservice1_5Controller.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 21
Project: lams   File: HttpComponentsClientHttpRequest.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
			}
		}
	}
}
 
Example 22
Project: lams   File: SimpleStreamingClientHttpRequest.java   Source Code and License 5 votes vote down vote up
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);
		}
	}
}
 
Example 23
Project: myanmarlottery   File: ResultControllerIntegrationTest.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 24
Project: microservices-tcc-alfa   File: PedidoController.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 25
Project: spring-boot-jwt-jpa   File: AuthenticationController.java   Source Code and License 5 votes vote down vote up
@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)));
}
 
Example 26
Project: xm-uaa   File: UserResource.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 27
Project: demo-spring-boot-security-oauth2   File: GrantByClientCredentialTest.java   Source Code and License 5 votes vote down vote up
@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());

}
 
Example 28
Project: spring-cloud-samples   File: CustomEncode.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 29
Project: initiatives_backend_auth   File: TokenService.java   Source Code and License 5 votes vote down vote up
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;
            });
}
 
Example 30
Project: xm-ms-timeline   File: WebConfigurerTest.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 31
Project: devoxxus-jhipster-microservices-demo   File: HeaderUtil.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 32
Project: spring-webflux-client   File: RequestHeadersTest.java   Source Code and License 5 votes vote down vote up
@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")));
}
 
Example 33
Project: lams   File: AbstractBufferingClientHttpRequest.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 34
Project: microservices-tcc-alfa   File: ProdutoController.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 35
Project: OpenLRW   File: ClassController.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 36
Project: sentry   File: Info.java   Source Code and License 5 votes vote down vote up
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;
    }
}
 
Example 37
Project: ServiceComb-Company-WorkShop   File: ManagerApplicationIT.java   Source Code and License 5 votes vote down vote up
private HttpEntity<Object> validationRequest(String authorization) {
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  headers.add(AUTHORIZATION, authorization);

  return new HttpEntity<>(headers);
}
 
Example 38
Project: family-tree-xml-parser   File: DocumentControllerIntegrationTest.java   Source Code and License 5 votes vote down vote up
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)
  );
}
 
Example 39
Project: klask-io   File: UserResource.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 40
Project: citizen-sdk-android   File: RestClient.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 41
Project: jhipster-microservices-example   File: HeaderUtil.java   Source Code and License 5 votes vote down vote up
public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) {
    log.error("Entity processing failed, {}", defaultMessage);
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-blogApp-error", "error." + errorKey);
    headers.add("X-blogApp-params", entityName);
    return headers;
}
 
Example 42
Project: che-starter   File: WorkspacePreferencesClient.java   Source Code and License 5 votes vote down vote up
public void setCommitterInfo(final String cheServerUrl, final String keycloakToken, final WorkspacePreferences preferences) {
    RestTemplate template = new KeycloakRestTemplate(keycloakToken);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<WorkspacePreferences> entity = new HttpEntity<WorkspacePreferences>(preferences, headers);
    template.exchange(CheRestEndpoints.UPDATE_PREFERENCES.generateUrl(cheServerUrl), HttpMethod.PUT, entity, String.class);
}
 
Example 43
Project: qualitoast   File: WebConfigurerTest.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 44
Project: qualitoast   File: WebConfigurerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCorsFilterOnApiPath() throws Exception {
    props.getCors().setAllowedOrigins(Collections.singletonList("*"));
    props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
    props.getCors().setAllowedHeaders(Collections.singletonList("*"));
    props.getCors().setMaxAge(1800L);
    props.getCors().setAllowCredentials(true);

    MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
        .addFilters(webConfigurer.corsFilter())
        .build();

    mockMvc.perform(
        options("/api/test-cors")
            .header(HttpHeaders.ORIGIN, "other.domain.com")
            .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))
        .andExpect(status().isOk())
        .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"))
        .andExpect(header().string(HttpHeaders.VARY, "Origin"))
        .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE"))
        .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
        .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));

    mockMvc.perform(
        get("/api/test-cors")
            .header(HttpHeaders.ORIGIN, "other.domain.com"))
        .andExpect(status().isOk())
        .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
 
Example 45
Project: websocket-poc   File: Credentials.java   Source Code and License 5 votes vote down vote up
public HttpHeaders httpHeaders() {
    String notEncoded = this.username + ":" + this.password;
    String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Basic " + encodedAuth);
    return headers;
}
 
Example 46
Project: cf-mta-deploy-service   File: RestTemplateFactory.java   Source Code and License 5 votes vote down vote up
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
    ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);
    HttpHeaders requestHeaders = request.getHeaders();
    if (!requestHeaders.containsKey(HttpHeaders.AUTHORIZATION)) {
        requestHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + computeAuthorizationToken());
    }
    return request;
}
 
Example 47
Project: shoucang   File: ContentResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /contents -> get all the contents.
 */
@RequestMapping(value = "/contents",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<Content>> getAllContents(Pageable pageable)
    throws URISyntaxException {
    Page<Content> page = contentRepository.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/contents");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 48
Project: speakTogether   File: HeaderUtil.java   Source Code and License 5 votes vote down vote up
public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) {
    log.error("Entity creation failed, {}", defaultMessage);
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-speakTogetherApp-error", "error." + errorKey);
    headers.add("X-speakTogetherApp-params", entityName);
    return headers;
}
 
Example 49
Project: Mastering-Microservices-with-Java-9-Second-Edition   File: BookingControllerIntegrationTests.java   Source Code and License 5 votes vote down vote up
/**
 * Test the GET /v1/booking API
 */
@Test
public void testGetByName() {

    HttpHeaders headers = new HttpHeaders();
    HttpEntity<Object> entity = new HttpEntity<>(headers);
    Map<String, Object> uriVariables = new HashMap<>();
    uriVariables.put("name", "Booking");
    ResponseEntity<Map[]> responseE = restTemplate.exchange("http://localhost:" + port + "/v1/booking/?name={name}", HttpMethod.GET, entity, Map[].class, uriVariables);

    assertNotNull(responseE);

    // Should return no content as there is no booking with id 99
    assertEquals(HttpStatus.OK, responseE.getStatusCode());
    Map<String, Object>[] responses = responseE.getBody();
    assertNotNull(responses);

    // Assumed only single instance exist for booking name contains word "Big"
    assertTrue(responses.length == 2);

    Map<String, Object> response = responses[0];
    String id = response.get("id").toString();
    assertNotNull(id);
    assertEquals("1", id);
    String name = response.get("name").toString();
    assertNotNull(name);
    assertEquals("Booking 1", name);
    boolean isModified = (boolean) response.get("isModified");
    assertEquals(false, isModified);
}
 
Example 50
Project: cmc-claim-store   File: CountyCourtJudgmentController.java   Source Code and License 5 votes vote down vote up
@PostMapping("/{claimId:\\d+}/county-court-judgment")
@ApiOperation("Save County Court Judgment")
public Claim save(
    @PathVariable("claimId") Long claimId,
    @NotNull @RequestBody @Valid CountyCourtJudgment countyCourtJudgment,
    @RequestHeader(HttpHeaders.AUTHORIZATION) String authorisation
) {
    String submitterId = userService.getUserDetails(authorisation).getId();
    return countyCourtJudgmentService.save(submitterId, countyCourtJudgment, claimId);
}
 
Example 51
Project: sentry   File: PermissionResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /permissions : get all the permissions.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of permissions in body
 * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
 */
@GetMapping("/permissions")
@Timed
@Secured(AuthoritiesConstants.SUPPORT)
public ResponseEntity<List<Permission>> getAllPermissions(@ApiParam Pageable pageable)
    throws URISyntaxException {
    log.debug("REST request to get a page of Permissions");
    Page<Permission> page = permissionService.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/permissions");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 52
Project: shoucang   File: PostResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /posts/tags/:id -> get all the posts filter by tag id
 */
@RequestMapping(value = "/posts/tags/{tagId:\\d+}",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(readOnly = true)
public ResponseEntity<List<PostDTO>> getAllPostsByTag(Pageable pageable, @PathVariable Long tagId)
    throws URISyntaxException {

    Tag tag = tagRepository.findOne(tagId);

    if (tag == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    Page<Post> page = postRepository.findUserPostsByTag(pageable, SecurityUtils.getCurrentUserLogin(), tagId);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/posts/tags/" + tagId);

    List<Long> ids = page.getContent().stream()
        .map(Post::getId)
        .collect(Collectors.toList());

    List<Post> posts = postRepository.findByIdIn(ids);

    return new ResponseEntity<>(posts.stream()
        .map(postMapper::postToSimplePostDTO)
        .collect(Collectors.toCollection(LinkedList::new)), headers, HttpStatus.OK);
}
 
Example 53
Project: spring-io   File: WebConfigurerTest.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 54
Project: Spring-Shiro-Spark   File: AdminController.java   Source Code and License 5 votes vote down vote up
@GetMapping(value = SUBPATH_PERMISSION)
public ResponseEntity<List<PermissionDto>> listPermissions(UriComponentsBuilder uriComponentsBuilder){
    HttpHeaders headers = ApplicationUtil.getHttpHeaders(uriComponentsBuilder,PATH + SUBPATH_PERMISSION);
    List<Permission> permissions = permissionService.listPermissions();
    List<PermissionDto> permissionDtos = permissions.stream()
            .map(permission -> {
                return convertToDto(permission);
            })
            .collect(Collectors.toList());
    return new ResponseEntity<List<PermissionDto>>(permissionDtos,headers,HttpStatus.OK);
}
 
Example 55
Project: amv-access-api-poc   File: AmvAccessRestExceptionHandlerAdvice.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler({
        Exception.class
})
public final ResponseEntity<Object> handle(Exception ex, WebRequest request) {
    HttpHeaders headers = new HttpHeaders();

    Exception e = unwrapIfNecessary(ex);

    final HttpStatus status = findHttpStatus(ex)
            .orElseGet(() -> findHttpStatus(e).orElse(HttpStatus.INTERNAL_SERVER_ERROR));

    return handleExceptionInternal(e, null, headers, status, request);
}
 
Example 56
Project: spring-webflux-client   File: DefaultRequestExecutorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void execute() {
    Request request = new MockRequest("http://example.ca", HttpMethod.GET);
    request.headers().add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
    
    requestExecutor.execute(request);
    ClientRequest clientRequest = verifyExchange();
    assertThat(clientRequest.url())
            .isEqualTo(URI.create("http://example.ca"));
    assertThat(clientRequest.method())
            .isEqualTo(HttpMethod.GET);
}
 
Example 57
Project: spring-security-oauth2-boot   File: OAuth2AutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
private HttpHeaders getHeaders(ClientDetails config) {
	HttpHeaders headers = new HttpHeaders();
	String token = new String(Base64.getEncoder().encode(
			(config.getClientId() + ":" + config.getClientSecret()).getBytes()));
	headers.set("Authorization", "Basic " + token);
	return headers;
}
 
Example 58
Project: ait-platform   File: AitRestExceptionHandler.java   Source Code and License 5 votes vote down vote up
@Override
protected ResponseEntity<Object> handleMissingServletRequestPart(final MissingServletRequestPartException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
	logger.info(ex.getClass().getName());
	//
	final String error = ex.getRequestPartName() + " part is missing";
	final AitException AitException = new AitException(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
	return handleExceptionInternal(ex, AitException, headers, AitException.getStatus(), request);
}
 
Example 59
Project: JRockets   File: Authentication.java   Source Code and License 5 votes vote down vote up
private HttpEntity<MultiValueMap<String, String>> constructRequest(){
    String authorizationValue = Base64Utils.encodeToString((CLIENT_ID+":"+CLIENT_SECRET).getBytes());

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic "+authorizationValue);
    headers.add("User-agent", userAgent);

    MultiValueMap<String, String> mvm = new LinkedMultiValueMap<String, String>();
    mvm.add("username",USERNAME);
    mvm.add("password",PASSWORD);
    mvm.add("grant_type", "password");

    return new HttpEntity<MultiValueMap<String, String>>(mvm, headers);
}
 
Example 60
Project: ait-platform   File: AitRestExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(MultipartException.class)
@ResponseBody
public ResponseEntity<Object> handleFileException(Exception ex, final HttpHeaders headers, WebRequest request) {
	ex.printStackTrace();
	final AitException AitException = new AitException(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), "Error al cargar informacion adicional");
	return handleExceptionInternal(ex, AitException, headers, AitException.getStatus(), request);
}