Freemarker-based Eclipse Plugin code generator plug-in development

Source: Internet
Author: User
Tags generator



Fixed type of software write more, there are always some copy and paste change the class name change the amount of basic files, similar degree very high. As a programmer, stick to the spirit of not writing a single line of repetitive code, writing an Eclipse code generator plugin. The plug-in generates the target file directly by the variable information and template location, and the target file location information, which is configured in the XML file, which reduces a lot of duplication work.






1. Create a plug-in with a popup menu project, introduce Freemarker.jar, configure the popup menu corresponding file name extension. coding.xml



2. Write the core of the document generation code, to ensure that the main function can be called. The core content is to write the template path in accordance with the requirements of Freemarker, the file name, the target path, the target filename, the character set used by the file, and the map containing all the data.

1 public class CodegenUtil
 2 {
 3 public static void genFile (String templatePath, String templateFileName, String targetPath, String targetFileName, String charset, Map paramMap)
 4 throws IOException, TemplateException
 5 {
 6
 7 File localFile = new File (targetPath, targetFileName);
 8 if (! LocalFile.exists ()) {
 9 if (! LocalFile.getParentFile (). Exists ())
10 localFile.getParentFile (). Mkdirs ();
11 localFile.createNewFile ();
12}
13 OutputStreamWriter localOutputStreamWriter = new OutputStreamWriter (new FileOutputStream (localFile), charset);
14
15 Configuration freemarkerConfigration = new Configuration ();
16 freemarkerConfigration.setDirectoryForTemplateLoading (new File (templatePath));
17
18 Template localTemplate = freemarkerConfigration.getTemplate (templateFileName, charset);
19 localTemplate.process (paramMap, localOutputStreamWriter);
20 localOutputStreamWriter.close ();
twenty one     
twenty two   }
twenty three }
3. Write Action call

public void run (IAction action) {
        
        // Read the selected configuration file
        IStructuredSelection selection = (IStructuredSelection) this.selection;

        ConsoleFactory.printToConsole ("-------- Start Coding --------", true);
        
        for (Object element: selection.toList ()) {
            File file = (File) element;
            String fullpath = file.getLocationURI (). GetPath ();
            
            Map <String, String> params;
            List <Map <String, String >> templateMapList = new ArrayList <Map <String, String >> ();
            
            try {

                String configfilepath = fullpath.substring (1);
                ConsoleFactory.printToConsole ("... load coding config" + configfilepath, true);
                
                params = XmlUtil.getVars (configfilepath);
                templateMapList = XmlUtil.getTemplates (configfilepath);
                
                for (Map <String, String> templateMap: templateMapList) {
                    String templateFilePath = templateMap.get (XmlUtil.TEMPLATE_PATH);
                    String templateFileName = templateMap.get (XmlUtil.TEMPLATE_NAME);
                    String targetFilePath = templateMap.get (XmlUtil.TARGET_PATH);
                    String targetFileName = templateMap.get (XmlUtil.TARGET_NAME);
                    
                    ConsoleFactory.printToConsole ("... coding ..." + targetFilePath + "\\" + targetFileName, true);

                    params.put (XmlUtil.TEMPLATE_PATH, templateFilePath);
                    params.put (XmlUtil.TEMPLATE_NAME, templateFileName);
                    params.put (XmlUtil.TARGET_PATH, targetFilePath);
                    params.put (XmlUtil.TARGET_NAME, targetFileName);
                    
                    String charset = params.get (XmlUtil.CHARSET);
                    
                    CodegenUtil.genFile (templateFilePath, templateFileName, targetFilePath, targetFileName, charset, params);

                }
                
            } catch (Exception e) {
                e.printStackTrace ();
            }
        }

        ConsoleFactory.printToConsole ("-------- Finish Coding --------", true);
        
    }
4. The things printed using System.out.print are not displayed in the plug-in running environment. ConsoleFactory is a console output class I wrote, which calls the Eclipse console, which is mainly used to give relevant information when using Code generation tips.

public class ConsoleFactory implements IConsoleFactory {

    private static MessageConsole console = new MessageConsole ("", null);
    static boolean exists = false;
    
    @Override
    public void openConsole () {
        showConsole ();
    }
    
    private static void showConsole () {
        if (console! = null) {
            IConsoleManager manager = ConsolePlugin.getDefault (). GetConsoleManager ();
            IConsole [] existing = manager.getConsoles ();
            
            exists = false;
            for (int i = 0; i <existing.length; i ++) {
                if (console == existing [i]) {
                    exists = true;
                }
            }
            if (! exists) {
                manager.addConsoles (new IConsole [] {console});
            }
            
        }
    }
    
    public static void closeConsole () {
        IConsoleManager manager = ConsolePlugin.getDefault (). GetConsoleManager ();
        if (console! = null) {
            manager.removeConsoles (new IConsole [] {console});
        }
    }
    
    public static MessageConsole getConsole () {
        showConsole ();
        return console;
    }
    
    public static void printToConsole (String message, boolean activate) {
        MessageConsoleStream printer = ConsoleFactory.getConsole (). NewMessageStream ();
        printer.setActivateOnWrite (activate);
        printer.println (message);
    }

}
5. The main content is completed. When using it, first configure the xml file, as shown in the following example. Select the .coding.xml file in Eclipse, right-click menu [Code Generator]-> [Generate Code]

<? xml version = "1.0" encoding = "utf-8"?>
<config xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance">
    <variables>
        <variable name = "developer" value = "PennPeng" />
        <variable name = "charset" value = "utf-8" />
<variable name = "class" value = "CodeGen" />
        <variable name = "name" value = "Name" />
        <variable name = "age" value = "age" />
    </ variables>
    
    <templates>
        <template>
            <variable name = "templatepath" value = "E: \ CodeGenTest \ template" />
            <variable name = "templatename" value = "a.ftl" />
            <variable name = "targetpath" value = "E: \ CodeGenTest" />
            <variable name = "targetname" value = "CodeGen.java" />
        </ template>
        <template>
            <variable name = "templatepath" value = "E: \ CodeGenTest \ template" />
            <variable name = "templatename" value = "b.ftl" />
            <variable name = "targetpath" value = "E: \ CodeGenTest" />
            <variable name = "targetname" value = "CodeGen2.java" />
        </ template>
    </ templates>
</ config>
 

There are many areas that need to be expanded and improved, such as automatic database support and the generation of various types of documents.

Project address https://github.com/buaawp/codegen

 

Development of eclipse plugin code generator plugin based on Freemarker

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.