Do you have an example to use CUD ODataXXXRequestBuilders - s4sdk

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");

Related

Convert List<Map<String, Object>> to Map<String, List<Map<String, Object>>> using Java 8 streams API

My question is little similar to what has already been asked here in stackoverflow. My input is as follows:
Map<String, Object> m1 = new HashMap<>();
m1.put("group", "1");
m2.put("A", 10l);
m2.put("B", 20l);
m2.put("C", 100l);
Map<String, Object> m2 = new HashMap<>();
m1.put("group", "1");
m2.put("A", 30l);
m2.put("B", 40l);
m2.put("C", 500l);
List<Map<String, Object>> beforeFormatting = new ArrayList<>();
beforeFormatting.add(m1);
beforeFormatting.add(m2);
My expected output is:
Map<String, List<Map<String, Object>>> afterFormatting;
Output:
1 -> [m1, m2]
I have tried below, but getting compile errors: seems like I am doing something wrong with mapping:
Map<String, List<Map<String, Object>>> afterFormatting = beforeFormatting.stream()
.collect(groupingBy(map -> map.get("group_id"), toList()));
Well map.get("group_id") returns an Object, but you try to map it to a String, change the return type:
Map<Object, List<Map<String, Object>>> afterFormatting = beforeFormatting.stream()
.collect(Collectors.groupingBy(map -> map.get("group_id")));
And also you can drop toList, since it is implicitly used when groupingBy with a single parameter is used.

Build query using QueryBuilders in rest client

By using rest client
Map<String, String> paramMap = new HashMap<String, String>();
String qqq = g.toJson(query.toString());
paramMap.put("q", "make:chevrolet");
paramMap.put("pretty", "true");
try {
Response response = restClient.performRequest("GET", "vehicles/_search", paramMap);
return EntityUtils.toString(response.getEntity());
Here instead of using map object ,how to build query using the QueryBuilders

combining methods with same flow in controller.

Method 1.
#RequestMapping(value="/getProfessor")
public #ResponseBody List<Object> getMember(HttpServletRequest request){
HttpSession session = request.getSession();
HashMap user = (HashMap)session.getAttribute("USER_INFO");
Map<String, Object> param = new HashMap<String, Object>();
param.put("phone", (String)user.get("PHONE");
ReportManager manager = new ReportManager();
List<Object> list = manager.getProfessor(param);
}
Method 2.
#RequestMapping(value="/getMember")
public #ResponseBody List<Object> getMember(HttpServletRequest request){
HttpSession session = request.getSession();
HashMap user = (HashMap)session.getAttribute("USER_INFO");
Map<String, Object> param = new HashMap<String, Object>();
param.put("phone", (String)user.get("PHONE");
ReportManager manager = new ReportManager();
List<Object> list = manager.getMember(param);
}
The code above briefly describe how I get list of members and professors.
The two methods have exactly same code flow except URL and the bottom-most methods. As you know, one of core principles in OOP is 'combine repeating problems'. So, the point is that I want to combine these method into one method.
public Map<String, Object> getParams(HttpServletRequest request){
HttpSession session = request.getSession();
HashMap user = (HashMap)session.getAttribute("USER_INFO");
Map<String, Object> param = new HashMap<String, Object>();
param.put("phone", (String)user.get("PHONE");
}
#RequestMapping(value="/getProfessor")
public #ResponseBody List<Object> getMember(HttpServletRequest request){
ReportManager manager = new ReportManager();
List<Object> list = manager.getProfessor(this.getParams(request));
}
#RequestMapping(value="/getProfessor")
public #ResponseBody List<Object> getMember(HttpServletRequest request){
ReportManager manager = new ReportManager();
List<Object> list = manager.getProfessor(this.getParams(request));
}
Agree with you, as per DRY coding principle duplicating the same code is not recommended.
Either you can use single RequestMapping with some kind of query parameter, OR
move the common code to different method, and invoke it from two methods.
Change the url to a more generic url like /getUser.
Pass an additional TYPE param like PROFESSOR/MEMBER in the request. Depending on the TYPE you can query two different methods in your controller method.

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

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.

Post data using Spring RestTemplate

I am trying to post data using Spring RestTemplate as below:
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
parameters.add("name1", "value1");
parameters.add("name2", "value2");
HttpMessageConverter<String> stringConverter = new StringHttpMessageConverter();
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
List<HttpMessageConverter<?>> msgConverters = new ArrayList<HttpMessageConverter<?>>();
msgConverters.add(formConverter);
msgConverters.add(stringConverter);
restTemplate.setMessageConverters(msgConverters);
String xml = restTemplate.postForObject(myurl, parameters, String.class);
On the server part, I am using a simple servlet to handle request as follow:
String name1 = request.getParameter("name1");
The server returns the xml as String.
When I used HashMap instead of MultiValueMap without Converter, the parameters are null on the server side. But after using the above code, I am getting error
Cannot extract response: no Content-Type found
Can you plz provide me a simple example to achieve what I want.
Here is what I used to format data for the Spring POST:
//FormHttpMessageConverter
is used to construct form parameters to POST on the URI
HttpMessageConverter<?> formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter<?> stringHttpMessageConverter = new StringHttpMessageConverter();
List<HttpMessageConverter> msgConverters = new ArrayList<HttpMessageConverter>();
msgConverters.add(formHttpMessageConverter);
msgConverters.add(stringHttpMessageConverter);
// Prepare acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.ALL);
// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<MultiValueMap<String,String>> httpEntity = new HttpEntity<MultiValueMap<String,String>>(map,headers);
ResponseEntity<String> resp = restTemplate.exchange("https://risk.XXXX.XXXXXX.net",HttpMethod.POST,httpEntity,String.class);

Resources