JSR 303 – Patterns and Anti-patterns with Hibernate and Spring Web Flow - Under The Hood

« SharePoint 2010 - Search Error - "The search service is not able to connect to the machine that hosts the administration component" | Main | An Ode to LINQ »

07/13/2011

Comments

Feed You can follow this conversation by subscribing to the comment feed for this post.

billy

Thanks for the post. So I have to create a ModelValidator and another Validator for my object I want validated? Webflow won't do this validation automatically like MVC does?

Jimmy Ray

The ModelValidator is simply a class that I used to aggregate calls. You don't need it. You don't need JSR-303 Javax Bean Validation either with SWF. You could go this route: http://static.springsource.org/spring-webflow/docs/2.0.x/reference/html/ch04s10.html

Or you can use JSR-303 like so: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/validation.html#validation-beanvalidation

Or this: http://static.springsource.org/spring/docs/3.0.0.RC3/spring-framework-reference/html/ch05s07.html

My approach lets you use JSR-303 constraint annotations, but also allows you to pick and use, based on view-state of your web flow, what constraints to validate.

billy

Do I need to have my model objects extend AbstractModel? When trying your example I get an error saying my model object is not type AbstractModel.

Jimmy Ray

yes, I have change the Customer type definition to read: public class Customer extends AbstractModel {

I do not supply this AbstractModel class, but you don't need my implementation to make this work. Worst case scenario, you could change generic type parameters in the ModelValidator.

billy

Yea thats what I ended up doing using a generic type. You've been very helpful but I have one more question. When stepping through the code I don't see how the valid property is ever false. In the ModelValidator it is set to true and then it is set to false inside the for loop of messages. messages is passed to the validateModelProperties method but in the CustomerValidator it is set as a new LinkedHashMap. What am I missing? It doesn't seem like the map will every have any records.

Jimmy Ray

The way we use it is that we pass model objects (Customer in this case) into the ModelValidator. The ModelValidator calls the JSR303 validator with this line: constraintViolations = validator.validateProperty(model, key);

If the validation fails: if (constraintViolations.size() > 0) {
isValid = false;

Then the isValid is marked to be true. If you create a Customer model instance and leave firstName null, you should see it return errors.

billy

Yea I understand that. The question was about the line above that. The for(String key : messages.keySet()). I just don't see how messages gets populated.

Jimmy Ray

messages is a map that is passed into the method. The messages map contains keys that are the strings ("firstName...") that match the bean properties that you are trying to validate. For each bean property, the ModelValidator calls validateProperty.

billy

Thanks again for the response. How does the messages map get populated in the CutomerValidator class? I see it declared like this Map> propertyMap = new LinkedHashMap>();
and then passed into the method.

Jimmy Ray

Put this (propertyMap.put("firstName", null);) in the CustomerValidator, before you call the ModelValidator.

billy

Got it! Thank you so much for helping me with this.

Sandile

I've been playing anourd with groovy/grails and really like the way you can fall back to standard java if needed. Looking at your list I feel ancient, but I've started exploring HTML5. Of all the things on the list I think Object-Oriented to the hybrid is most likely to happen because in my experience very few developers really understand OOP and they been writing bloated inefficient code that hopefully a hybrid solution may reign in. Speaking of trends what about process wise? I've been forced to look at Lean Software Development and it seems just another use for SCRUM and Agile techniques. Where do you think the methodology trends are going to take us?[]Reply from :I'm not sure where the methodology trends are going, but I know what I'd like to see. First, I want waterfall and big design up front to go away. Those just haven't worked on any teams or any situations I've been a part of. Second, I want agile stuff be a little less rigid. It's funny, but the people who are the biggest agile evangelists are generally the first people to tell you that you're doing it wrong. I'm not excited about using scrum, evo, xp, or whatever the flavor of the day is. All I want is something that works for my team regardless of whether I follow all the rules or not. I think it revolves anourd a few ideas though:1) Work in iterations2) Customer feedback at each iteration3) Test driven development (Unit and integration tests)4) Continuous integrationThat would be a pretty good start for most teams. Each of those seem pretty simple, but I'd be hard pressed to find evidence of any of these at most shops I've been at.[]

Kawd

