Using Spring RESTTeample how do I pass hashmap values for url on post? - spring

Using Spring RESTTeample how do I pass hashmap values for url on post?
I am trying to use Spring RESTTeample to post a User Object to a web service but the issue I am having is that I am putting my id into a hashMap and I dont know how to pass the hashmap into RESTTemplate to use. Can you please look at the following code and let me know.. I dont want to hard code the ID on the URL
Map<String, String> vars = new HashMap<String, String>();
vars.put("id", "MMS");
RestTemplate rt = new RestTemplate();
rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
rt.getMessageConverters().add(new StringHttpMessageConverter());
URI uri = new URI("http://" + mRESTServer.getHost() + ":8080/springmvc-resttemplate-test/api/{id}");
User u = new User();
u.setName("Mickey Mouse");
u.setUser("MMS");
User returns = rt.postForObject(uri, u, User.class);

In the code given, you are currently only passing the user information. If you want to pass the id and the user information to the REST service, why not put the user object into the hashmap along with the id and pass the hashmap to the rest service. A sample will be like this
Map<String, Object> request = new HashMap<String, Object>();
request.put("id", "MMS");
request.put("user", user);
restTemplate.postForObject(completeUrl,request, User.class);
This is provided your rest service accepts such an input.

Related

Is it possible to update the statusIds of single positions of an order with the Shopware REST API?

i am trying to update an order based on the return process.
If the return process is done, the order statusId and the statusIds of the positions of an order has to be updated.
I have already managed to update the statusId of the order through this endpoint
/api/orders/15 (PUT-Request). But this Endpoint only allows few parameters to be updated.
Here is the shopware 5 api documentation: https://developers.shopware.com/developers-guide/rest-api/examples/order/
Is there another way to update the positions? Or do i have to update it in the database directly? This seems to be very dirty.
I am using Spring Boot to make the requests. Here is the code for updating the order statusId
private JSONObject setShopwareOrderStatus(ReturnOrder order, SetOrderStatusRequest orderStatus) {
String apiUrl = String.format("https://shop.com/api/orders/%d?useNumberAsId=true", order.getOrderId());
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.AUTHORIZATION, "Basic apiToken");
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<SetOrderStatusRequest> request = new HttpEntity<>(
orderStatus, headers);
ResponseEntity<String> responseEntity =
restTemplate.exchange(apiUrl, HttpMethod.PUT, request, String.class);
return new JSONObject(responseEntity.getBody());
}
Hope someone is able to help me

Do you have an example to use CUD ODataXXXRequestBuilders

In all the documentation I found examples for ODataQueryBuilder.
But do you also have an example how to use the Create, Update and Delete methods of the package com.sap.cloud.sdk.odatav2.connectivity:
ODataCreateRequestBuilder
ODataDeleteRequestBuilder
ODataUpdateRequestBuilder
How is the CSRF token handled?
Please provide a working example?
CSRF tokens are fetched with a HEAD request on the metadata endpoint of the OData service.
Some notes:
The following examples assume that you have a destination named "DestinationName" configured in the SAP Cloud Platform cockpit.
Please keep in mind that the S/4HANA virtual data model is usually the easier alternative.
ODataCreateRequestBuilder
Map<String, Object> body = new HashMap<>();
body.put("FirstName", "John");
body.put("LastName", "Doe");
body.put("BusinessPartnerCategory", "1");
ODataCreateRequest createRequest =
ODataCreateRequestBuilder
.withEntity("/sap/opu/odata/sap/API_BUSINESS_PARTNER", "A_BusinessPartner")
.withBodyAsMap(body)
.build();
createRequest.execute("DestinationName");
ODataUpdateRequestBuilder
Map<String, Object> keys = new HashMap<>();
keys.put("BusinessPartner", "12345");
Map<String, Object> params = new HashMap<>();
params.put("FirstName", "John");
params.put("MiddleName", "D.");
params.put("LastName", "Doe");
params.put("BusinessPartnerCategory", "1");
final ODataUpdateRequest updateRequest =
ODataUpdateRequestBuilder
.withEntity("/sap/opu/odata/sap/API_BUSINESS_PARTNER", "A_BusinessPartner", keys)
.withBodyAsMap(params)
.build();
updateRequest.execute("DestinationName");
ODataDeleteRequestBuilder
Map<String, Object> keys = new HashMap<>();
keys.put("BusinessPartner", "12345");
keys.put("AddressID", "98765");
ODataDeleteRequest deleteRequest =
ODataDeleteRequestBuilder
.withEntity("/sap/opu/odata/sap/API_BUSINESS_PARTNER", "A_BusinessPartnerAddress", keys)
.build();
deleteRequest.execute("DestinationName");

