Org.eclipse.core.resources.natures org.eclipse.core.resources.builders Extension Point Introduction

Source: Internet
Author: User

Builder and Nature are the two extensibility points available in eclipse. In general, we have our own specific project types, and then add custom builder and nature to this type of project.

In fact, the so-called specific project is usually identified by the unique nature, and the General Builder is built on a specific type of project, so we can conclude: nature determines project and builder.

1. Create Nature Extension points

   <extension         id= "nature"         name= "WorkFlow Project nature"         point= "Org.eclipse.core.resources.natures" >      <runtime>         <run               class= "Com.workflow.nature.WorkflowProjectNature" >         </run >      </runtime>      <builder            id= "Mydesigner.builder" ><!-- Builder's extension point ID plugin ID plus builder extended id-->      </builder>   </extension>
2. Create builder Extension points

<extension         id= "builder"         name= "WorkFlow Project Builder"         point= " Org.eclipse.core.resources.builders ">      <builder            hasnature=" true "            isconfigurable=" false ">         <run               class= "Com.workflow.builder.ProjectBuilder" >         </run>      </builder>   </extension>
3, nature of the implementation of the class

Import Org.eclipse.core.resources.iproject;import Org.eclipse.core.resources.iprojectdescription;import Org.eclipse.core.resources.iprojectnature;import Org.eclipse.core.runtime.coreexception;import Com.workflow.builder.projectbuilder;import com.workflow.tool.projectutil;/** * Custom Nature Implementation class * @author LWW * */public Class Workflowprojectnature implements Iprojectnature {private IProject project;public static final String ID = "Mydesigne R.nature ";//nature ID for plugin ID plus nature extension id/** * Builder installation */@Overridepublic void Configure () throws Coreexception {      Iprojectdescription description = Project.getdescription ();      Projectutil.addbuildertoproject (description, new string[] {projectbuilder.id}, NULL);  Project.setdescription (description, NULL); }/** * Builder Uninstall */@Overridepublic void Deconfigure () throws Coreexception {iprojectdescription Description = Project.get      Description (); Projectutil.removebuilderfromproject (description, new string[] {ProjectbuiLder.id}, NULL); Project.setdescription (description, NULL); } @Overridepublic IProject Getproject () {return project;} Called @Overridepublic void Setproject (IProject project) {//at project.setdescription (), If the project description the Naturethis.project = Project;}}
4, the implementation of the builder class

Import Java.util.map;import Javax.xml.parsers.parserconfigurationexception;import javax.xml.parsers.SAXParser; Import Javax.xml.parsers.saxparserfactory;import Org.eclipse.core.resources.ifile;import Org.eclipse.core.resources.ifolder;import Org.eclipse.core.resources.imarker;import Org.eclipse.core.resources.iproject;import Org.eclipse.core.resources.iresource;import Org.eclipse.core.resources.iresourcedelta;import Org.eclipse.core.resources.iresourcedeltavisitor;import Org.eclipse.core.resources.iresourcevisitor;import Org.eclipse.core.resources.incrementalprojectbuilder;import Org.eclipse.core.runtime.coreexception;import Org.eclipse.core.runtime.iprogressmonitor;import Org.xml.sax.saxexception;import Org.xml.sax.saxparseexception;import org.xml.sax.helpers.defaulthandler;/** * Custom The builder implementation class *org.eclipse.core.resources.builders is used to provide an operation that will automatically build when Iresource changes, like changing a Java file, and automatically build, * As shown in error, we extend this builder and use it in our own projects. All we have to do is implement the build process, * as the time is controlled by eclipse * @author LWW * */public CLass Projectbuilder extends Incrementalprojectbuilder {private IProject project;public static final String ID = "Mydesigne R.builder ";//builder with ID plugin ID plus builder extended id.private static final String Marker_type =" Mydesigner.xmlproblem "; Private SAXParserFactory parserfactory;/** * Different build strategies are implemented depending on the build type */@Overrideprotected iproject[] Build (int kind , map<string, string> args,iprogressmonitor monitor) throws coreexception {switch (kind) {case full_build: FullBuild (monitor); Break;default:iresourcedelta delta = Getdelta (project); if (delta = = null) {fullbuild (monitor);} else {incrementalbuild (delta, monitor);} break;} return null;} /** * Execute this method when you click Clean Action in the Project menu bar */@Overrideprotected void clean (Iprogressmonitor monitor) throws Coreexception { Super.clean (monitor);/* Remove all build files */ifolder outputfiles = Project.getfolder ("Processes"); o Utputfiles.refreshlocal (Iresource.depth_infinite, monitor), if (Outputfiles.exists ()) {Outputfiles.delete (True, monitor);}} /** * Call someInitial information, or initial variable */@Overrideprotected void Startuponinitialize () {super.startuponinitialize (); this.project = Getproject () ;} /** * Add identity, display the error in markers View * @param file * @param message * @param linenumber * @param severity */private void Addmarker (Final IFile file, String message, int linenumber,int severity) {try {imarker marker = File.createmarker (Marker_type); Marker.setattribute (imarker.priority, Imarker.priority_high); Marker.setattribute (Imarker.message, MESSAGE); Marker.setattribute (imarker.severity, SEVERITY); if (linenumber = =-1) {linenumber = 1;} Marker.setattribute (Imarker.line_number, linenumber);} catch (Coreexception e) {}}/** * check file suffix. xml * @param resource */void Checkxml (Iresource Resource) {if (Resource Instanceo F IFile && Resource.getname (). EndsWith (". xml")) {IFile file = (IFile) resource;deletemarkers (file); Xmlerrorhandler reporter = New xmlerrorhandler (file), try {getparser (). Parse (File.getcontents (), reporter);} catch ( Exception E1) {}}}/** * Delete markers * @param file */private void Deletemarkers (IFile file) {try {file.deletemarkers (Marker_type, False, Iresource.depth_zero);} catch ( Coreexception CE) {}}private saxparser getparser () throws Parserconfigurationexception,saxexception {if (parserFactory = = null) {parserfactory = Saxparserfactory.newinstance ();} return Parserfactory.newsaxparser ();} protected void FullBuild (final iprogressmonitor monitor) throws Coreexception {try {getproject (). Accept (New Workflowresourcevisitor ());} catch (Coreexception e) {}}protected void IncrementalBuild (Iresourcedelta delta,iprogressmonitor monitor) throws coreexception {//The visitor does the work.delta.accept (new Workflowdeltavisitor ());} Class Workflowdeltavisitor implements Iresourcedeltavisitor {@Overridepublic Boolean visit (Iresourcedelta Delta) Throws Coreexception {Iresource resource = Delta.getresource (); switch (Delta.getkind ()) {case iresourcedelta.added:// Handle added Resourcecheckxml (Resource); break;case iresourcedelta.removed://handle removed ResourcebreaK;case iresourcedelta.changed://handle CHANGED resourcecheckxml (resource); break;} Return true to continue visiting Children.return true;}} Class Workflowresourcevisitor implements Iresourcevisitor {@Overridepublic Boolean visit (Iresource Resource) throws coreexception {checkxml (Resource); return true;}} Class Xmlerrorhandler extends DefaultHandler {private IFile file;public xmlerrorhandler (IFile file) {this.file = file;} private void Addmarker (saxparseexception e, int severity) {ProjectBuilder.this.addMarker (file, E.getmessage (), E.getlinenumber (), severity);} public void error (Saxparseexception exception) throws Saxexception {Addmarker (exception, imarker.severity_error);} public void FatalError (Saxparseexception exception) throws Saxexception {Addmarker (exception, Imarker.severity_error) ;} public void Warning (Saxparseexception exception) throws Saxexception {Addmarker (exception, imarker.severity_warning);}}}

5. Operation class

Import Java.util.arraylist;import Java.util.list;import Org.eclipse.core.resources.icommand;import Org.eclipse.core.resources.iprojectdescription;import Org.eclipse.core.runtime.coreexception;import org.eclipse.core.runtime.iprogressmonitor;/** * Project Action Class (add nature, builder) * @author LWW * */public class Projectutil {/** * Add nature information to Project * Add comment information */public static void Addnature2project (iprojectdescription      Description, string[] natureids) throws coreexception {string[] prevnatures = Description.getnatureids ();      string[] Newnatures = new String[prevnatures.length + natureids.length];      System.arraycopy (prevnatures, 0, newnatures, 0, prevnatures.length);      for (int i = prevnatures.length;i<newnatures.length;i++) {Newnatures[i] = Natureids[i-prevnatures.length];          } description.setnatureids (Newnatures);    Description.setcomment ("It ' s a WorkFlow project"); }/** * Add Builder to Project * @param description * @param builderids * @param moNitor * @throws coreexception */public static void Addbuildertoproject (iprojectdescription description, string[]      Builderids, Iprogressmonitor Monitor) throws Coreexception {icommand[] Buildspec = Description.getbuildspec ();      icommand[] Newbuilders = new Icommand[buildspec.length + builderids.length];      System.arraycopy (buildspec, 0, newbuilders, 0, buildspec.length);          for (int i = buildspec.length; i < newbuilders.length; i++) {ICommand command = Description.newcommand ();          Command.setbuildername (Builderids[i-buildspec.length]);      Newbuilders[i] = command;  } description.setbuildspec (Newbuilders); }/** * Remove builder from Project * @param description * @param builderids * @param monitor */public static void Removebuilderfr Omproject (iprojectdescription description, string[] builderids, Iprogressmonitor monitor) {Icomma      nd[] Buildspec = Description.getbuildspec (); List<icommand> NEWbuilders = new arraylist<icommand> ();          for (ICommand Command:buildspec) {Boolean find = false;                  for (String id:builderids) {if (Command.getbuildername (). Equals (ID)) {find = true;              Break          }} if (!find) {newbuilders.add (command);  }} description.setbuildspec (Newbuilders.toarray (new icommand[0])); }  }

Org.eclipse.core.resources.builders is used to provide an operation that automatically builds when Iresource changes, like changing Java files, automatically builds, and displays errors. We extend this builder and use it in our own projects. All we have to do is implement the build process, as the time is controlled by eclipse
In the example above, when modifying a file, verify that there is a problem with the XML file content format and display it in the markers view, so add the extension point org.eclipse.core.resources.markers.
6, Markers Extension point

<extension         id= "Xmlproblem"         name= "Com.workflow.xmlProblem"         point= " Org.eclipse.core.resources.markers ">      <persistent            value=" true ">      </persistent>      <super            type= "Org.eclipse.core.resources.problemmarker" >      </super>   </extension>

7. Create the Project

Iworkspace workspace = Resourcesplugin.getworkspace ();  Iworkspaceroot root = Workspace.getroot ();    String projectName = "TESTNPB";  IProject project = Root.getproject (projectName);  if (!project.exists ()) {      project.create (null);      Project.open (null);  }  Iprojectdescription description = Project.getdescription ();  Projectutil.addnature2project (description, new string[]{liugangprojectnature.id}, NULL);  Project.setdescription (description, NULL);  

The created project becomes

Buildspec and Natures are more in. project files
When a file with the suffix. XML is modified, it is saved, it checks the contents of the XML file and displays an error message in the markers if there is a problem with the content


Reference: http://liugang594.iteye.com/blog/261513

http://blog.csdn.net/soszou/article/details/8018032

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.