The way I understand how eclipse validation framework works:
- generate an object with a factory
- set a value for an attribute in this object
- check validation
For example:
public class ValidateNameTest {
public static void main(String[] args) {
ExtlibraryPackageImpl.init();
ExtlibraryFactory factory = ExtlibraryFactory.eINSTANCE;
Writer writer = factory.createWriter();
// comment next line for false result in console
writer.setName("test");
writer.setFirstName("test");
writer.setLastName("test");
boolean isNull = (writer.getName() == null) ? true : false;
System.out.println("writer name is null : " + isNull);
boolean result = validateObject(writer);
System.err.println("result = " + result);
boolean result2 = validateObject2(writer);
System.err.println("result2 = " + result2);
boolean result3 = validateObject3(writer);
System.err.println("result3 = " + result3);
boolean result4 = validateObject5(writer);
System.out.println("result4 = " + result4);
}
public static boolean validateObject(Writer writer) {
ExtlibraryValidator validator = ExtlibraryValidator.INSTANCE;
if (!validator.validateWriter_hasValidName(writer, null, null)) {
return false;
}
return true;
}
public static boolean validateObject2(EObject eObject) {
EValidator validator = EValidator.Registry.INSTANCE
.getEValidator(eObject.eClass().getEPackage());
if (validator != null) {
if (!validator.validate(eObject, null, null)) {
return false;
}
}
return true;
}
public static boolean validateObject3(EObject eObject) {
Diagnostic diagnostic = Diagnostician.INSTANCE.validate(eObject);
return diagnostic.getSeverity() == Diagnostic.OK;
}
public static boolean validateObject5(EObject eObject)
{
Diagnostic diagnostic = Diagnostician.INSTANCE.validate(eObject);
if (diagnostic.getSeverity() == Diagnostic.ERROR || diagnostic.getSeverity() == Diagnostic.WARNING)
{
System.err.println(diagnostic.getMessage());
for (Diagnostic childDiagnostic : diagnostic.getChildren())
{
switch (childDiagnostic.getSeverity())
{
case Diagnostic.ERROR:
case Diagnostic.WARNING:
System.err.println("\t" + childDiagnostic.getMessage());
}
}
return false;
}
return true;
}
}
But I want to check if a value is valid for the model before I call the setter for the attribute. Is this possible with Eclipse EMF validation framework? Can somebody give an example please?
I know of one common use case where this is possible: Data binding between model and UI controls.
When you establish the EMF data binding between your model and the user interface, you can validate user input as follows. Create an update strategy (target to model) and override the method validateBeforeSet(Object). Here is an example: