在Maven2插件中用Velocity对配置文件的集中管理

正如我在“用Velocity进行配置文件信息的集中管理 ”————http://danlley.iteye.com/blog/106130 中的许诺,这个专题将专门说说如何在Maven2插件中用Velocity对配置文件的集中管理。有了上个专题的基础,我这里也就化繁就简了。下面这段代码是通过上个专题的例子进行改写、整理、重构以后的代码,核心任务就是处理配置文件。

 

java 代码
  1. public class VelocitySamples{   
  2.     private VelocityContext context;   
  3.   
  4.     /**  
  5.      * 

    comments : 程序入口

     
  6.      *          

     

     
  7.      * author  danlley  
  8.      * coding date  2007-7-24  
  9.      * @param path            资源文件路径,默认与Maven默认资源文件路径相同  
  10.      * @param template        资源仓库  
  11.      * @param destPath        目标路径,默认与Maven编译路径相同  
  12.      * @throws Exception  
  13.      */  
  14.     public void dealFile(String path,String template,String destPath) throws Exception{   
  15.         File[] files=new File(path).listFiles();   
  16.         String errMsg="请核对路径: "+path+" 确认是否有资源文件存在于此路径下.";   
  17.         if(files.length==0)   
  18.             throw new FileNotFoundException(errMsg);   
  19.         context=new VelocityContext();   
  20.         applyProperties(path+template);//initial the VelocityContext   
  21.         Velocity.init();   
  22.         for(File file:files){   
  23.             if(!file.isFile())   
  24.                 continue;   
  25.             String origName=file.getName();   
  26.             if(!checkFile(origName))   
  27.                 continue;   
  28.             createFile(origName,destPath,path);   
  29.         }   
  30.     }   
  31.        
  32.     /**  
  33.      * 

    comments : 此方法用于检查文件是否为待处理文件,在本例子中待处理文件的后缀均为“*.danlley”

     
  34.      *               如:log4j配置文件则为log4j.xml.danlley,转换后为log4j.xml  
  35.      *          

     

     
  36.      * author  danlley  
  37.      * coding date  2007-8-6  
  38.      * @param origName  
  39.      * @return  
  40.      * @throws Exception  
  41.      */  
  42.     public boolean checkFile(String origName)throws Exception{   
  43.         int index=origName.lastIndexOf(".");   
  44.         String tail=origName.substring(index+1,origName.length());   
  45.         if("danlley".equals(tail))   
  46.             return true;   
  47.         else  
  48.             return false;   
  49.     }   
  50.   
  51.     /**  
  52.      * 

    comments : 生成转换后的文件

     
  53.      *          

     

     
  54.      * author  danlley  
  55.      * coding date  2007-7-24  
  56.      * @param origFileName  
  57.      * @param destPath  
  58.      * @param targetPath  
  59.      * @throws Exception  
  60.      */  
  61.     public void createFile(String origFileName,String destPath,String targetPath) throws Exception{   
  62.         int index=origFileName.lastIndexOf(".");   
  63.         String destFileName=origFileName.substring(0,index);   
  64.         BufferedWriter writer=new BufferedWriter(new FileWriter(destPath+destFileName));   
  65.         Template template=Velocity.getTemplate(targetPath+origFileName);   
  66.         template.merge(context,writer);   
  67.         writer.flush();   
  68.         writer.close();   
  69.     }   
  70.   
  71.     /**  
  72.      * 

    comments : 为 VelocityContext 获取替换信息

     
  73.      *          

     

     
  74.      * author  danlley  
  75.      * coding date  2007-7-24  
  76.      * @param path  
  77.      * @throws Exception  
  78.      */  
  79.     public void applyProperties(String path) throws Exception{   
  80.         FileInputStream fis=new FileInputStream(path);   
  81.         if(null==fis)throw new NullPointerException("broken file or bad file!");   
  82.         Properties prop=new Properties();   
  83.         prop.load(fis);   
  84.         Enumeration enu=prop.keys();   
  85.         while(enu.hasMoreElements()){   
  86.             String key=enu.nextElement().toString();   
  87.             String value=prop.get(key).toString();   
  88.             context.put(key,value);   
  89.         }   
  90.     }   
  91. }  

