spring function in aws lambda not sending back status code - spring

I had the following code working and returning a statusCode.
final APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
responseEvent.setHeaders(Map.of(CONTENT_TYPE, APPLICATION_JSON));
responseEvent.setBody(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
responseEvent.setStatusCode(200);
However i have recently updated the spring function adapter to 3.2.3, and i no longer recieve the status code in the response. In fact the response is now just the body.
My setup is aws lambda using spring function, behind api gateway.

this works.
final APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
final Map<String, Object> headers = new HashMap<>();
headers.put(CONTENT_TYPE, APPLICATION_JSON);
final ObjectMapper objectMapper = new ObjectMapper();
responseEvent.setBody(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
responseEvent.setStatusCode(HttpStatus.OK.value());
Message<APIGatewayProxyResponseEvent> finalResponse = new GenericMessage<>(responseEvent, headers);

Related

REST API call from spring boot not working

I am trying to fetch live data from NSE options trading. Below code is not working and the request made is stuck without any response.
Any workaround on this?
public void getLiveBankNiftyData() {
String RESOURCE_PATH = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY";
ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity(RESOURCE_PATH, Object[].class);
Object[] objects = responseEntity.getBody();
}
i tried this
// request url
String url = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY";
// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();
// make an HTTP GET request
String json = restTemplate.getForObject(url, String.class);
// print json
System.out.println(json);
I found a way out. Instead of using RestTemplate I used WebClient and this solved the issue.

Spring Security 5 rest client with OAuth2

I would like to implement a client which should simply send some rest calls with a OAuth2 token. Using spring-security-oauth it was pretty easy to use the OAuth2RestTemplate with a client-credentials flow. Today I saw most of those classes are deprecated in 2.4.0 and the recommendation is to use Spring Security 5. I've googled around and looked into the Migration Guide [1] but I've not understood what I've to do to perform some simple rest call which fetches a token with Spring Security 5. I think I'm even not sure what kind of libraries are needed. So what I'm basically is looking for is a way to provide a client-id, client-secret and a tokenendpoint programatically (not via properties) to some kind of rest template and send a request to a specific url.
--edit--
I found a way of using the web client without using the properties but rather using the ClientRegestration object. I'm not sure if that is a recommended way:
#Test
public void test() {
WebClient webClient = getWebClient();
ResponseSpec retrieve = webClient.get().uri("https://somepath")
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(REG_ID)).retrieve();
Flux<String> result = retrieve.bodyToFlux(String.class); // flux makes no sense here, use Mono instead
Mono<List<String>> response = result.collectList();
List<String> block = response.block();
System.out.print(block);
System.out.print("debug");
}
public WebClient getWebClient() {
Builder clientRegestrationBuilder = ClientRegistration.withRegistrationId(REG_ID);
clientRegestrationBuilder.clientId(CLIENT_ID);
clientRegestrationBuilder.clientSecret(CLIENT_SECRET);
clientRegestrationBuilder.tokenUri(TOKEN_ENDPOINT);
clientRegestrationBuilder.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS);
ClientRegistration clientRegistration = clientRegestrationBuilder.build();
ReactiveClientRegistrationRepository repo = new InMemoryReactiveClientRegistrationRepository(clientRegistration);
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(repo,
new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
return WebClient.builder().filter(oauth).build();
}
Regards
monti
[1] https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Migration-Guide
The following code is a unit test which shows how a ClientRegistration can be done programatically. In "real" spring scenario I guess the ClientRegistration should be provided as bean and finally injected as a list to a ReactiveClientRegistrationRepository...
public void test() {
WebClient webClient = getWebClient();
ResponseSpec retrieve = webClient.get().uri("https://somepath")
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(REG_ID)).retrieve();
Flux<String> result = retrieve.bodyToFlux(String.class); // flux makes no sense here, use Mono instead
Mono<List<String>> response = result.collectList();
List<String> block = response.block();
System.out.print(block);
System.out.print("debug");
}
public WebClient getWebClient() {
Builder clientRegestrationBuilder = ClientRegistration.withRegistrationId(REG_ID);
clientRegestrationBuilder.clientId(CLIENT_ID);
clientRegestrationBuilder.clientSecret(CLIENT_SECRET);
clientRegestrationBuilder.tokenUri(TOKEN_ENDPOINT);
clientRegestrationBuilder.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS);
ClientRegistration clientRegistration = clientRegestrationBuilder.build();
ReactiveClientRegistrationRepository repo = new InMemoryReactiveClientRegistrationRepository(clientRegistration);
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(repo,
new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
return WebClient.builder().filter(oauth).build();
}

