2015-01-15 3 views
0

У меня есть много файлов XML в Workbench Project Explorer, каждый из которых является экземпляром одной из десяти различных моделей ecore. Для каждой модели ecore я хотел бы внести commonFilter в точку расширения навигатора navigatorContent, чтобы позволить пользователю показывать или скрыть соответствующие файлы XML. Это внешние файлы инструментов, поэтому нет возможности идентифицировать контент, просто наблюдая за именем файла или расширением xml, а переименование не представляется возможным. Используя, возможно, класс, основанный на org.eclipse.jface.viewers.ViewerFilter, каков наилучший способ определить, какая из моделей ecore содержится в файле XML? Я предполагаю, что есть простой способ сделать это с помощью ресурсов EMF или с помощью EcoreUtil или с адаптерами, но я не нашел успешной техники. Альтернативно, способ сделать это непосредственно из точки добавочного номера filterExpression или viewerContentBinding зрителя будет прекрасным. Все плагины genmodel доступны для различных моделей ecore.Eclipse Project Explorer фильтр для файлов XML

package com.my.navigator; 
import org.eclipse.core.resources.IFile; 
import org.eclipse.jface.viewers.Viewer; 
import org.eclipse.jface.viewers.ViewerFilter; 


public class MyViewerFilter extends ViewerFilter { 

public MyViewerFilter() { 
} 

@Override 
public boolean select(Viewer viewer, Object parentElement, Object element) { 
     if (element instanceof IFile) { 
      IFile file = (IFile)element; 
      // check whether file is one of our ecore models... 
      // ... 
     } 

     return true; 
    } 

} 

ответ

0

Вы можете использовать org.eclipse.core.contenttype.contentTypes для определения новых типов контента для вашего файла.

Используйте аргумент describer определения типа содержимого, чтобы указать класс «описатель содержимого», который может проверить соответствие файла XML вашим требованиям. Уже существует класс XMLContentDescriber, который вы можете использовать в качестве основы для описания.

Например, это определение типа содержимого для Ant build.xml файлов:

<extension 
    point="org.eclipse.core.contenttype.contentTypes"> 
    <content-type 
     id="antBuildFile" 
     name="%antBuildFileContentType.name" 
     base-type="org.eclipse.core.runtime.xml" 
     file-names="build.xml" 
     file-extensions="macrodef,ent,xml,ant" 
     priority="normal"> 
     <describer 
      class="org.eclipse.ant.internal.core.contentDescriber.AntBuildfileContentDescriber"> 
     </describer> 
    </content-type> 
</extension> 

и это Ant содержание описатель, чтобы дать вам общее представление о том, что вы можете:

public final class AntBuildfileContentDescriber extends XMLContentDescriber implements IExecutableExtension { 

    private int checkCriteria(InputSource contents) throws IOException { 
     AntHandler antHandler = new AntHandler(); 
     try { 
      if (!antHandler.parseContents(contents)) { 
       return INDETERMINATE; 
      } 
     } 
     catch (SAXException e) { 
      // we may be handed any kind of contents... it is normal we fail to parse 
      return INDETERMINATE; 
     } 
     catch (ParserConfigurationException e) { 
      // some bad thing happened - force this describer to be disabled 
      String message = "Internal Error: XML parser configuration error during content description for Ant buildfiles"; //$NON-NLS-1$ 
      throw new RuntimeException(message); 
     } 
     // Check to see if we matched our criteria. 
     if (antHandler.hasRootProjectElement()) { 
      if (antHandler.hasProjectDefaultAttribute() || antHandler.hasTargetElement() || antHandler.hasAntElement()) { 
       // project and default attribute or project and target element(s) 
       // or project and top level ant element(s) (classpath, import, macrodef, path, property, taskdef, typedef) 
       return VALID; 
      } 
      // only a top level project element...maybe an Ant buildfile 
      return INDETERMINATE; 
     } 

     return INDETERMINATE; 
    } 

    @Override 
    public int describe(InputStream contents, IContentDescription description) throws IOException { 
     // call the basic XML describer to do basic recognition 
     if (super.describe(contents, description) == INVALID) { 
      return INVALID; 
     } 
     // super.describe will have consumed some chars, need to rewind 
     contents.reset(); 
     // Check to see if we matched our criteria. 
     return checkCriteria(new InputSource(contents)); 
    } 

    @Override 
    public int describe(Reader contents, IContentDescription description) throws IOException { 
     // call the basic XML describer to do basic recognition 
     if (super.describe(contents, description) == INVALID) { 
      return INVALID; 
     } 
     // super.describe will have consumed some chars, need to rewind 
     contents.reset(); 
     // Check to see if we matched our criteria. 
     return checkCriteria(new InputSource(contents)); 
    } 

    @Override 
    public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { 
     // do nothing 
    } 
} 
Смежные вопросы