既然是Maven插件开发,那我这里也就用Maven来管理工程了,下面是POM的配置祥单:

xml 代码
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.     <modelVersion>4.0.0modelVersion>  
  4.     <groupId>org.danlleygroupId>  
  5.     <artifactId>maven-velocity-pluginartifactId>  
  6.     <packaging>maven-pluginpackaging>  
  7.     <version>1.0version>  
  8.     <name>maven-velocity-pluginname>  
  9.     <url>http://maven.apache.orgurl>  
  10.     <build>  
  11.         <plugins>  
  12.             <!---->  
  13.             <plugin>  
  14.                 <groupId>org.apache.maven.pluginsgroupId>  
  15.                 <artifactId>maven-compiler-pluginartifactId>  
  16.                 <configuration>  
  17.                     <source>1.5source>  
  18.                     <target>1.5target>  
  19.                 configuration>  
  20.             plugin>  
  21.         plugins>  
  22.     build>  
  23.     <dependencies>  
  24.         <dependency>  
  25.             <groupId>junitgroupId>  
  26.             <artifactId>junitartifactId>  
  27.             <version>4.0version>  
  28.             <scope>testscope>  
  29.         dependency>  
  30.         <dependency>  
  31.             <groupId>velocitygroupId>  
  32.             <artifactId>velocityartifactId>  
  33.             <version>1.4version>  
  34.         dependency>  
  35.         <dependency>  
  36.             <groupId>org.apache.mavengroupId>  
  37.             <artifactId>maven-plugin-apiartifactId>  
  38.             <version>2.0version>  
  39.         dependency>  
  40.     dependencies>  
  41. project>  

让我不解的是Maven在进行代码编译时采用的还是Older Pattern,但是我的代码又用到了一些JDK5的某些特性,万般无赖,我只好用下面的方式进行显式申明了:

xml 代码
  1. <!---->  
  2. <plugin>  
  3.     <groupId>org.apache.maven.pluginsgroupId>  
  4.     <artifactId>maven-compiler-pluginartifactId>  
  5.     <configuration>  
  6.         <source>1.5source>  
  7.         <target>1.5target>  
  8.     configuration>  
  9. plugin>  

还需要强调的一点是下面这段代码,我这里没有用jar也没有用war,因为我写的不是资源包,而是插件:

xml 代码
  1. <packaging>maven-pluginpackaging>  

接下来在src/main/scripts路径下定义文件velocity.mojos.xml。内容如下:

xml 代码
  1. <pluginMetadata>  
  2.     <mojos>  
  3.         <mojo>  
  4.             <goal>velocitygoal>  
  5.             <call>velocitycall>  
  6.             <description>Say Hello, World.description>  
  7.         mojo>  
  8.     mojos>  
  9. pluginMetadata>  

Maven 官方的说明中好像说mojo的文件命名必须与goal一致,因此,由于我的goal是velocity,那mojo也就成了velocity.mojos.xml。当然至于这个goal到最后回去call什么东西,其实这里并不是很重要了,只要在使用plugin的工程中声明你需要call什么东西就可以了。如果大家对Maven插件开发比较感兴趣,可以到http://danlley.iteye.com/blog/102159去看看我的另外一片专题文章,希望对大家能够有所帮助。有了这篇文章做基础,我下面也就省去部分Maven相关的概念,直接给出我实现的钩子程序了(需要说明的一点是,在下面的这段程序中,注释和代码同样重要)。