Spring Framework - Where to parse JWT for custom claim?

I have created a Spring JWT authorization application. JWT contains some custom claims. On a resource server side, I wonder, where should I parse the JWT token to collect and check these claims? Should I do this in a controller or in some filter? Whats the best practice? Maybe you have some example?
You can use a combination of a Jackson Object Mapper and Spring Security classes, namely Jwt, JwtHelper and Authentication. You can get the authentication by using Spring Security's static context object and then parse the token you receive using the JwtHelper.
ObjectMapper objectMapper = new ObjectMapper();
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
Map<String, Object> map =
objectMapper.convertValue(authentication.getDetails(), Map.class);
// create a token object to represent the token that is in use.
Jwt jwt = JwtHelper.decode((String) map.get("tokenValue"));
// jwt.getClaims() will return a JSON object of all the claims in your token
// Convert claims JSON object into a Map so we can get the value of a field
Map<String, Object> claims = objectMapper.readValue(jwt.getClaims(), Map.class);
String customField = (String) claims.get("you_custom_field_name");
I would suggest debugging and putting a breakpoint on the third line in the code above. At that point, expose the authentication object. I might have some useful details you'll need later.
This can all be done on the controller. I'm not sure how to use the filter to do so.
you can also use springframework.boot.json.JsonParser:
JsonParser parser = JsonParserFactory.getJsonParser();
Map<String, ?> tokenData = parser.parseMap(JwtHelper.decode(token).getClaims());
> tokenData.get("VALID_KEY");
I'm using this:
private Claim getClaim(String claimKey) {
Authentication token = SecurityContextHolder.getContext().getAuthentication();
try {
DecodedJWT jwt = JWT.decode(token.getCredentials().toString());
return jwt.getClaim(claimKey);
} catch (JWTVerificationException ex) {
throw new RuntimeException(ex);
}
}

How to pass header Information as key value pair to consume rest service using spring

I got a url of web service which returns values in json format but it needs header information in get request as key value pair e.g. I need to pass Emp_code as key and 'xyz' as value to get details of all employees in postman.
private static void getEmployees()
{
final String uri = "http://abc/springrestexample/employees";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);
System.out.println(result);
}
In above code how can I pass header info(key-value) so as to consume service.
You can add headers to your request by using the following example:
org.springframework.http.HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("yourHeaderKey", "yourHeadeerValue");
org.springframework.http.HttpEntity<?> httpEntity = new HttpEntity<>(requestHeaders);
And then issuing this call to your restTemplate:
restTemplate.exchange(uri, org.springframework.http.HttpMethod.GET, httpEntity , String.class);

Need help on RestTemplate Post Request with Body Parameters?

I have a rest api url and submitted the same as POST request with body (user name, password, other parameters) via Rest Client (restclient-ui-2.4-jar-with-dependencies) and it got worked fine without any issues.
Ex:
URL: https://test.com/cgi-bin/testing/api
Body: username=testuser&password=pass123&id=13002&name=raju
The same is not working fine when i used Spring RestTemplate postForObject(url, varmap, Employee.class) method.
Can someone help me with a simple example where the request is a URL, with body parameters and the response is XML which is mapped with a class?
Sample Code:
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("username", "test");
map.add("password", "test123");
map.add("id", "1234");
MarshallingHttpMessageConverter mc = new MarshallingHttpMessageConverter();
mc.setMarshaller(new Jaxb2Marshaller());
mc.setUnmarshaller(new Jaxb2Marshaller());
list.add(marshallingHttpMessageConverter);
emediateRestTemplate.setMessageConverters(list);
Employee employee = (Employee) restTemplate.postForObject(url, map, Employee.class);
Thanks in advance,
Kathir
The above converters Ex: "MarshallingHttpMessageConverter" are not required.
MultiValueMap<String, String> parametersMap = new LinkedMultiValueMap<String, String>();
parametersMap.add("username", "test");
parametersMap.add("password", "test123");
parametersMap.add("id", "1234");
For Post:
restTemplate.postForObject(url, parametersMap, Employee.class);
url is String - rest api URL
parametersMap - MultiValueMap
Employee - object which needs to be converted from the JSON response
For Get:
restTemplate.getForObject(url, class object, variablesMap);
url is : String - rest api URL
variablesMap - Map
class object - object which needs to be converted from the JSON response

Resources