1、在之前library的model、edit、editor基础上,增加一个Validator插件。
2、增加如下扩展点。
3、增加以下类。
ValidationDelegateClientSelector
LiveValidationContentAdapter
UniqueBookNameConstriant
4、在editor插件的LibraryEditor类中注册LiveValidationContentAdapter。
修改createModel方法
5、跑起应用,对Library模型进行修改时,如果book重名,则会在Problems视图提示错误。
[img]http://dl.iteye.com/upload/attachment/564824/dd75b996-5cf2-3d90-9ab8-5451778eb8e5.jpg[/img]
2、增加如下扩展点。
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
<extension
point="org.eclipse.emf.validation.constraintProviders">
<category
id="library.constriants"
mandatory="false"
name="Library Constriants">
</category>
<constraintProvider
cache="true">
<package
namespaceUri="http://www.eclipse.library">
</package>
<constraints
categories="library.constriants">
<constraint
class="constriants.UniqueBookNameConstriant"
id="UniqueBookNameConstriant"
lang="java"
mode="Live"
name="UniqueBookNameConstriant"
severity="ERROR"
statusCode="1">
<message>
Book must have the unique name.
</message>
<target
class="Book">
<event
name="Set">
<feature
name="name">
</feature>
</event>
<event
name="Unset">
<feature
name="name">
</feature>
</event>
</target>
</constraint>
</constraints>
</constraintProvider>
</extension>
<extension
point="org.eclipse.emf.validation.constraintBindings">
<clientContext
id="library.validator.clientContext">
<selector
class="library.validator.ValidationDelegateClientSelector">
</selector>
</clientContext>
<binding
category="library.constriants"
constraint="UniqueBookNameConstriant"
context="library.validator.clientContext">
</binding>
</extension>
<extension
id="libraryMarker"
point="org.eclipse.core.resources.markers">
<super
type="org.eclipse.core.resources.problemmarker">
</super>
<persistent
value="true">
</persistent>
<attribute
name="targetClassName">
</attribute>
<attribute
name="targetContainer">
</attribute>
</extension>
</plugin>
3、增加以下类。
ValidationDelegateClientSelector
package library.validator;
import org.eclipse.emf.validation.model.IClientSelector;
public class ValidationDelegateClientSelector implements IClientSelector {
public static boolean running = false;
@Override
public boolean selects(Object object) {
return running;
}
}
LiveValidationContentAdapter
package library.validator;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EValidator;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.emf.ecore.util.EObjectValidator;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.ui.action.ValidateAction;
import org.eclipse.emf.validation.model.EvaluationMode;
import org.eclipse.emf.validation.model.IConstraintStatus;
import org.eclipse.emf.validation.service.ILiveValidator;
import org.eclipse.emf.validation.service.ModelValidationService;
public class LiveValidationContentAdapter extends EContentAdapter {
private ILiveValidator validator = null;
public LiveValidationContentAdapter() {
}
public void notifyChanged(final Notification notification) {
super.notifyChanged(notification);
if (validator == null) {
validator = (ILiveValidator) ModelValidationService.getInstance()
.newValidator(EvaluationMode.LIVE);
validator.setReportSuccesses(true);
}
ValidationDelegateClientSelector.running = true;
IStatus status = validator.validate(notification);
final IConstraintStatus constraintStatus = status instanceof IConstraintStatus ? (IConstraintStatus) status
: null;
if (constraintStatus != null) {
processStatus(constraintStatus);
}
ValidationDelegateClientSelector.running = false;
}
private void processStatus(final IConstraintStatus constraintStatus) {
final BasicDiagnostic diagnostic = new BasicDiagnostic(
EObjectValidator.DIAGNOSTIC_SOURCE, 0, "", constraintStatus
.getTarget().eResource().getContents().toArray());
if (!constraintStatus.isOK()) {
appendDiagnostics(constraintStatus, diagnostic);
}
WorkspaceJob workspaceJob = new WorkspaceJob("markerUitl") {
@Override
public IStatus runInWorkspace(IProgressMonitor monitor)
throws CoreException {
ValidateAction.EclipseResourcesUtil eclipseResourcesUtil = new ValidateAction.EclipseResourcesUtil();
deleteResourceMarker(constraintStatus);
for (Diagnostic childDiagnostic : diagnostic.getChildren()) {
eclipseResourcesUtil.createMarkers(constraintStatus
.getTarget().eResource(), childDiagnostic);
}
return Status.OK_STATUS;
}
};
workspaceJob.schedule();
}
private void appendDiagnostics(IStatus status, DiagnosticChain diagnostics) {
if (status.isMultiStatus()) {
IStatus[] children = status.getChildren();
for (int i = 0; i < children.length; i++) {
appendDiagnostics(children[i], diagnostics);
}
} else if (status instanceof IConstraintStatus) {
diagnostics.add(new BasicDiagnostic(status.getSeverity(), status
.getPlugin(), status.getCode(), status.getMessage(),
((IConstraintStatus) status).getResultLocus().toArray()));
}
}
private void deleteResourceMarker(IConstraintStatus status) {
Resource resource = status.getTarget().eResource();
if (resource == null) {
return;
}
URI uri = resource.getURI();
StringBuffer platformResourcePath = new StringBuffer();
for (int j = 1, size = uri.segmentCount(); j < size; ++j) {
platformResourcePath.append('/');
platformResourcePath.append(URI.decode(uri.segment(j)));
}
IFile file = ResourcesPlugin.getWorkspace().getRoot()
.getFile(new Path(platformResourcePath.toString()));
try {
IMarker[] markers = file.findMarkers(EValidator.MARKER, false,
IResource.DEPTH_INFINITE);
for (IMarker m : markers) {
if (m.exists()
&& m.getAttribute(EValidator.URI_ATTRIBUTE, "")
.equals(EcoreUtil.getURI(status.getTarget())
.toString())) {
m.delete();
}
}
} catch (CoreException e1) {
e1.printStackTrace();
}
}
}
UniqueBookNameConstriant
package constriants;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.validation.AbstractModelConstraint;
import org.eclipse.emf.validation.IValidationContext;
import org.eclipse.library.Book;
public class UniqueBookNameConstriant extends AbstractModelConstraint {
@Override
public IStatus validate(IValidationContext ctx) {
System.out.println(ctx.getEventType());
EObject target = ctx.getTarget();
String targetName = ((Book) target).getName();
if (targetName == null || targetName.isEmpty()) {
return ctx.createSuccessStatus();
}
TreeIterator<EObject> ite = target.eResource().getAllContents();
while (ite.hasNext()) {
EObject obj = ite.next();
if (obj instanceof Book) {
Book book = (Book) obj;
if (book == null || book == target) {
continue;
}
if (targetName.equals(book.getName())) {
return ctx.createFailureStatus();
}
}
}
return ctx.createSuccessStatus();
}
}
4、在editor插件的LibraryEditor类中注册LiveValidationContentAdapter。
修改createModel方法
/**
* This is the method called to load a resource into the editing domain's resource set based on the editor's input.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createModel() {
URI resourceURI = EditUIUtil.getURI(getEditorInput());
Exception exception = null;
Resource resource = null;
try {
// Load the resource through the editing domain.
//
resource = editingDomain.getResourceSet().getResource(resourceURI, true);
}
catch (Exception e) {
exception = e;
resource = editingDomain.getResourceSet().getResource(resourceURI, false);
}
Diagnostic diagnostic = analyzeResourceProblems(resource, exception);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter);
// XXX
if (!resourceHasLiveAdapter(resource)) {
EContentAdapter liveValidationContentAdapter = new LiveValidationContentAdapter();
resource.eAdapters().add(liveValidationContentAdapter);
}
}
private boolean resourceHasLiveAdapter(Resource r) {
for (Adapter next : r.eAdapters()) {
if (next instanceof LiveValidationContentAdapter) {
return true;
}
}
return false;
}
5、跑起应用,对Library模型进行修改时,如果book重名,则会在Problems视图提示错误。
[img]http://dl.iteye.com/upload/attachment/564824/dd75b996-5cf2-3d90-9ab8-5451778eb8e5.jpg[/img]