Why im getting Exception- Not enough variables available to expand in Spring Rest URI call?

im working on a rest API call related to Payments. But i encountered with an exception. I know this comes due to setting parameters to the rest uri.
String uri = "https://test-gateway.mastercard.com/api/rest/version/52/merchant/{merchantId}/order/{orderId}/transaction/{transactionId}";
LinkedMultiValueMap<String, String> uriVars = new LinkedMultiValueMap<>();
uriVars.add("merchantId", _paymentInstrument.getAcquirerMid());
uriVars.add("orderId", _paymentInstrument.getOrderId().toString());
uriVars.add("transactionId", _paymentInstrument.getTargetTransactionId().toString());
String uri = UriComponentsBuilder.fromHttpUrl(url)
.queryParams(uriVars).build().toUriString();
VoidRequest voidRequest =
createVoidRequest(_paymentInstrument.getTargetTransactionId());
HttpEntity<VoidRequest> requestEntity = new HttpEntity<>(voidRequest, headers);
ResponseEntity<TransactionResponse> responseEntity = restTemplate.exchange(uri, HttpMethod.PUT, requestEntity, TransactionResponse.class);
Exception im getting is Using RestTemplate in Spring. Exception- Not enough variables available to expand "merchantId".

413 request entity too large issue in HTTP Get method call

Please don't mistake it as already asked question. The main difference here is, this issue is coming in Get method call. All the solutions discussed here or other places talks about either POST method or multipart form data.
Configuration I have provided is as below:
String url = env.getProperty(ApplicationConstants.PMCC_MANAGER_REGION_QUERY_URL);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url).queryParam("inTIS_PMA_NUMBER","ALL");
URI uri = builder.build().toUri();
RestTemplate restTemplate = getRestTemplateBuilder().build();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
private RestTemplateBuilder getRestTemplateBuilder() {
Integer connectionTimeOut = 2000;
Integer readTimeOut = 3000;
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.setConnectTimeout(connectionTimeOut);
restTemplateBuilder.setReadTimeout(readTimeOut);
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setBufferRequestBody(false);
restTemplateBuilder.requestFactory(factory);
return restTemplateBuilder;
}
This code is part of Spring Boot application and deployed in WebLogic server.

send multipart response in spring boot

I am working on apis which is developed in spring boot. Now I have one API in which I have to send response which contains one binary file and and xml.
Both will be seperated by multipart boundary.
So is there any way to do this?
In spring boot try following the way to send a response in multipart.
#RequestMapping(method = { RequestMethod.GET },value = "/multipartdata",produces=MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<MultiValueMap<String, Object>> gerMultipartData()
throws Exception {
MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>();
formData.add("first_name", "ganesh");
formData.add("last_name", "patil");
formData.add("file-data_1", new FileSystemResource("C:\Users\ganesh\img\logo.png"));
formData.add("file-data_2", new FileSystemResource("C:\Users\ganeshg\Desktop\download.jpg"));
formData.add("file-data_3", new FileSystemResource("C:\Users\ganeshg\Desktop\odstext.txt"));
formData.add("file-data_4", new FileSystemResource("D:\Agent\152845.docx"));
formData.add("file-data_5", new FileSystemResource("D:\testxls.xlsx"));
return new ResponseEntity<MultiValueMap<String, Object>>(formData, HttpStatus.OK);
}

Resources