Hi!
What I miss in Castor is validation when setting a value using the
setters "setXX(value)" in a class generated from a XML Schema. Since the
schema includes "all" verification needed to validate a
Element/Attribute, why not use that validation fully when working with
the values in java.
It seams to me that in Castor validation only occurs when
marshaling/unmarshaling, or when calling the isValid() method in the
generated class. The isValid() is expensive, in creating objects and
going through all fields. What I wanted is when trying to set a value
through one of the setXX(), the generated class would throw an exception
if the value was invalid according to the class field descriptor.
So this is what I have done:
I have created a class called "myFieldValidator" (FieldValidator is
already taken). It is a heavy modified version of "Validator". The
myFieldValidator method validate() is called whenever a value is set
using the generated classes setXX(). If the validating (according to the
descriptor) fails a ValidationException is thrown.
The classes generated from the XML schema has been modified:
A "throws ValidationException" is added to all setters and a method call
"fieldValidate("_id", id)" that perform the validation on the value
added.
public void setCity(java.lang.String city) throws
ValidationException {
fieldValidate("_city", city);
this._city = city;
}
The method fieldValidate() is added to the bottom of this file.The
fieldValidate() method is just a helper method that calls the
myFieldValidator to perform the validation.
Validation is also performed when adding a custom object, like a "Item"
object, through a setter. So when the setItem() method is called a
Item.isValid() is called to validate the Item before adding it. (The
isValid() is a part of the source created by the SourceGenerator.)
A small modification of FieldValidator.java was needed to get the
TypeValidator for a specific field. So this was added to the
FieldValidator.java:
public TypeValidator getValidator() {
return _validator;
}
This is a suggestion to how instant field validation can be done. If you
are interested in taking a look at the code, you can get it here:
http://www.npstrandberg.com/validate.jar. To run this example you need
the source code for Castor. Then you must add the above code to the
FieldValidator.java, so that it will return the TypeValidator. Compile
Castor and then run this example.
Niels Peter Strandberg
-----------------------------------------------------------
If you wish to unsubscribe from this mailing, send mail to
[EMAIL PROTECTED] with a subject of:
unsubscribe castor-dev