How to add HTTP headers in Microprofile REST client dynamically? - java

I am developing application, which uses microprofile rest client. And that rest client should send REST request with various http header. Some headers names changes dynamically. My microprofile rest client should be generic, but I did not find how to implement such behaviour.
According to the documentation you need to specify all header names in the implementation via annotations and that is not generic. Is there any way how to "hack" it and add HTTP headers programatically?
Thanks in advance
GenericRestClient genericRestClient = null;
Map<String, Object> appConfig = context.appConfigs();
String baseUrl = (String) appConfig.get("restClient.baseUrl");
path = (String) appConfig.get("restClient.path");
try {
genericRestClient = RestClientBuilder.newBuilder()
.baseUri(new URI(baseUrl)).build(GenericRestClient.class);
}catch(URISyntaxException e){
logger.error("",e);
throw e;
}
Response response = genericRestClient.sendMessage(path, value);
logger.info("Status: "+response.getStatus());
logger.info("Response body: "+response.getEntity().toString());
Generic rest client code:
#RegisterRestClient
public interface GenericRestClient {
#POST
#Path("{path}")
#Produces("application/json")
#Consumes("application/json")
public Response sendMessage(<here should go any map of custom headers>, #PathParam("path") String pathParam, String jsonBody);
}

According to the spec, you can use a ClientHeadersFactory. Something like this:
public class CustomClientHeadersFactory implements ClientHeadersFactory {
#Override public MultivaluedMap<String, String> update(
MultivaluedMap<String, String> incomingHeaders,
MultivaluedMap<String, String> clientOutgoingHeaders
) {
MultivaluedMap<String, String> returnVal = new MultivaluedHashMap<>();
returnVal.putAll(clientOutgoingHeaders);
returnVal.putSingle("MyHeader", "generated");
return returnVal;
}
}
#RegisterRestClient
#RegisterClientHeaders(CustomClientHeadersFactory.class)
public interface GenericRestClient {
...
}
You can't pass values directly to the ClientHeadersFactory; but you can directly access the headers of an incoming request, if your own service is called via JAX-RS. You can also #Inject anything you need. If this is still not sufficient and you really need to pass things from the service call, you can use a custom #RequestScope bean, e.g.:
#RequestScope
class CustomHeader {
private String name;
private String value;
// getters/setters
}
public class CustomClientHeadersFactory implements ClientHeadersFactory {
#Inject CustomHeader customHeader;
#Override public MultivaluedMap<String, String> update(
MultivaluedMap<String, String> incomingHeaders,
MultivaluedMap<String, String> clientOutgoingHeaders
) {
MultivaluedMap<String, String> returnVal = new MultivaluedHashMap<>();
returnVal.putAll(clientOutgoingHeaders);
returnVal.putSingle(customHeader.getName(), customHeader.getValue());
return returnVal;
}
}
class Client {
#Inject CustomHeader customHeader;
void call() {
customHeader.setName("MyHeader");
customHeader.setValue("generated");
...
Response response = genericRestClient.sendMessage(path, value);
}
}

Add ClientRequestHeader to your client as follows:
#POST
// read from application.properties
#ClientRequestHeader(name=“myHeader1”, value="${myProperty}")
// read from a method
#ClientRequestHeader(name=“myHeader2”, value="{addHeaderMethod}")
Response sendMessage();
default String addHeaderMethod() {
//put your logic here
return “my dynamic value”;
}

Related

Spring ArgumentResolver to get pathvariable map and

