基於Freemarker的eclipse plugin代碼產生器外掛程式開發

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

固定類型的軟體寫多了,裡面總是有一些複製粘貼改變類名改變數的基礎檔案,相似程度非常高。作為一名程式員,堅持不多寫一行重複代碼的精神,寫了一個Eclipse的代碼產生器外掛程式。外掛程式通過在xml檔案中配置的變數資訊及模版位置、目標檔案位置資訊,直接產生目標檔案,減少了大量的重複工作。

1.建立一個plug-in with a popup menu工程,引入freemarker.jar,配置popup menu的對應副檔名為.coding.xml

2.先寫核心的文檔產生代碼,保證使用main函數可調用。核心的內容是按照freemarker的要求寫好 模版路徑、模板檔案名稱、目標檔案路徑、目標檔案名、檔案所使用的字元集、以及包含所有資料的map

 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();21     22   }23 }

3.寫Action調用

public void run(IAction action) {                        //讀取選定的設定檔            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.使用System.out.print所列印的東西在外掛程式的運行環境下是不顯示的,ConsoleFactory是我寫的一個控制台輸出類,調用了Eclipse的控制台,主要用來在使用時給出相關的代碼產生提示。

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.主要內容完畢。使用時先配好xml檔案,如下樣本。在Eclipse中選中.coding.xml檔案,右鍵菜單 [代碼產生器]-->[產生代碼]

<?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="姓名" />        <variable name="age" value="年齡" />    </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>

 

還有很多需要擴充完善的地方,比如資料庫的自動支援、各類型文檔的產生。

項目地址 https://github.com/buaawp/codegen

 

基於Freemarker的eclipse plugin代碼產生器外掛程式開發

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.