固定类型的软件写多了,里面总是有一些复制粘贴改变类名改变量的基础文件,相似程度非常高。作为一名程序员,坚持不多写一行重复代码的精神,写了一个Eclipse的代码生成器插件。插件通过在xml文件中配置的变量信息及模版位置、目标文件位置信息,直接生成目标文件,减少了大量的重复工作。

1.建立一个plug-in with a popup menu工程,引入freemarker.jar,配置popup menu的对应文件扩展名为.coding.xml

2.先写核心的文档生成代码,保证使用main函数可调用。核心的内容是按照freemarker的要求写好 模版路径、模板文件名、目标文件路径、目标文件名、文件所使用的字符集、以及包含所有数据的map

 public class CodegenUtil
 {
   public static void genFile(String templatePath, String templateFileName, String targetPath, String targetFileName, String charset, Map paramMap)
     throws IOException, TemplateException
   {

     File localFile = new File(targetPath, targetFileName);
     if (!localFile.exists()) {
       if (!localFile.getParentFile().exists())
         localFile.getParentFile().mkdirs();
       localFile.createNewFile();
     }
     OutputStreamWriter localOutputStreamWriter = new OutputStreamWriter(new FileOutputStream(localFile), charset);

     Configuration freemarkerConfigration = new Configuration();
     freemarkerConfigration.setDirectoryForTemplateLoading(new File(templatePath));

     Template localTemplate = freemarkerConfigration.getTemplate(templateFileName, charset);
     localTemplate.process(paramMap, localOutputStreamWriter);
     localOutputStreamWriter.close();

   }
 }

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代码生成器插件开发的更多相关文章

  1. 基于 SWTBot 进行 Eclipse GUI 自动化测试

    背景简介 在软件开发领域,持续集成和部署对于软件测试自动化提出了越来越高的要求,基于 Eclipse 应用在这一需求中仍然占据重要的组成部分.目前主流的测试自动化工具主要以录制回放的功能为主,辅助以脚 ...

  2. Hadoop 1.1.2 eclipse plugin 编译 win7 集成

    Windows平台上使用ANT编译Hadoop Eclipse Plugin 一.准备工作:   1.安装JDK 下载页面:http://www.oracle.com/technetwork/java ...

  3. Peer Code Reviews Made Easy with Eclipse Plug-In

    欢迎关注我的社交账号: 博客园地址: http://www.cnblogs.com/jiangxinnju/p/4781259.html GitHub地址: https://github.com/ji ...

  4. freemarker编辑器eclipse插件

    freemarker编辑器eclipse插件 支持语法高亮,语法校验,代码提示的工具 freemarker  IDE(JBoss): http://download.jboss.org/jbossto ...

  5. GWT(Google Web Tookit) Eclipse Plugin的zip下载地址(同时提供GWT Designer下载地址)

    按照Eclipse Help->Install new software->....(这里是官方安装文档:http://code.google.com/intl/zh-CN/eclipse ...

  6. Installing the Eclipse Plugin

    Installing the Eclipse Plugin Android offers a custom plugin for the Eclipse IDE, called Android Dev ...

  7. Eclipse Plugin Dev Materials

    以下资料是本人在开发Eclipse 插件时候收集的一些比较有用的资料Link,和大家分享下. 比较权威的资料: Helpful Eclipse Plugin Websites: Eclipse Art ...

  8. Eclipse plugin web site 发布和版本更新

    Eclipse plugin web site 发布和版本更新 在eclipse插件开发过程中免不了要发布1.0, 1.1, 1.2…….等等,随着版本的递增,假如每次都发布一个插件zip包,那使用者 ...

  9. eclipse plugin 导出插件包

    当我们的插件在完成一个阶段性开发的时候,我们要发布一个1.0的版本.这个时候会碰到一个问题.如何把我们的插件打成包?有多种途径,下面具体讨论一下. 首先从插件完成到被他人(或者我们自己)使用有两个步骤 ...

随机推荐

  1. JavaEE笔记(九)

    List.Map.Set的配置 bean package com.spring.bean; import java.util.List; import java.util.Map; import ja ...

  2. P4198 楼房重建

    P4198 楼房重建 集中写博客= = 首先把高度变成斜率 然后就比较玄学了,首先用线段树维护一个区间的斜率最大值,和只看这个区间时能看见的楼房个数ans 然后更新时先更新max,再处理神奇的ans ...

  3. [Luogu4921]情侣?给我烧了![错位排列]

    题意 题意很清楚 \滑稽 分析 对于每一个询问 \(k\) ,记 \(g(x)\) 表示 \(x\) 对情侣都错开的方案总数,那么答案可以写成如下形式: \[ {ans}_k= \binom{n}{k ...

  4. Object C学习笔记11-数组

    在Object C也提供了类似C#中的Array数组对象,在Object C中使用NSArray 来创建数组:但是在Object C中NSArray 只能存放对象类型的指针,不能存放int,char, ...

  5. zabbix监控DELL服务器硬件状态

    zabbix监控DELL服务器硬件状态 登录dell服务的管理页面 默认用户名:root 密码:calvin 服务器开放snmp信息,开启完应用 Zabbix服务器导入dell监控硬件模板 验证 sn ...

  6. CentOS 下 SonarQube 6.7 的下载、配置、问题排查

    CentOS 下 SonarQube 6.7 的下载.配置.问题排查 系统: CentOS 7 x86_64 SonarQube 版本: 6.7.3 Java 版本: 1.8.0_171 MySQL ...

  7. Centos 7 安装Zabbix

    一.环境准备与说明: 1.zabbix server 版本:3.4.12 ,https://www.zabbix.com/download 2.zabbix agent版本:3.4.14,https: ...

  8. Hyperledger Fabric CA User’s Guide——CA用户指南(一)

    Fabric CA用户指南 Hyperledger Fabric CA是一种用于Hyperledger Fabric的认证机构(CA). 它提供了如下特性: 登记身份(注册ID),或者连接到作为用户注 ...

  9. Hyperledger Fabric 账本结构解析

    前言 现在很多人都在从事区块链方面的研究,作者也一直在基于Hyperledger Fabric做一些开发工作.为了方便后来人更快的入门,本着“开源”的精神,在本文中向大家讲解一下Hyperledger ...

  10. 基于Python的信用评分卡模型分析(二)

    上一篇文章基于Python的信用评分卡模型分析(一)已经介绍了信用评分卡模型的数据预处理.探索性数据分析.变量分箱和变量选择等.接下来我们将继续讨论信用评分卡的模型实现和分析,信用评分的方法和自动评分 ...