this my method signature
#RequestMapping(value = {"/article", "/article/{id}", "/article/{name}"}, method = RequestMethod.GET,
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<JsonNode> get(#PathVariable Map<String, String> pathVarsMap, #RequestParam(value="test") MultiValueMap<String, String> test, #RequestBody(required=false) JsonNode requestBody )
I want to make this into
public ResponseEntity<JsonNode> get( MyStructure mystr)
where MyStructure will have #PathVariable Map<String, String> pathVarsMap, #RequestParam(value="test") MultiValueMap<String, String> test, #RequestBody(required=false) JsonNode requestBody inside of it.
I know that I have to use custom resolvers and implement resolveArgument. One of the examples i saw did (Map<String, String>) httpServletRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE). But im not sure how to get it to work. Can i create MultiValueMap and RequestBody inside MyString ?
In another place, I see that the recommendation is to use
#Nonnull
protected final Map<String, String> getUriTemplateVariables(NativeWebRequest request) {
#SuppressWarnings("unchecked")
Map<String, String> variables =
(Map<String, String>) request.getAttribute(
URI_TEMPLATE_VARIABLES_ATTRIBUTE, SCOPE_REQUEST);
return (variables != null) ? variables : Collections.<String, String>emptyMap();
}
so im a bit confused on how should i be implementing this
All #PathVariable , #RequestParam and #RequestBody can only be annotated on the method parameters , so there are no ways for you to annotate them on the object fields.
The codes of the existing HandlerMethodArgumentResolver that resolve the values for these annotations also assume these annotation are annotated on the method parameters ,that means you also cannot simply delegate to them to resolve the value for your request object.
Your best bet is to simply reference the corresponding HandlerMethodArgumentResolver for each annotation and copy the related codes to your implementation.
For #PathVariable , it is resolved by PathVariableMapMethodArgumentResolver
For #RequestParam on MultiValueMap , it is resolved by RequestParamMapMethodArgumentResolver
For #RequestBody , it is resolved by RequestResponseBodyMethodProcessor . Internally , it works with a list of HttpMessageConverter to read the HTTP request body. As you are now using Jackson to read the request body , you only need to focus on MappingJackson2HttpMessageConverter for simplicity.
It is easier than I expected. There following implementation should be a good starting point for you.
First define MyStructure class :
public class MyStructure {
public Map<String, String> pathVariables;
public MultiValueMap<String, String> queryParameters;
public JsonNode requestBody;
}
And implement MyStructureArgumentResolver :
public class MyStructureArgumentResolver implements HandlerMethodArgumentResolver {
private MappingJackson2HttpMessageConverter messageConverter;
public MyStructureArgumentResolver(MappingJackson2HttpMessageConverter messageConverter) {
super();
this.messageConverter = messageConverter;
}
#Override
public boolean supportsParameter(MethodParameter parameter) {
return MyStructure.class.isAssignableFrom(parameter.getParameterType());
}
#Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
MyStructure request = new MyStructure();
request.queryParameters = resolveQueryParameters(webRequest);
request.pathVariables = resolvePathVariables(webRequest);
request.requestBody = resolveRequestBody(webRequest, parameter);
return request;
}
private MultiValueMap<String, String> resolveQueryParameters(NativeWebRequest webRequest) {
// resolve all query parameter into MultiValueMap
Map<String, String[]> parameterMap = webRequest.getParameterMap();
MultiValueMap<String, String> result = new LinkedMultiValueMap<>(parameterMap.size());
parameterMap.forEach((key, values) -> {
for (String value : values) {
result.add(key, value);
}
});
return result;
}
private Map<String, String> resolvePathVariables(NativeWebRequest webRequest) {
Map<String, String> uriTemplateVars = (Map<String, String>) webRequest.getAttribute(
HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
if (!CollectionUtils.isEmpty(uriTemplateVars)) {
return new LinkedHashMap<>(uriTemplateVars);
} else {
return Collections.emptyMap();
}
}
private JsonNode resolveRequestBody(NativeWebRequest webRequest, MethodParameter parameter)
throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
HttpInputMessage inputMessage = new ServletServerHttpRequest(servletRequest);
MediaType contentType;
try {
contentType = inputMessage.getHeaders().getContentType();
} catch (InvalidMediaTypeException ex) {
throw new HttpMediaTypeNotSupportedException(ex.getMessage());
}
if (contentType == null) {
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
Class<?> contextClass = parameter.getContainingClass();
JsonNode body = JsonNodeFactory.instance.objectNode();
if (messageConverter.canRead(JsonNode.class, contextClass, contentType)) {
body = (JsonNode) messageConverter.read(JsonNode.class, inputMessage);
}
return body;
}
}
Then register MyStructureArgumentResolver :
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Autowired
private MappingJackson2HttpMessageConverter messageConverter;
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new MyStructureArgumentResolver(messageConverter));
}
}
And use it in the controller method :
#RequestMapping(value = { "/test/{name}" }, method = RequestMethod.GET)
public ResponseEntity<String> test(MyStructure request) {
}
#PostMapping("/get")
public ResponseEntity<JsonNode> get( #RequestBody MyStructure mystr){...}
When call this api, fill in params in request body, send body as application/json. Refer to this sample: sample project

Is it possible to pass custom object into SpringBoot's endpoint?

I have a SpringBoot project and in an every endpoint's the first call is parsing a request header into a POJO object. making sure required headers are set. Is it possible "to teach" SpringBoot to be able to provide custom object in endpoints?
class CommonHeader {
private String callerId;
private String systemId;
....
public static CommonHeader parseCommonHeader(Map<String, String> map) {
CommonHeader header = new CommonHeader();
header.setCallerId(map.get("x-caller-id"));
.....
return header;
}
}
#Path("/columnConfigs")
Response getColumnConfig(#RequestHeader Map<String, String> headers) {
CommonHeader commonHeader = parseCommonHeader(headers);
....
}
#Path("/other")
Response getColumnConfig(#RequestHeader Map<String, String> headers) {
CommonHeader commonHeader = parseCommonHeader(headers);
....
}
I would like to be able to simplify the following code into:
#Path("/columnConfigs")
Response getColumnConfig(CommonHeader commonHeader) {
....
}
#Path("/other")
Response getColumnConfig(CommonHeader commonHeader) {
....
}
I was looking for some solution for this, that is, bind headers to an object of our definition. I found a good technique here: Using Custom Data Binders in SpringMVC
What you have to do in a nutshell are these, apart from the already created CommonHeader class:
Define an annotation, say #MyHeaders (with #Retention( RUNTIME ) and #Target( PARAMETER ))
#Retention( RUNTIME )
#Target( PARAMETER )
public #interface MyHeaders {}
Create an implementation of HandlerMethodArgumentResolver, say MyHeadersResolver. This will map the headers from the request into an instance of CommonHeader and return it.
#Override
public boolean supportsParameter( MethodParameter methodParameter ){
return methodParameter.getParameterAnnotation( MyHeaders.class ) != null;
}
#Override
public Object resolveArgument( MethodParameter methodParameter, ModelAndViewContainer mavc, NativeWebRequest req, WebDataBinderFactory wdbf ) throws Exception{
HttpServletRequest request = (HttpServletRequest) req.getNativeRequest();
CommonHeader h = new CommonHeader();
Collections.list( request.getHeaderNames() ).forEach( header -> {
switch( header.toLowerCase() ) {
//Set values into CommonHeader instance
}
});
return h;
}
Declare this to SpringMVC as an argument resolver in a class that implements WebMvcConfigurer, like this:
#Override
public void addArgumentResolvers( List<HandlerMethodArgumentResolver> resolvers ) {
resolvers.add( new MyHeadersResolver() );
}
Your controller method signature will now look like this:
Response getColumnConfig( #MyHeaders CommonHeader commonHeader )
Define CommonHeader to extend Map<String, String>:
#RequestHeader
public interface CommonHeader extends Map<String, String> {
}

Map as parameter in RestAPI Post request

I have created an API with a Map<String, Integer> parameter, like this:
#RequestMapping(value = "upload", method = RequestMethod.POST)
public ResponseEntity<String> handleContactsFileUpload(#RequestParam("file") MultipartFile file,
#RequestParam("name") String name,
#RequestParam("campaignAppItemId") Long campaignAppItemId,
#RequestParam("fileColumnHeaders") Map<String,Integer> fileColumnHeaders) throws Exception {
if (file == null)
return new ResponseEntity<>("No file uploaded", HttpStatus.BAD_REQUEST);
contactService.handleContactsFile(file, name, campaignAppItemId,fileColumnHeaders);
return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
}
I am trying to call this via Postman:
I passed the fileColumnHeaders inside Body->Form Data as in the screenshot.
Then I got a message like this in Postman:
Failed to convert value of type 'java.lang.String' to required type 'java.util.Map'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Map': no matching editors or conversion strategy found.
Anybody know why this message came ?
How can we pass a map as a parameter in Rest API request?
How can we pass a map through Postman?
You could use #RequestBody instead of #RequestParam for Maps and other non trivial data types and objects - this way spring will map the JSON representing your map parameter to a domain object, which is then serializable and can be converted to a java object.
... Or simply create a converter:
#Component
#RequiredArgsConstructor
public class StringToMapConverter implements Converter<String, Map<String, Object>> {
private final ObjectMapper objectMapper;
#Override
public Map<String, Object> convert(String source) {
try {
return objectMapper.readValue(source, new TypeReference<Map<String, String>>() {
});
} catch (final IOException e) {
return null;
}
}
}
Firstly, you create DTO object to get all data from your request.
public class FormDataDTO {
private MultipartFile file;
private String name;
private Long campaignAppItemId;
private Map<String,Integer> fileColumnHeaders;
// getters, setters
}
Secondly, you can map FormDataDTO from your request without any annotation:
#RequestMapping(value = "upload", method = RequestMethod.POST)
public ResponseEntity<String> handleContactsFileUpload(FormDataDTO formDataDTO){
// your logic code here
}
Finally, form-data in your request will be:
I think this could work:
#RequestMapping(value = "upload/{fileColumnHeaders}", method = RequestMethod.POST)
public ResponseEntity<String> handleContactsFileUpload(#RequestParam("file") MultipartFile file,
#RequestParam("name") String name,
#RequestParam("campaignAppItemId") Long campaignAppItemId,
#MatrixVariable Map<String,Integer> fileColumnHeaders) throws Exception {
if (file == null)
return new ResponseEntity<>("No file uploaded", HttpStatus.BAD_REQUEST);
contactService.handleContactsFile(file, name, campaignAppItemId,fileColumnHeaders);
return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
}
Put all other parameters into the body, but add the fileColumnHeaders to the URL like this:
/upload/firstName=1;lastName=2;address=3;phone=4
You will also need this extra configuration:
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}

Returning JSON object as response in Spring Boot

I have a sample RestController in Spring Boot:
#RestController
#RequestMapping("/api")
class MyRestController
{
#GetMapping(path = "/hello")
public JSONObject sayHello()
{
return new JSONObject("{'aa':'bb'}");
}
}
I am using the JSON library org.json
When I hit API /hello, I get an exception saying :
Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request processing failed; nested exception is
java.lang.IllegalArgumentException: No converter found for return
value of type: class org.json.JSONObject] with root cause
java.lang.IllegalArgumentException: No converter found for return
value of type: class org.json.JSONObject
What is the issue? Can someone explain what exactly is happening?
As you are using Spring Boot web, Jackson dependency is implicit and we do not have to define explicitly. You can check for Jackson dependency in your pom.xml in the dependency hierarchy tab if using eclipse.
And as you have annotated with #RestController there is no need to do explicit json conversion. Just return a POJO and jackson serializer will take care of converting to json. It is equivalent to using #ResponseBody when used with #Controller. Rather than placing #ResponseBody on every controller method we place #RestController instead of vanilla #Controller and #ResponseBody by default is applied on all resources in that controller. Refer this link: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody
The problem you are facing is because the returned object(JSONObject) does not have getter for certain properties. And your intention is not to serialize this JSONObject but instead to serialize a POJO. So just return the POJO.
Refer this link: https://stackoverflow.com/a/35822500/5039001
If you want to return a json serialized string then just return the string. Spring will use StringHttpMessageConverter instead of JSON converter in this case.
The reason why your current approach doesn't work is because Jackson is used by default to serialize and to deserialize objects. However, it doesn't know how to serialize the JSONObject. If you want to create a dynamic JSON structure, you can use a Map, for example:
#GetMapping
public Map<String, String> sayHello() {
HashMap<String, String> map = new HashMap<>();
map.put("key", "value");
map.put("foo", "bar");
map.put("aa", "bb");
return map;
}
This will lead to the following JSON response:
{ "key": "value", "foo": "bar", "aa": "bb" }
This is a bit limited, since it may become a bit more difficult to add child objects. Jackson has its own mechanism though, using ObjectNode and ArrayNode. To use it, you have to autowire ObjectMapper in your service/controller. Then you can use:
#GetMapping
public ObjectNode sayHello() {
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("key", "value");
objectNode.put("foo", "bar");
objectNode.put("number", 42);
return objectNode;
}
This approach allows you to add child objects, arrays, and use all various types.
You can either return a response as String as suggested by #vagaasen or you can use ResponseEntity Object provided by Spring as below. By this way you can also return Http status code which is more helpful in webservice call.
#RestController
#RequestMapping("/api")
public class MyRestController
{
#GetMapping(path = "/hello", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> sayHello()
{
//Get data from service layer into entityList.
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject entity = new JSONObject();
entity.put("aa", "bb");
entities.add(entity);
}
return new ResponseEntity<Object>(entities, HttpStatus.OK);
}
}
you can also use a hashmap for this
#GetMapping
public Map<String, Object> get() {
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("results", somePOJO);
return map;
}
More correct create DTO for API queries, for example entityDTO:
Default response OK with list of entities:
#GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public List<EntityDto> getAll() {
return entityService.getAllEntities();
}
But if you need return different Map parameters you can use next two examples
2. For return one parameter like map:
#GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getOneParameterMap() {
return ResponseEntity.status(HttpStatus.CREATED).body(
Collections.singletonMap("key", "value"));
}
And if you need return map of some parameters(since Java 9):
#GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getSomeParameters() {
return ResponseEntity.status(HttpStatus.OK).body(Map.of(
"key-1", "value-1",
"key-2", "value-2",
"key-3", "value-3"));
}
#RequestMapping("/api/status")
public Map doSomething()
{
return Collections.singletonMap("status", myService.doSomething());
}
PS. Works only for 1 value
If you need to return a JSON object using a String, then the following should work:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
...
#RestController
#RequestMapping("/student")
public class StudentController {
#GetMapping
#RequestMapping("/")
public ResponseEntity<JsonNode> get() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree("{\"id\": \"132\", \"name\": \"Alice\"}");
return ResponseEntity.ok(json);
}
...
}
use ResponseEntity<ResponseBean>
Here you can use ResponseBean or Any java bean as you like to return your api response and it is the best practice. I have used Enum for response. it will return status code and status message of API.
#GetMapping(path = "/login")
public ResponseEntity<ServiceStatus> restApiExample(HttpServletRequest request,
HttpServletResponse response) {
String username = request.getParameter("username");
String password = request.getParameter("password");
loginService.login(username, password, request);
return new ResponseEntity<ServiceStatus>(ServiceStatus.LOGIN_SUCCESS,
HttpStatus.ACCEPTED);
}
for response ServiceStatus or(ResponseBody)
public enum ServiceStatus {
LOGIN_SUCCESS(0, "Login success"),
private final int id;
private final String message;
//Enum constructor
ServiceStatus(int id, String message) {
this.id = id;
this.message = message;
}
public int getId() {
return id;
}
public String getMessage() {
return message;
}
}
Spring REST API should have below key in response
Status Code
Message
you will get final response below
{
"StatusCode" : "0",
"Message":"Login success"
}
you can use ResponseBody(java POJO, ENUM,etc..) as per your requirement.
I use to return Map<String,Object> in the Controller by using the toMap() method of org.json.JSONObject as follows.
#GetMapping("/json")
public Map<String, Object> getJsonOutput() {
JSONObject jsonObject = new JSONObject();
//construct jsonObject here
return jsonObject.toMap();
}
you can do this :
#RestController
#RequestMapping("/api")
class MyRestController
{
#GetMapping(path = "/hello")
public JSONObject sayHello()
{
return new JSONObject("{'aa':'bb'}").toMap();;
}
}

