Difference between "addError(ObjectError error)" and "rejectValue(String field, String errorCode)" in Spring - 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.

Related

Putting Spring WebFlux Publisher inside Model, good or bad practice?

I'm working on a code audit on a SpringBoot Application with Spring WebFlux and the team is putting Publisher directly inside the Model and then resolve the view.
I'm wondering if it is a good or bad practice because it seems to be working but in that case, which component is in charge of executing the Publisher ?
I think that it's the ViewResolver and it should not be its job. What do you think ?
Moreover, if the Publisher is not executed by the Controller, the classes annotated by #ControllerAdvice such like ExceptionHandler won't work if these Publisher return an error, right ?
Extract of the Spring WebFlux documentation :
Spring WebFlux, unlike Spring MVC, explicitly supports reactive types in the model (for example, Mono or io.reactivex.Single). Such asynchronous model attributes can be transparently resolved (and the model updated) to their actual values at the time of #RequestMapping invocation, provided a #ModelAttribute argument is declared without a wrapper, as the following example shows:
#ModelAttribute
public void addAccount(#RequestParam String number) {
Mono<Account> accountMono = accountRepository.findAccount(number);
model.addAttribute("account", accountMono);
}
#PostMapping("/accounts")
public String handle(#ModelAttribute Account account, BindingResult errors) {
// ...
}
In addition, any model attributes that have a reactive type wrapper are resolved to their actual values (and the model updated) just prior to view rendering.
https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-ann-modelattrib-methods
Doesn't come as a shock to me.
Actually seems to be a good trade off between complexity and efficiency when the Publisher is handling complex stuff.
It has the advantage of executing the Publisher only if and when needed.
Although it might be a problem if the ModelMap handler does not have the capacity to use it properly.
As for the exceptional cases, maybe you do not want it to be executed and just printed, thus failing faster.
As for the question about what is executing the Publisher, a specific ViewResolver can be used as it is the component responsible for the "rendering". IMHO that's it's job. I do not know if a standard ViewResolver can be used for detecting values vs publishers and handle those automagically, yet this seems completely doable and efficient.

Implementing Spring Security AccessDecisionManager by example

