Eclipse of Open Source code application

Source: Internet
Author: User
Tags modifier

At the time of writing this, coincided with the Eclpse Mars (4.5) officially released, finally by the eclipse to Mars, but also from I began to develop products based on the past 10 years, this 10 years, through the eclipse from the private core framework to embrace OSGi, by a single Java The IDE grew into a Big Mac technology platform, from pure desktop to Web, embedded full bloom, individuals also experienced from the ordinary developer to Committer, and leave the community process, the only constant is: Eclipse is still my only choice to develop Java.


For this open source project (group) that is being contributed and maintained by a group of the world's most smart people, I believe that any engineer who loves this industry can benefit from it, and this time I'll talk about a gadget I wrote based on Eclipse.


Do not know that everyone has similar experience, every product release deadline, team will start to tidy up the Java source code in the license declaration of the problem, strict unified development style for all the team, basically is a kind of hope, from the beginning impossible, how to do, do not repair it, Can't publish, fix it, such a bad job no one wants to do, presumably, repair Java source code inside the license declaration is divided into the following two main ways:

1. Since it is Java source code, then Java, do not read out the file, insert or replace it? , positioning, well, file head of easy, member variable type, have to think about ...

2. How to kill chickens with sledgehammer? , the combination of Unix inside the small command, minutes to fix.


I've seen the results in both ways, to be honest, it's not that good.


Is this a simple matter? It's not hard to tell the truth, but Oracle still puts the license declaration in the Java source code in the form below, in order to change the previous Sun's license statement to its own.




This is worse than killing them for many engineers with code-format obsessive-compulsive disorder.


In fact, I did not receive such a rotten job, I just think about the next, if you want to deal with, how to do? Well, if you can manipulate every part of the Java source code, it's okay.


Wow, somebody's going to jump right up and say, this has to know the compiler, right, is the compiler, but also not so complex, also used a little bit AST knowledge, do not know AST? Oh, there's nothing wrong with Eclipse doing it for you.


So I started to implement such a quick fix in the Java source code in the license declaration of the gadget, the basic idea is based on the Eclipse JDT in the AST implementation, in the Java syntax this granularity to modify, and made an Eclipse plug-in, which after everyone installed, You can finish the work by simply a button.


The specific implementation steps are as follows:


1. Generate an Eclipse plug-in project, choose a template, the simplest kind, can point toolbar above the button, pop up a "Hello, World" dialog box. Don't know how to develop an Eclipse plug-in ah, it doesn't matter, after reading this blog, you will. (Don't forget the praise!) )


2. In the action callback method, the code is as follows.

public void Run (IAction action) {license = Getlicensecontent (license_file_name); license_inline = Getlicensecontent ( License_inline_file_name), if (License_inline.endswith ("\ n")) {license_inline = license_inline.substring (0, License_ Inline.length ()-1);} sum = 0;iworkspace workspace = Resourcesplugin.getworkspace (); Iworkspaceroot root = Workspace.getroot (); iproject[] Projects = Root.getprojects (); for (IProject project:projects) {try {if (Project.isopen ()) {Processproject (Project)}} C Atch (Exception e) {messagedialog.openinformation (Window.getshell (), "Fix License", "Exception happened, please check The console log. "); E.printstacktrace (); return;}} Messagedialog.openinformation (Window.getshell (), "Fix License", "All Java source files has been processed. Total = "+ sum);}


First get license content, divided into the main license and in-line license, the specific content is not shown here, and then get all the projects in Eclipse, traverse each project and processing, here only to deal with open projects, if you do not want to deal with the project, close on the line.


3. Process the project.

private void Processproject (IProject project) throws Exception {if (project.isnatureenabled (" Org.eclipse.jdt.core.javanature ")) {Ijavaproject javaproject = javacore.create (project); ipackagefragment[] Packages = Javaproject.getpackagefragments (); for (Ipackagefragment mypackage:packages) {if (mypackage.getkind () = = Ipackagefragmentroot.k_source) {for (Icompilationunit unit:mypackage.getCompilationUnits ()) {sum = sum + 1; Processjavasource (unit);}}}}


Of course, only fix the Java project, no Java nature, are discarded.

After getting the Java project, get all the package, here the package and the usual meaning of the Java package, the specific meaning of the API, as after-school homework.

Further, you can get the Java source files, and get the compilation unit, with this, the future road will have direction.


4. Process the Java source files.

private void Processjavasource (Icompilationunit unit) throws Exception {Itextfilebuffermanager BufferManager = Filebuffers.gettextfilebuffermanager (); IPath path = Unit.getpath (); try {buffermanager.connect (path, null); I Textfilebuffer Textfilebuffer = buffermanager.gettextfilebuffer (path); IDocument doc = Textfilebuffer.getdocument (); if ((License!=null) && (license.length () > 0)) {processheadlicense (doc);} if ((license_inline! = null) && (license_inline.length () > 0)) {processinlinelicense (doc);} Textfilebuffer.commit (null, FALSE);} finally {buffermanager.disconnect (path, null);}}

There are some things in the Eclipse Jface text package that are different from the common Java file read/write API, but the basic idea is the same. When the IDocument object is taken, the formal license processing can begin.


5. Handle the Java File Header license declaration.

private void Processheadlicense (IDocument doc) throws Exception {Compilationunit cu = Getast (doc); Comment Comment = null;if (Cu.getcommentlist (). Size () = = 0) {doc.replace (0, 0, license);} else {Comment = (Comment) cu.getc Ommentlist (). get (0); String firstcomment = Doc.get (). substring (comment.getstartposition (), comment.getstartposition () + comment.getlength ()); if (Validateheadlicense (firstcomment)) {Doc.replace (Comment.getstartposition (), Comment.getlength (), license);} else {doc.replace (0, 0, license);}}} Private Compilationunit Getast (idocument doc) {astparser parser = Astparser.newparser (AST). JLS4);    Parser.setkind (astparser.k_compilation_unit);    Parser.setsource (Doc.get (). ToCharArray ());    Parser.setresolvebindings (true);    Compilationunit cu = (compilationunit) parser.createast (null);        return CU;}


Based on the AST, you can get all the comments in the Java source code, and then you can insert or replace the license declaration of the file header according to various situations.


6. Member Variable type license declaration.

This License statement resembles the following example.

public class Demo {public static final String copyright = "(C) Copyright IBM Corporation 2013, 2014, 2015."; Public Demo () {}public void Hello () {}}

It is handled in the following manner.

private void Processinlinelicense (IDocument doc) throws Exception {Compilationunit cu = Getast (doc);    Cu.recordmodifications ();    AST ast = Cu.getast ();    if (Cu.types (). Get (0) instanceof Typedeclaration) {typedeclaration td = (typedeclaration) cu.types (). get (0);    fielddeclaration[] fd = Td.getfields ();    if (Fd.length = = 0) {td.bodydeclarations (). Add (0, Createliceseinlinefield (AST));    } else {fielddeclaration firstfd = fd[0];    Variabledeclarationfragment VDF = (variabledeclarationfragment) firstfd.fragments (). get (0);    if (Vdf.getname (). Getidentifier (). Equals ("COPYRIGHT")) {td.bodydeclarations (). Remove (0);    Td.bodydeclarations (). Add (0, Createliceseinlinefield (AST));    } else {td.bodydeclarations (). Add (0, Createliceseinlinefield (AST)); }}}//record Changestextedit edits = cu.rewrite (doc, null); edits.apply (DOC);} Private Fielddeclaration Createliceseinlinefield (AST ast) {Variabledeclarationfragment VDF = Ast.newvariabledeclarationfragmenT (); Vdf.setname (Ast.newsimplename ("COPYRIGHT")); StringLiteral SL = ast.newstringliteral (); Sl.setliteralvalue (license_inline); Vdf.setinitializer (SL); Fielddeclaration fd = ast.newfielddeclaration (VDF); Fd.modifiers (). AddAll (Ast.newmodifiers (modifier.public | modifier.static | modifier.final)); Fd.settype (Ast.newsimpletype (Ast.newsimplename ("String")); return FD;}

The license declaration of a member variable type is slightly cumbersome to handle, mainly because of the creation and parsing of Java member variables, but it is not very difficult to understand, and it is possible to learn how the AST handles the various components of the Java class.


7. Test.

Start a new debug Eclipse plug-in Eclipse Runtime, import any number of Java projects, select the "Fix License" action from the menu or toolbar, and check any Java source files after completion. See if license has been repaired.


8. Package distribution.

The tool plug-in can be packaged and installed by Eclipse's standard plug-in, or generated with an update site for users to install online.


Well, wordy so much, to the end of the moment, the last sentence, this gadget all the source code has been on GitHub open source, like to download and test, the source is attached to a detailed installation of the document.


Tool Address: Https://github.com/alexgreenbar/open_tools.git







Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Eclipse of Open Source code application

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.