How to send a query params map using RESTEasy proxy client

I'm looking for a way to pass a map that contains param names and values to a GET Web Target. I am expecting RESTEasy to convert my map to a list of URL query params; however, RESTEasy throws an exception saying Caused by: javax.ws.rs.ProcessingException: RESTEASY004565: A GET request cannot have a body.
. How can I tell RESTEasy to convert this map to a URL query parameters?
This is the proxy interface:
#Path("/")
#Consumes(MediaType.APPLICATION_JSON)
public interface ExampleClient {
#GET
#Path("/example/{name}")
#Produces(MediaType.APPLICATION_JSON)
Object getObject(#PathParam("name") String name, MultivaluedMap<String, String> multiValueMap);
}
This is the usage:
#Controller
public class ExampleController {
#Inject
ExampleClient exampleClient; // injected correctly by spring DI
// this runs inside a spring controller
public String action(String objectName) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
// in the real code I get the params and values from a DB
params.add("foo", "bar")
params.add("jar", "car")
//.. keep adding
exampleClient.getObject(objectName, params); // throws exception
}
}
After hours digging down in RESTEasy source code, I found out that there is no way to do that though interface annotation. In short, RESTEasy creates something called a 'processor' from org.jboss.resteasy.client.jaxrs.internal.proxy.processors.ProcessorFactory to map the annotation to the target URI.
However, it is really simple to solve this issue by creating a ClientRequestFilter that takes the Map from the request body (before executing the request of course), and place them inside the URI query param. Check the code below:
The filter:
#Provider
#Component // because I'm using spring boot
public class GetMessageBodyFilter implements ClientRequestFilter {
#Override
public void filter(ClientRequestContext requestContext) throws IOException {
if (requestContext.getEntity() instanceof Map && requestContext.getMethod().equals(HttpMethod.GET)) {
UriBuilder uriBuilder = UriBuilder.fromUri(requestContext.getUri());
Map allParam = (Map)requestContext.getEntity();
for (Object key : allParam.keySet()) {
uriBuilder.queryParam(key.toString(), allParam.get(key));
}
requestContext.setUri(uriBuilder.build());
requestContext.setEntity(null);
}
}
}
PS: I have used Map instead of MultivaluedMap for simplicity

Categories

Resources