`
cutesunshineriver
  • 浏览: 200672 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

EMF校验--Live模式

EMF 
阅读更多
1、在之前library的model、edit、editor基础上,增加一个Validator插件。

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视图提示错误。
  • 大小: 53.3 KB
分享到:
评论

相关推荐

    emf-xsd-SDK-2.6.1

    在"emf-xsd-SDK-2.6.1"的压缩包中,包含了Eclipse环境的相关文件,这通常意味着我们可以在这个环境中开发和测试基于EMF和XSD的模型应用。Eclipse是一个集成开发环境(IDE),支持多种编程语言和插件,EMF相关的插件...

    emf-sdo-xsd-SDK-2.3.2.zip

    《Eclipse插件开发与应用:深入理解emf-sdo-xsd-SDK-2.3.2》 在软件开发领域,Eclipse作为一款强大的开源集成开发环境(IDE),因其高度可扩展性和丰富的插件生态而深受开发者喜爱。Eclipse插件是其核心功能之一,...

    emf-sdo-SDK-2.2.2

    `emf-sdo-SDK-2.2.2`是EMF对SDO标准的实现,是一个针对Eclipse环境的插件。 在Eclipse中,`emf-sdo-SDK-2.2.2`主要包含以下几个方面的知识点: 1. **元模型(Metamodel)**:元模型是描述数据结构的模型,它定义了...

    emf-sdo-xsd-SDK-2.0.1.zip

    在EMF-SDO-XSD SDK中,"eclipse"可能指的是Eclipse集成开发环境(Integrated Development Environment),这是一个广泛使用的Java开发工具,也支持多种其他语言和框架,包括Struts。开发者可以使用Eclipse来导入和...

    emf-xsd-Update-2.7.2

    【标题】"emf-xsd-Update-2.7.2" 涉及到的是一个针对Eclipse集成开发环境的扩展,主要关注的是EMF(Eclipse Modeling Framework)和XSD(XML Schema Definition)的更新版本2.7.2。这个更新包包含了对EMF框架的增强...

    emf-xsd-Update-2.10.2

    【标题】"emf-xsd-Update-2.10.2" 是一个与Java可视化开发相关的软件更新版本,主要用于支持Visual Editor的安装和使用。这个版本是2.10.2,通常代表着修复了一些已知问题,增加了新功能,或者优化了性能。 【描述...

    emf-sdo-SDK-2.2.0(2) eclipse 可视化 界面设计

    emf-sdo-SDK-2.2.0(2) eclipse 可视化 界面设计。 因为size太大,所以分成了2部分,另一部分在 emf-sdo-SDK-2.2.0(1)里面。 emf-sdo-SDK-2.2.0(1)的下载地址: http://download.csdn.net/source/1002774

    emf-sdo-xsd-SDK-2.4.0.zip

    emf-sdo-xsd-SDK-2.4.0.zip emf是Eclipse modeling framework组建框架的缩写;SDO是服务数据对象的缩写,它是Java程序的一种数据编程框架;emf-sdo-xsd-SDK-2.4.0.zip是Eclipse编程器的组成员之一。

    emf-sdo-runtime-2.2.0.zip

    "emf-sdo-runtime-2.2.0.zip" 是一个包含EMF SDO运行时库的压缩包,用于在Eclipse环境中集成SDO功能。这个版本号2.2.0表明这是一个特定的稳定版本,包含了该版本中所有修复的bug和新增的功能。 在压缩包内的...

    emf-runtime-2.6.1.7z

    Eclipse 3.6.1(Helios)的插件。emf-runtime-2.6.1.7z。

    emf-sdo-runtime-2.2.0.zip、GEF-runtime-3.2.zip和VE-runtime-1.2.3_jem.zip

    myeclipse ,swing ,chajian,解压,添加

    emf-runtime-2.6.1

    标题中的"emf-runtime-2.6.1"指的是EMF框架的运行时组件,版本号为2.6.1。 EMF的核心功能包括: 1. **模型定义**:通过扩展XML Schema Definition (XSD) 或者ECORE(EMF的元数据模型)来定义模型结构。ECORE是一种...

    emf-runtime-2.5.0.zip

    "emf-runtime-2.5.0.zip" 是一个包含EMF运行时库的压缩文件,版本为2.5.0。这个版本可能包含了对模型对象的创建、序列化、反序列化以及与模型相关的事件处理等功能。它对于那些希望在Eclipse环境下开发图形化编辑器...

    emf-sdo-xsd-SDK-2.2.1

    标题中的"emf-sdo-xsd-SDK-2.2.1"指的是Eclipse Modeling Framework (EMF) Service Data Objects (SDO) XSD SDK的一个特定版本,即2.2.1。EMF是Eclipse基金会开发的一个强大的建模框架,它允许开发者创建、操作和...

    emf-sdo-runtime-2.2.0 (emf build 2.2.0)

    eclipse可视化插件安装必备插件之一:emf-sdo-runtime-2.2.0。eclipse全部可视化插件正确配置是eclipse-SDK-3.2-win32,emf-sdo-runtime-2.2.0,GEF-runtime-3.2,VE-runtime-1.2,VE-SDK-1.2

    LAS2emf tool--convert LAS format log curves into EMF

    LAS2emf convert LAS--standard industrial Logging curve data into EMF format Graphics.

    emf-sdo-runtime

    `emf-sdo-runtime`是EMF针对SDO标准实现的运行时库,它是Eclipse IDE中的一个插件,用于支持在Eclipse环境中开发和使用SDO的应用。 EMF-SDO-Runtime的核心功能包括: 1. **数据对象模型**:它允许开发者定义复杂的...

    emf-xsd-Update-2.7.1

    【标题】"emf-xsd-Update-2.7.1" 涉及的是EMF(Eclipse Modeling Framework)的版本更新至2.7.1。EMF是Eclipse项目的一部分,它提供了一个用于构建基于模型的应用程序的框架和工具。在这一版本的更新中,开发者可能...

Global site tag (gtag.js) - Google Analytics