Eclipse of Open Source code application

Source: Internet
Author: User
Tags modifier

When writing this, coincides with the Eclpse Mars (4.5) officially announced, and finally from the eclipse of Mars, and also from the beginning of my development product 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 has grown into a Big Mac-free technology platform. From pure desktop to Web, embedded in full bloom, individuals have experienced the process of growing from a common developer to committer and leaving the community, the only constant is that eclipse is still my only choice to develop Java.


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


Do not know if we have similar experience, every time the product release deadline, team will start to tidy up the Java source code in the license statement, strict unified development style for all team, basically is a kind of wishful thinking. It's impossible to start from the beginning. Don't fix it, can't publish it, fix it. No one wants to do this kind of crap, probably. 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 Ah, do not read out the file. Insert or replace? , 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 of these ways. To tell you the truth, it's really not.


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




This is for a lot of project architects with code format obsessive-Compulsive disorder. It's worse than killing them.


In fact, I didn't get this kind of bad work. I was just thinking about it. Suppose you want to handle it well. What should I do? Well, if you can manipulate every part of the Java source code?


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 is no problem, and Eclipse does it for you.


So I started to achieve such a high-speed repair Java source code in the license declaration of the gadget, the basic idea is based on the Eclipse JDT in the AST implementation. In Java syntax this granularity is changed and made into an eclipse plug-in, which is installed after everyone. You can finish your work by simply a button.


The detailed implementation process is 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 can be.

Do not know how to develop an Eclipse plug-in ah. Never mind, read this blog. You'll get it. (Don't forget the praise!) )


2. Inside 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 details are not shown here. Then get all the projects in Eclipse, traverse each project and process it, just deal with the open project, assuming you have a project you don't want to work on. Close.


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, just fix the Java project, no Java nature, are discarded.

After getting the Java project, get the entire package, which is different from the usual Java package. Look at the API in detail, and work after class.

Further, you will be able to 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, it is possible to start a formal license process.


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 AST, you can get all the comments in the Java source code, then you can insert or replace the license declaration of the file header according to various situations.


6. Member Variable type license declaration.

Such a license declaration 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 such a way as the following.

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 the member variable type is slightly cumbersome to handle. The main reason is that Java member variables are involved in the creation and parsing, but in fact it is not very difficult to understand, and from which you can learn how the AST fine-grained processing of the various components of the Java class.


7. Test.

Start a new eclipse Runtime for debugging Eclipse plug-in, import a few Java projects, and choose the Fix License action from the menu or toolbar. After that, check the random Java source file to see if license has been repaired.


Let's take a look at a simple test result.

This is before the fix.

Package Com.demo;public Class Demo {public demo () {}public void Hello () {}}


This one was repaired.

/* IBM Confidential * OCO SOURCE materials *  * (C) Copyright IBM Corporation,. * * The source code for  This program was not published or otherwise * divested of it trade secrets, irrespective of the what have been * deposited with  The U.S. copyright Office.*/package Com.demo;public class Demo {public static final String copyright = "(C) Copyright IBM Corporation 2013, 2014, 2015. "; Public Demo () {}public void Hello () {}}

8. Package distribution.

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


All right. 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 be able to download and test. The source code is accompanied by a specific installation of the document.


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







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.