应的通知从而触发验证。通知消息包括了诸如发生 改变的属性及该属性变化前后的值等信息。在扩展点定义中去声明那些需要在取值发生变化 时进行实时验证的属性。
清单 7 是对之前定义的 bacth constraint 定义的修改,当事件类型不为空是,也就是 说验证服务收到了模型属性变更的通知事件,此时触发验证检查新的属性值是否为空。
清单 7. 之前定义的 bacth constraint 定义的修改
public class NonEmptyNamesConstraint extends AbstractModelConstraint {
public IStatus validate(IValidationContext ctx) {
EObject eObj = ctx.getTarget();
EMFEventType eType = ctx.getEventType();
// bacth validation 时调用
if (eType == EMFEventType.NULL) {
String name = null;
if (eObj instanceof Writer) {
name = ((Writer)eObj).getName();
} else if (eObj instanceof Library) {
name = ((Library)eObj).getName();
} else if (eObj instanceof Book) {
name = ((Book)eObj).getTitle();
}
if (name == null || name.length() == 0) {
return ctx.createFailureStatus(new Object[] {eObj.eClass().getName ()});
}
// live validation 时调用
} else {
Object newValue = ctx.getFeatureNewValue();
if (newValue == null || ((String)newValue).length() == 0) {
return ctx.createFailureStatus(new Object[] {eObj.eClass().getName ()});
}
}
return ctx.createSuccessStatus();
}
}
使用EMF Validation框架来验证EMF模型(10)
时间:2011-04-23 IBM 仇璐 杨晓峰
下面清单 8 的代码是对 constraintProviders 扩展点的修改,可以看到首先验证模式由 batch 变成了 live,此外我们定义了感兴趣的验证目标 EClass, 目标属性 EStructuralFeature 和触发事件类型。
清单 8. constraintProviders 扩展点的修改
<extension
point="org.eclipse.emf.validation.constraintProviders">
<category
name="Library Constraints"
id=" org.eclipse.emf.validation.example.library "/>
<constraintProvider cache="true">
<package namespaceUri="platform:/resource/test.emf.validation/model/Library.ecore"/>
<constraints categories=" emf.validation.example.library ">
<constraint
lang="Java"
class=" emf.model.library.validation.constraints.NonEmptyNamesConstraint "
severity="ERROR"
mode="Live"
name="Non-Empty Names"
id=" emf.validation.example.library.NameNotEmpty "
statusCode="1">
<description>
All items in a library model should have some unique identifier or name.
</description>
<message>
A {0} has been found to have no unique identifier (name or title).
</message>
|