In Hibernate Validator, how can the method validation tell the caller that the return value may be null? - hibernate-validator

The method validation in Hibernate Validator can tell callers that the return value is #NotNull, but how can I tell the caller that the return value might be null? In Findbugs, I have #CheckForNull, but that's only active at compile time, not at run time.

it sounds like you are asking for something like #Nullable. That is not part of Bean Validation and most likely won't be. See also the discussion of the expert group around this - http://lists.jboss.org/pipermail/beanvalidation-dev/2013-January/thread.html
What can you achieve with a #Nullable anyways. In the context of Bean Validation, the implementation would just always return true.

Related

Constraints configuring for Beans Validation via a properties file

I'd like to configure bean validation (JEE6) constraints via a properties file or database.
So for instance the Max value below would get pulled from the properties file or database.
Is this possible in ?
#Max(value = 1)
private int elvis;
Any suggestions on a possible approach.
It is not possible via standard Bean Validation. The default as per specification are annotations or as alternative XML.
In theory, Hibernate Validator has the (internal) concept of a MetaDataProvider and one could think of plugging in a DbMetaDataProvider. However, that would be quite some work and I am not sure that it would be worth the effort.
What is you use case anyways? Why don't you use XML?
You can write your own constraint and validator for that. The constraint’s argument could be some identifier of the validation parameters stored in database and the validator could query database for these parameters to validate a value according to them.
Some hints:
See this validator for an idea how to reuse existing validators from your “über validator”.
See this question and this answer for a hint how to inject bean to a validator.

Model Binding and Validation Errors

I am using asp.net MVC3 and I am very new to this technology.
My models are designed in such a way that the properties will throw validation errors if the data is invalid. In this case, the properties are not set with invalid data.
When I redisplay my editing-view, validation error messages are shown; however the values that the user previously entered are gone because the model that it is bound to only contains the old-valid data.
For example, say I had a Person class and the Name property cannot be a null or empty string otherwise it throws a validation exception and prevents the property from being set. Now say the user removes the value from the Name property and tries to save the Person from the web. A validation exception will be thrown and handled properly to add the error to the ModelState so that it is displayed on the screen; however the old value for the Name is redisplayed since the invalid, empty string never made it into the property.
I do not know how to solve this problem and any advice on the issue would be greatly appreciated.
My advise is allow invalid data but use validation attributes. You wont save invalid entities so there is no problem and this is the standard approach these days. If you don't want do that, there is no easy solution. Most simple solution would be using the info from Request.Form
You should implement IValidatableObject to performe this kind of validation at server side.
From MSDN IValidatableObject Interface:
Provides a way for an object to be invalidated.
Theres an exemple here Using IValidatableObject Custom Validation, also from MSDN.
The solution to this problem was to create a ViewModel that allowed invalid data to be entered into this. This solution also simplified my ModelBinder classes because it took on most of the work.

HibernateValidator is initializing Constraints when first evaluated, not at system load time

We are using HibernateValidator, and have the following issue:
We create our own validator object which implements ConstraintValidator. The first time the validator validates any specific Constraint, it calls the initialization code for that constraint. This is causing a performance problem. Is there any way that we can tell HibernateValidator to run the initialization for a Constraint at load time, not the first time the Constraint is actually validated?
Thanks
There is no such way. The spec basically just says:
The life cycle of a constraint validation implementation instance is
undefined. Compliant implementations are allowed to cache
ConstraintValidator instances retrieved from the
ConstraintValidatorFactory. The initialize method is called by the
Bean validation provider prior to any use of the constraint
implementation.
It is only guaranteed that initialize is called prior a isValid call. There is no way to pre-initialize. The reason initialize is only called once is, because Validator caches the ConstraintValidator instance, but this is nothing I would rely on.
If you really want to make sure that initialize is called at startup you could do some warmup validation during this phase.
OOI, what are you doing in initialize that it becomes a performance issue?

How to abort an ASMX request based on logic in the constructor?

I have a common base class from which all my ASMX webservice classes will inherit. In the constructor, I want to do some common authentication checks; if they fail, I would like to halt processing right away (subclass's code would not get executed) and return a 401-status-code response to the caller.
However, the common ASPX-like ways of doing this don't seem to work:
Context.Response.End(); always kicks back a ThreadAborted exception to the caller, within a 500-status-code response. Even if I explicitly set Context.Response.StatusCode = 401 before calling End(), it is ignored. The result is still a 500-response, and the message is always "thread-aborted-exception".
MSDN suggests I use HttpContext.Current.ApplicationInstance.CompleteRequest() instead. However, this does not stop downstream processing: my subclass's functions are still executed as if the constructor had done nothing. (Kind of defeats the purpose of checking authorization in the constructor.)
I can throw a new HttpException. This is a little better in that it does prevent downstream processing, and at least it gives me control over the exception Message returned to the caller. However, it isn't perfect in that the response is still always a 500.
I can define a DoProcessing instance var, and set it to true/false within the constructor. Then have every single WebMethod in every single subclass wrap its functionality within an if (DoProcessing) block... but let's face it, that's hideous!
Is there a better / more thorough way to implement this sort of functionality, so it is common to all my ASMX classes?
edit: Accepting John's answer, as it is probably the best approach. However, due to client reluctance to adopt additional 3rd-party code, and some degree of FUD with AOP, we didn't take that approach. We ended up going with option #3 above, as it seemed to strike the best balance between speed-of-implementation and flexibility, and still fulfill the requirements.
The best way to do it would be to switch to WCF, which has explicit support for such a scenario.
If you must still use ASMX, then your best bet is to call the base class methods from each web method. You might want to use something like PostSharp to "magically" cause all of your web methods to call the base class method.
Context.Response.Write("My custom response message from constructor");
Context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
Context.Response.End();
That code prevent to pass in web method after constructor.

testing controller action which returns RedirectToRouteResult

I have an action in my controller:
RedirectToRouteResult Create(UserDTO UserDTO)
Which at some point decides with which HTML to respond after a post request by redirecting to an action:
return ModelState.IsValid ? RedirectToAction("ThanksCreate") : RedirectToAction("Register");
In my unit tests I would like to get hold of the ‘views’ modelstate somehow like this:
var modelState = result.ViewData.ModelState;
Assert.IsFalse( modelState.IsValid );
where ‘result’ (ViewResult) is the result of the action ‘Create’ depending on the submitted DTO. My dilemma is that my action ‘returns’ a RedirectToRouteResult which I thought is quite nice but it might not be testable or is it?
How could I get hold of the ModelState in my scenario? Thanks.
Best wishes,
Christian
enter code here
I updated my answer on your other (related) question. In this scenario, I think it's arguably incorrect to test the model state as it isn't exposed outside the method. Rather, you should use your set up to induce correct/incorrect model state and test that the method has the proper output based on the given set up.

Resources