java 代码
  1. package org.danlley.util.samples;   
  2.   
  3. import java.io.File;   
  4.   
  5. import org.apache.maven.plugin.AbstractMojo;   
  6. import org.apache.maven.plugin.MojoExecutionException;   
  7.   
  8. /**  
  9.  * replace.  
  10.  *   
  11.  * @goal replace  
  12.  */  
  13. public class VelocityMojo extends AbstractMojo {   
  14.     /**  
  15.      * scriptSourceDirectory.  
  16.      *   
  17.      * @parameter default-value="${project.build.scriptSourceDirectory}"  
  18.      */  
  19.     private String scriptSourceDirectory;   
  20.     /**  
  21.      * outputDirectory.  
  22.      *   
  23.      * @parameter default-value="${project.build.outputDirectory}"  
  24.      */  
  25.     private String outputDirectory;   
  26.     /**  
  27.      * template.  
  28.      *   
  29.      * @parameter default-value="${project.build.outputDirectory}"  
  30.      */  
  31.     private String template;   
  32.   
  33.     public void execute() throws MojoExecutionException {   
  34.         try {   
  35.             getLog().info("+-----------------------------------------+");   
  36.             getLog().info("|             Velocity Files:             |");   
  37.             getLog().info("+-----------------------------------------+");   
  38.             listFile();   
  39.             VelocitySamples _instance = new VelocitySamples();   
  40.             _instance.dealFile(scriptSourceDirectory + "/", template, outputDirectory + "/");   
  41.             getLog().info("生成文件已经被放置在路径:"+outputDirectory+" 请核对!");   
  42.         } catch (Exception e) {   
  43.             e.printStackTrace();   
  44.         }   
  45.     }   
  46.        
  47.     /**  
  48.      * 

    comments : 只会列出需要处理的文件

     
  49.      *          

     

     
  50.      * author  danlley  
  51.      * coding date  2007-8-6  
  52.      * @throws Exception  
  53.      */  
  54.     public void listFile() throws Exception {   
  55.         File[] files = (new File(scriptSourceDirectory)).listFiles();   
  56.         for (File file : files) {   
  57.             VelocitySamples ve = new VelocitySamples();   
  58.             if (ve.checkFile(file.getName())) {   
  59.                 getLog().info(file.getName());   
  60.             }   
  61.         }   
  62.     }   
  63. }  

接下来进行install,接受到 BUILD SUCCESSFUL消息意味着插件开发过程结束,下面说说使用。在需要使用该插件的Maven2工程中打开POM,加入如下代码:

xml 代码
  1. <build>  
  2.     <plugins>  
  3.         <plugin>  
  4.             <groupId>org.danlleygroupId>  
  5.             <artifactId>maven-velocity-pluginartifactId>  
  6.             <version>1.0version>  
  7.             <configuration>  
  8.                 <template>sample_data.propertiestemplate>  
  9.             configuration>  
  10.             <executions>  
  11.                 <execution>  
  12.                     <phase>compilephase>  
  13.                     <goals>  
  14.                         <goal>replacegoal>  
  15.                     goals>  
  16.                 execution>  
  17.             executions>  
  18.         plugin>  
  19.     plugins>  
  20. build>  

 

 

加入工程以后我的测试执行结果如下:

F:\workspaces\maven-velocity-lab>mvn compile
[INFO] Scanning for projects...
[INFO] -------------------------------------------------------------------------
---
[INFO] Building maven-velocity-lab
[INFO]    task-segment: [compile]
[INFO] -------------------------------------------------------------------------
---
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [velocity:replace {execution: default}]
[INFO] +-----------------------------------------+
[INFO] |             Velocity Files:             |
[INFO] +-----------------------------------------+
[INFO] dlmchibernate.cfg.xml.danlley
[INFO] log4j.xml.danlley
[INFO] dlhibernate.cfg.xml.danlley
[INFO] download_config.xml.danlley
[INFO] 生成文件已经被放置在路径:F:\workspaces\maven-velocity-lab\target\classes
 请核对!
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 second
[INFO] Finished at: Mon Aug 06 16:38:58 CST 2007
[INFO] Final Memory: 5M/9M
[INFO] ------------------------------------------------------------------------

 

参考资料:http://maven.apache.org/guides/plugin/guide-java-plugin-development.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值