Please note: someone seems to be serially DVing my questions without explanation. This question is on topic, is not a duplicate, shows research and provides an SSCCE. If you wish to DV or CV it, that's fine, but please provide a comment as to why so I can have a chance to address your concerns...
Spring Boot 2.3.x and Spring Security here.
I have some pretty complicated authorization logic, and so I believe I need to write my own AccessDecisionManager impl and wire it into my WebSecurityConfigurerAdapter impl (if that's wrong or misunderstood in any way, please correct me!).
So then, to implement your own AccessDecisionManager you need to implement 3 methods, one of which is:
public class MyCustomAccessDecisionManager implements AccessDecisionManager {
#Override
public void decide(
Authentication authentication,
Object object,
Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
// TODO
}
}
I have scoured the Google Gods high and low, and for the life of me I cannot find a meaningful, real world example of what the Object object and Collection<ConfigAttribute> configAttributes arguments are, what they are used for, how they are intended on being used, and what some real world (concrete) examples of them will be at runtime.
The Authentication argument is obvious: it is my auth token and will contain the principal, possibly their credential, and a list of GrantedAuthorities (permissions) associated with the principal.
But the other two arguments (object and configAttributes ) are absolute mysteries to me.
Does anybody know what these arguments are, what some real world use cases of them are, and how they are intended to be used?
As JavaDoc for AccessDecisionManager says:
object – the secured object being called
Usually, it's an instance of the MethodInvocation interface and it represents the method for which call security decision should be performed.
configAttributes - the configuration attributes associated with the secured object being invoked
It's a collection of metadata attributes related to the security object (Method). For example, it can contain information about annotations related to this method, such as #PermitAll, #PreAuthorize, #PostFilter, etc.

How to add a custom ContentHander for JAXB2 support in Spring 3 (MVC)?

Scenario: I have a web application that uses Spring 3 MVC. Using the powerful new annotations in Spring 3 (#Controller, #ResponseBody etc), I have written some domain objects with #XML annotations for marhalling ajax calls to web clients. Everything works great. I declared my Controller class to have a return type #ResponseBody with root XML object - the payload gets marshalled correctly and sent to Client.
The problem is that some data in the content is breaking the XML compliance. I need to wrap this with CDATA when necessary. I saw a POST here How to generate CDATA block using JAXB? that recommends using a custom Content Handler. Ok, fantastic!
public class CDataContentHandler extends (SAXHandler|XMLSerializer|Other...) {
// see http://www.w3.org/TR/xml/#syntax
private static final Pattern XML_CHARS = Pattern.compile("[<>&]");
public void characters(char[] ch, int start, int length) throws SAXException {
boolean useCData = XML_CHARS.matcher(new String(c,start,length)).find();
if (useCData) super.startCDATA();
super.characters(ch, start, length);
if (useCData) super.endCDATA();
}
}
Using Spring MVC 3, how do I achieve this? Everything was "auto-magically" done for me with regards to the JAXB aspects of setup, Spring read the return type of the method, saw the annotations of the return type and picked up JAXB2 off the classpath to do the marshalling (Object to XML conversion). So where on earth is the "hook" that permits a user to register a custom Content Handler to the config?
Using EclipseLink JAXB implementation it is as easy as adding #XmlCDATA to the Object attribute concerned. Is there some smart way Spring can help out here / abstract this problem away into a minor configuration detail?
I know Spring isn't tied to any particular implementation but for the sake of this question, please can we assume I am using whatever the default implementation is. I tried the Docs here http://static.springsource.org/spring-ws/site/reference/html/oxm.html but it barely helped at all with this question from what I could understand.
Thanks all for any replies, be really appreciated.
Update:
Thanks for the suggested answer below Akshay. It was sufficient to put me on right tracks. Investigating further, I see there is a bit of history with this one between Spring version 3.05 and 3.2. In Spring 3.05 it used to be quite difficult to register a custom MessageConverter (this is really the goal here).
This conversation pretty much explains the thinking behind the development changes requested:
https://jira.springsource.org/browse/SPR-7504
Here is a link to the typically required class override to build a cusom solution:
http://static.springsource.org/spring/docs/3.1.0.M1/javadoc-api/org/springframework/http/converter/AbstractHttpMessageConverter.html
And the following Question on stack overflow is very similar to what I was asking for (except the #ResponseBody discussion relates to JSON and jackson) - the goal is basically the same.
Spring 3.2 and Jackson 2: add custom object mapper
So it looks like usage of , and overriding MarshallingHttpMessageConverter is needed, registering to AnnotationMethodHandlerAdapter. There is a recommended solution in link above to also get clever with this stuff and wrap the whole thing behind a custom defined Annotation.
I haven't yet developed a working solution but since I asked the questions, wanted to at least post something that may help others with the same sort of question, to get started. With all due respect, although this has all improved in Spring 3.2, it's still bit of a dogs dinner to get a little customization working... I really was expecting a one liner config change etc.
Rather than twist and bend Spring, perhaps the easiest answer for my particular issue is just to change JAXB2 implementation and use something like Eclipse Link JAXB that can do this out of the box.
Basically you need to create a custom HttpMessageConverter. Instead of relying on the Jaxb2RootElementHttpMessageConverter that spring uses by default.
Unfortunately, customizing one converter means you are telling spring that you will take care of loading all the converters you need! Which is fairly involved and can get complicated, based on whether you use annotations, component scanning, Spring 3.1 or earlier, etc.. The issue of how to add a custom converter is addressed here: Custom HttpMessageConverter with #ResponseBody to do Json things
In your custom message converter you are free to use any custom JAXB2 content handlers.
Another, simpler approach to solve your original problem would be to use a custom XmlJavaTypeAdapter. Create a custom implementation of javax.xml.bind.annotation.adapters.XmlAdapter to handle CDATA, in the marshal method wrap the return value with the cdata braces. Then in your mapped pojo, use the XmlAdapter annotation, pass it the class of your custom adapter and you should be done.
I have not myself implemented the adapter approach, so couldn't provide sample code. But it should work, and won't be a lot of work.
Hope this helps.

Spring 3, ReST, #ResponseBody and #ExceptionHandler

I have been trying to get exception handling working in my simple Spring 3 based ReST web services. Based on everything I have seen, there is a bug that prevents this from working automatically with the #ResponseBody and #ExceptionHandler annotations
https://jira.springsource.org/browse/SPR-6902
So given that it isn't supported until Spring 3.1 or 3.0.6, what is the current best method for doing exception handling? I have seen numerous posts but haven't found a clear answer that has worked for me. An ideal solution would be one that automatically provides support for both xml and json
Do I have to manually define the entire marshalling setup? Won't this remove the need for the annotations that make using Spring 3 rest support worth it?
Seems in order to manually define marshalling (i.e. Jaxb2Marshaller) I need to add a new dependency on spring-ws which is a bit of a pain
Is it easier to just define a 'Response' object that all my methods return and wrap all functions in try/catch blocks?
You can redirect on error and then return something in #ResponseBody:
#ExceptionHandler(Exception.class)
public ModelAndView handleMyException(Exception exception) {
return new ModelAndView("redirect:errorMessage?error="+exception.getMessage());
}
#RequestMapping(value="/errorMessage", method=RequestMethod.GET)
#Responsebody
public String handleMyExceptionOnRedirect(#RequestParameter("error") String error) {
return error;
}
Little ugly, but this is just work around till the fix will be available.
This is a good workaround, but with one addition. The #ExceptionHandler(Exception.class)
should be #ExceptionHandler(MyException.class, YourException.class) as you can get into a loop using the general Exception class.
You can then test for (ex instanceof Myexception) to determine the message to display if need be.

Flex/Spring/Hibernate validation - spring Validator and ExceptionTranslator

I'm beginner in mentioned technologies and forgive me if I ask some dumb questions.
I have design problem with validation code in my app. Very often i break the DRY principle. Besides, validation confuses me somehow. I always questioning myself where to put some validation stuff, checked vs unchecked, what to propagate, what to validate etc. Still, there are some topics about mentioned stuffs, so i will concentrate on my specific problem with F/S/H technologies.
For example, my DAO save method have following validation:
public void save(Person p){
if(p==null) throw IllegalArgumentException("Person object is required...");
//...
}
Exactly the same validation i also have in delete, update and read methods in DAO layer.
I was looking for some solution with com.springframework.validation.Validator interface, but I bump in to problem with propagation of error codes to Flex client.
Maybe, i could do something like this...
public void save(Person p){
BeanPropertyBindingResult err = new BeanPropertyBindingResult(p,"Errors");
//myValidator will be injected
myValidator.validate(p,err);
//...
throw MyException("Message",err);
//...
}
I don't know if this is good approach. What validation approach to use to minimize repetition of such validation code. If someone can to give me some direction, hint, link, I'll appreciate it.
Maybe you should try some Design by Contract annotation driven solution like Contract4j?

Resources