Change language of the spring context with the parameter in the body - spring

I need to change the language of the spring context. The problem is that it doesn't reach me by header or by URL parameter. How could I read the parameter of the body and change it from the whole context?
EDIT:
The client sends the locale parameter in the request body. I need to capture that parameter and set the language in the spring context.
Body example:
{
"name":"username",
"locale": "en"
}

Related

Add and remove arbitrary input fields from Swagger UI in Spring Boot

I have a Spring Boot application with springfox-swagger-ui. I need to:
Make Swagger UI display input field for a parameter that does not appear among the request handler params in my controller. For example, the request contains a hashCode parameter, which I verify with a HandlerInterceptorAdapter and then I don't need anymore, thus I don't list it among the request handler params. But I want to have it in Swagger UI.
Remove an input field from Swagger UI that corresponds to a parameter that I have in my request handler in my controller. For example, the request contains a userId, which I use to construct an User object with a HandlerMethodArgumentResolver and then inject it into the request handler by adding a parameter of type User. Thus I don't want Swagger UI to create User input field, but instead a userId input field.
To summarize, I need to show an input field in Swagger UI that does not correspond to any request handler parameter, and I need to hide an input field in Swagger UI that corresponds to a request handler parameter. How to do this?

Rest doc for PUT request with request param but without request body setting content type as form url encoded

I have noticed that rest doc (HttpRequestSnippet.java) is setting APPLICATION_FORM_URLENCODED_VALUE as content type for PUT with request parameter and without request body. This should be corrected, may be introducing a MEDIATYPE as NONE and set content type as NONE or ALL when request body/content empty.
For example, my put request is like below:
/api/v1/config/?mode=unknow
This sounds like a bug in Spring REST Docs' HttpRequestSnippet for which I've opened an issue.

How can I use the bot composer to dynamically configure the body part of a HTTP REQUEST

I am using Bot Composer to publish my first chatbot. I need to construct the chatbot to send out an HTTP POST request to fetch external resources from a remote website. As specified by the composer interface, I can embed JSON, form data, or string in the body of the HTTP POST request. Instead of hard-coding the body part of the POST request, I need to pass in one or multiple properties (chatbot's variable) to generate the body of the HTTP POST dynamically. Here are my questions:
(1) can I pass a variable to the body part of the HTTP REQUEST (such as POST)? can I embed a property such as $(user. name) in the HTTP POST body?
For example, can I embed a property such as $(user.name) in a string or form data (such as fname=$(user. name) to construct the body part of the HTTP POST REQUEST?
(2) The document specifies that there is a pre-build function JSON to serialize data. If I understand correctly, I can't pass a variable (such as $(user. name) to the JSON pre-built function. Therefore, I will probably need to embed an expression in the body to pass the variable. Yet, I couldn't find any detailed information. Is there anywhere I can find a good example showing how to write an expression inside the body part of the HTTP REQUEST
Thanks for any information/assistance.
Yes, you can do this. The simplest way is to set the body to Object and then put in your structured json, something similar to:
{
"userinfo": {
"username": "${user.username}",
"name": "${user.personalname}",
"favoritecolor": "${user.favcolor}",
"profileupdated":"${dialog.userprofileuptodate}"
}
}
I am trying to figure out how to set it up in an adaptive expression in LG, and then be able to refrence it with something like:
# APIBodyTemplate()
-```
{
"userinfo": {
"username": "${user.username}",
"name": "${user.personalname}",
"favoritecolor": "${user.favcolor}",
"profileupdated":"${dialog.userprofileuptodate}"
}
}
```
And then using something like the following in an expression in the body field:
=json(APIBodyTemplate()), but that is not quite working yet. Might be a bug. I will update when I have more info.

#RequestHeader required property behavior for request paramter and value

Can we make a header parameter mandatory but not the value using #RequestHeader?
For example if we use,
#RequestHeader(value = "abc", required = true)
both parameter and it value has to be there.
Edit:
Suppose i call some rest api has above request header param with "abc" but no value. So in this case i am able to invoke the rest api successfully since i have invoke with "abc" header param even i did not enter a value to it. Due to some governance tool rule, i need to have a specific header param but i dont want force user to enter any value.
Spring 5.2 and lower
The #RequestHeader doesn't provide additional facility to check the value of the parameter to be mandatory i.e. not null.
Given below are the available fields as per Spring Doc
defaultValue: The default value to use as a fallback.
name: The name of the request header to bind to.
required: Whether the header is required; null values are allowed
value: Alias for name()
So what you can do is read the parameter either with the help of #RequestHeader or inject a HttpServletRequest request, read by request.getHeader(...) and check inside the controller method if the value exists and then can call methods to perform the necessary logic.
Although you can make sure that the parameter exists with the help of required attribute for e.g. #RequestHeader(value = "Authorization", required = true) String authorization).
Spring 5.3+
The required field was tightened up, both the property and the value should exist. From the release notes:
The #RequestHeader annotation detect a null conversion result value and treat it as missing. In order to allow an empty value to be injected as a null argument, either set required=false on the argument annotation, e.g. #RequestParam(required=false), or declare the argument as #Nullable.
As #Mudassar said, #RequestHeader doesn't provide additional facility to check the value of the parameter to be mandatory i.e. not null.
It is related to this issue: https://github.com/spring-projects/spring-framework/issues/23939
I developed a workaround for this problem using an annotation #RequestHeaderNonNull that I've created: https://github.com/armandoalmeida/request-header-required-non-null
I hope I've helped you!

Validate request headers with Spring validation framework

Is it possible to use the Spring validation framework with Spring MVC to validate the presence and value of an HTTP request header?
To check the presence of a request header, you don't need the validation framework. Request header parameters are mandatory by default, and if a mandatory header is missing in a request, Spring MVC automatically responds with 400 Bad Request.
So the following code automatically checks the presence of the header "Header-Name"...
#PostMapping("/action")
public ResponseEntity<String> doAction(#RequestHeader("Header-Name") String headerValue) {
// ...
}
... and if the header shall be optional, the annotation would need to be replaced by:
#RequestHeader(name = "Header-Name", required = false)
To check the value of a request header, the Spring validation framework can be used. To do this, you need to
Add #Validated to the controller class. This is a workaround needed until this feature is implemented.
Add the JSR-303 annotation to the request header parameter, e.g.
#RequestHeader("Header-Name") #Pattern(regexp = "[A-Za-z]*") String headerValue
Note however that this will result in a 500 in case of an invalid header value. Check this question for how to also get the correct status code (i.e. 400) for this case.
I don't see how this would be possible, since the validation framework only operates on your domain objects, not on the HTTP request itself. Specifically, the Validator interface doesn't specify any methods that take the HttpServletRequest object, which is what you'd need to have access to in order to grab the headers and test them.
Using the validation framework feels like the wrong solution to whatever problem you're trying to solve, especially since it's hard to know how there'd be a unique HTTP request header for a given form submission. Are you looking to test for an HTTP header that should always be present in requests to your app? Then you might want to consider implementing a HandlerInterceptor, which will intercept and process all requests to pages that you've mapped in any HanderMappings. Are you looking to test for an HTTP header that should always be present in any page view of your app? Then you'd want to implement a Filter, which operates outside of the context of Spring MVC.

Resources