A little silipistmc Cedric but some interesting concepts.the first problem is that@Author(date = February 26th, 2005 )will generate a compiler error because the element lastName is not specified and it does not have a default clause in the definition of @Author, so you can't actually omit it.If you solve that problem by specifying defaults in the declaration of Author, then you might still be stuck because you might not be able to determine whether an element (like lastName in your last example) was ommitted, or was actually explicitly set to its default value. It all depends on the API you are using. With com.sun.mirror and com.sun.javadoc you can make the distinction, with java.lang.reflect you cannot.To solve that you could look up the default value, and if the annotation's value was the default you could ASSUME it was unspecified (and therefore should inherit the value declared in super), but that assumption might be wrong.You can make the assumption less likely to be wrong by making the default value something ridiculously meaningless, or something that is actually semantically invalid (to your application not to the compiler). All you have to do in the processing is to convert the declared default value, to the semantic default value when processing, (or cry foul if a value must be specified somewhere, that is if at the application level there is no default, even though at the implementation level there is).You could possibly write a general purpose method to do partial inheritance processing. Element declarations in an annotation type can themselves be annotated, so you could tell the processing algorithm what the application level default value was with an annotation./**An annotation for annotation type members, specifying how the Partial Inheritance processor should process annotations of the target's enclosing annotation type.*/@Target(METHOD)@interface PartialInheritance {/**set to true if the processor needs to generate an error if no value for the target is specified in any of the declared or inherited annotations.*/boolean noRealDefault() default false;/**The target element's declared default value is used to detect whether the element value is being over-ridden or not and should not be a meaningful value. If a value is not specified in any of the declared or inherited annotations, then the value of this element, not the target's default will be taken as the value by the Partial Inheritance mechanism.*/String realDefaultString() default ;}@interface Author {/**The last name, if not specified, the value is inherited from superclass, if no inherited value is available either, the lastName is considered to be */@PartialInheritance(realDefaultString= ")public String lastName() default ~@~ ;/**The date. if not specified, the value must be inherited from a superclass's @Author.*/@PartialInheritance(noRealDefault=true)public String date() default ~@~ ;}

Stephanie

I'm not sure I agree with mac. Metadata may be a non object ornetied concept, but in Java annotations are attached to object ornetied constructs. They belong to the class (or feature) they are defined in. Fields and methods also belong to the class they are defined in and they can be inherited. Why shouldn't annotations be inherited according to the same rules that are already well understood by Java developers? That is one of the first things that occured to me when I was first learning about Java annotations, so I can attach one of these to one of my Classes and read it back at runtime, cool but it won't get inherited, hmmm.. And it doesn't seem that confusing to me as far as using annotations that can be inherited. The only confusing part that I can see would be writing tool or framework that has to correctly infer inheritance where none really' exists. I would have rather seen it as part of the official release because I'm not sure that widespread use of both inheritable and standard annotations would be a good thing. For instance what if a framework I use enables inheriting annotations that it processes. If I add my own annotations that the framwork knows nothing about then I have classes with both types in it. That sounds like trouble to me.But I don't buy the it's not OO, leave it alone argument: a big part of OO is rolling different language features into a Class and handling them in a consistent way. And as far as `Applying Inheritance or Partial Inheritance mecanism` : thats how everything else is done in Java so why not just phrase it `Applying the standard Java inheritance mecanism`

James

Actually Annotations do support Inheritance of a kind.That kind thuogh is that an annotation can be declared (using the meta-annotation @Inherited) to be inherited from classes to subclasses ONLY. Unfortunately (IMHO) many of the useful applications of inheritance would be inheriting from interfaces and JSR-175 s inheritance mechanism does not allow this.Also the inheritance is a full inheritance, not the partial inheritance that Cedric discusses, and this, combined with the fact that we cannot extend an annotation type (therefore making our own similar annotation, being a kind of the other) and define different default values, makes annotations considerably less useful than they might otherwise be.Given these limitations in JSR-175 The concept of partial inheritance has proven useful to Cedric, and I can understand why. Since my comment yesterday I have written a meta-annotation for member elements, and a java.lang.reflect processing engine that can (for the examples above) return an Author object that exhibits the sort of partial inheritance Cedric discussed. This engine is general purpose and not restricted to one particular annotation type.

The comments to this entry are closed.

Subscribe to Thinking

Contact ICF Interactive

  • ICF Interactive a full-service, interactive agency with the ability to guide brands digitally – through an informed strategy, inspired design, technical know-how and an obsession for humanity, we not only can launch your site but we can digitally catapult your brand. If you have a project in mind, would like information regarding our work, career opportunities, proposal requests or anything else, please feel free to get in touch. We’re ready for what’s next. hello@icfi.com