Kotlin class.java of generic data type - spring

I am quite noob in Kotlin, so here is my question:
I am using <T> T convert(#Nullable Object source, Class<T> targetType);
There is a TestDto<NounDto> type, which is my targetType.
When I try to pass TestDto<NounDto>::class.java as a param to converter.convert(entity, TestDto<NounDto>::class.java), I get "Only classes are allowed on the left hand side of a class literal" error message.
Is it possible at all to pass this data type? And how if yes?
Thanks in advance for replies!

Related

How Spring deserializes query params into Kotlin data classes?

Assume a Spring #RestController with a simple #GetMapping that accepts a VenueQuery dataclass as its parameter:
data class VenueQuery(
val cityId: Long? = null,
val countryIso: String? = null,
)
#RestController
open class VenueController {
#GetMapping("/venues")
open fun getVenues(
request: HttpServletRequest,
response: HttpServletResponse,
venueQuery: VenueQuery
) { ... }
}
Runing the code as above, works "well". GET /venues?cityId=1&countryIso=CZ gets deserialised into VenueQuery(cityId=1, countryIso="CZ"}.
However, annotating the venueQuery function argument with #RequestParam causes the same request to be rejected with BAD_REQUEST "Missing required parameter 'venueQuery'". This makes sense, but renders the former case even more confusing.
After searching for quite some time I still can't answer the following questions:
Where can I find a documentation that describes this behavior in more detail? I.e. any reference I could point to instead of relying on a one-time observation?
Is the first case even an expected behavior?
How does spring knows it should populate the venueQuery argument with query params, but not the request and response params? Does it infer by its types of servlet request/response?
Generally I struggle to find any documentation (not a "how to" but documentation) about how the Spring annotations and principles apply in Kotlin. Are there any notable sources?
Thanks for any answers!
Expected behavior?
Yes.
How does spring knows it should populate the venueQuery argument with query params?
By its type. Try two of VenueQuery and see what happens.
Generally I struggle to find any documentation...
Unless the behavior is markedly different, there’s no special mention for Kotlin. As for “notable sources”, I’ve always found the answers I’m looking for in their source code. Grab a cup of coffee and fire up a debugger, you’ll too.

Coding to an interface on a Spring Controller method with #RequestMapping

I have a Controller with the following method:
#RequestMapping(method = POST)
public ModelAndView emailRegister(EmailParameter parameters, ModelMap model) {}
Where EmailParameter is an interface. I understand Spring (magically?) maps the incoming HTTP parameters to my object fields by name, and it can't do this as I have declared an Interface.
Is it possible to declare an interface here, if so is there additional config I need somewhere?
I don't have extensive programming experience so I may be wrong in trying to use an Interface type here, but I believe this is what I should be doing?
Additionally if someone could explain how Spring maps the request parameters to my object fields, that would be much appreciated. Or a link to where this is explained, as I haven't been able to find one!
Thanks
You shouldn't use Interface because Spring needs to instantiate that object, otherwise you will be requiring the property editors OR converters.
Read the following post to know about How Spring MVC Binds Parameter?
Read section "Binding Domain Object" in following link.
https://web.archive.org/web/20160516151809/http://www.jpalace.org/document/92/binding-and-validation-of-handler-parameters-in-spring-mvc-controllers

Is it valid to apply JsonConverter for query string arguments

All,
My team has recently encountered with a roadblock of using JsonConverter with HttpRequest arguments.
My API method definition is as below
[HttpGet]
[GET("Values/Data/{inputString}/{inputDateTime:datetime}")]
public HttpResponseMessage GetResponseForData(string inputString, [JsonConverter(typeof(DateTimeToTicksConverter))] DateTime inputDateTime)
{
// do something here
}
The DateTimeToTicksConverter is to intercept the DateTime attributes and then transform as defined. When this attribute is applied on the attributes of a model it works fine. However when the attribute is defined as in the API above it doesn't intercept during request.
I would like to know if it is valid to expect JsonConverter to intercept the request parameters?
Any help is much appreciated. Thanks
That's not meant to be used there, that attribute is just metada which json.net looks for when serializing a class to JSON, but webapi has no knowledge of it.
You can achieve what you want using a custom httpparameterbinding. You can find more info here http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Spring MVC request / command objects

Is there a convenient way to turn something like this..
#RequestMapping("/some/action/{q}/...")
public void doSomething(#PathVariable("q"), oh, my, god, a, billion, annotated parameters) { .. }
Into something like this..
#RequestMapping("/some/action/{q}/...")
public void doSomething(NiceEncapsulatingRequetObject request) { .. }
With Spring MVC?
After checking the docs, it doesn't seem like it is supported out of the box. You could try to create your own HandlerMethodArgumentResolver which gives you this feature. You might run into some issues since you'll need a circular reference between your implementation and the HandlerMethodArgumentResolverComposite instance. Nevertheless I think it should be possible.
Yes spring supports this out of the box, it is usualy refered to as bean binding.
Basicly you create an object with paramaters with the same name,
so if you have a paramater "q", your object should contain a private string q with both getter and setter present. It's also prefered not to use any constructors.
Spring will just fill in the paramaters it has in your object and pass it via the method's paramater.
You can create you own object like NiceEncapsulatingRequetObject and it's attributes should be String oh, Integer my etc. If you send the request with the exact names it will work

Difference between "addError(ObjectError error)" and "rejectValue(String field, String errorCode)" in Spring

I am trying to understand the difference between:
void addError(ObjectError error) (from
org.springframework.validation.Errors)
void rejectValue(String field,
errorCode) (from org.springframework.validation.BindingResult)
I did read the Spring javadocs but could not understand the difference between the two.
Can anyone please provide an explanation or a code sample?
rejectValue simply encapsulates the call to addError() providing ObjectError or FieldError instance.
According to javadoc addError() only supports ObjectError And FieldError, so it's NOT about creating custom ObjectErrors
void org.springframework.validation.BindingResult.addError(ObjectError error)
Add a custom ObjectError or FieldError to the errors list.
Intended to be used by cooperating strategies such as BindingErrorProcessor.
So addError() is more suitable for the framework developers and rejectValue() is the way to go.

Resources