ITeye博客

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

danlley · 2007-08-06 16:55 · PM(Project Manage) · 企业架构 · Markdown

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

 

java 代码

  1. public class VelocitySamples{

  2. private VelocityContext context;

  3. /**

  4. * 

    comments : 程序入口

  5. *

  6. * author  danlley

  7. * coding date  2007-7-24

  8. * @param path            资源文件路径,默认与Maven默认资源文件路径相同

  9. * @param template        资源仓库

  10. * @param destPath        目标路径,默认与Maven编译路径相同

  11. * @throws Exception

  12. */

  13. public void dealFile(String path,String template,String destPath) throws Exception{

  14. File[] files=new File(path).listFiles();

  15. String errMsg="请核对路径: "+path+" 确认是否有资源文件存在于此路径下.";

  16. if(files.length==0)

  17. throw new FileNotFoundException(errMsg);

  18. context=new VelocityContext();

  19. applyProperties(path+template);//initial the VelocityContext

  20. Velocity.init();

  21. for(File file:files){

  22. if(!file.isFile())

  23. continue;

  24. String origName=file.getName();

  25. if(!checkFile(origName))

  26. continue;

  27. createFile(origName,destPath,path);

  28. }

  29. }

  30. /**

  31. * 

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

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

  33. *

  34. * author  danlley

  35. * coding date  2007-8-6

  36. * @param origName

  37. * @return

  38. * @throws Exception

  39. */

  40. public boolean checkFile(String origName)throws Exception{

  41. int index=origName.lastIndexOf(".");

  42. String tail=origName.substring(index+1,origName.length());

  43. if("danlley".equals(tail))

  44. return true;

  45. else

  46. return false;

  47. }

  48. /**

  49. * 

    comments : 生成转换后的文件

  50. *

  51. * author  danlley

  52. * coding date  2007-7-24

  53. * @param origFileName

  54. * @param destPath

  55. * @param targetPath

  56. * @throws Exception

  57. */

  58. public void createFile(String origFileName,String destPath,String targetPath) throws Exception{

  59. int index=origFileName.lastIndexOf(".");

  60. String destFileName=origFileName.substring(0,index);

  61. BufferedWriter writer=new BufferedWriter(new FileWriter(destPath+destFileName));

  62. Template template=Velocity.getTemplate(targetPath+origFileName);

  63. template.merge(context,writer);

  64. writer.flush();

  65. writer.close();

  66. }

  67. /**

  68. * 

    comments : 为 VelocityContext 获取替换信息

  69. *

  70. * author  danlley

  71. * coding date  2007-7-24

  72. * @param path

  73. * @throws Exception

  74. */

  75. public void applyProperties(String path) throws Exception{

  76. FileInputStream fis=new FileInputStream(path);

  77. if(null==fis)throw new NullPointerException("broken file or bad file!");

  78. Properties prop=new Properties();

  79. prop.load(fis);

  80. Enumeration enu=prop.keys();

  81. while(enu.hasMoreElements()){

  82. String key=enu.nextElement().toString();

  83. String value=prop.get(key).toString();

  84. context.put(key,value);

  85. }

  86. }

  87. }

既然是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. <plugin>
  13. <groupId>org.apache.maven.pluginsgroupId>
  14. <artifactId>maven-compiler-pluginartifactId>
  15. <configuration>
  16. <source>1.5source>
  17. <target>1.5target>
  18. configuration>
  19. plugin>
  20. plugins>
  21. build>
  22. <dependencies>
  23. <dependency>
  24. <groupId>junitgroupId>
  25. <artifactId>junitartifactId>
  26. <version>4.0version>
  27. <scope>testscope>
  28. dependency>
  29. <dependency>
  30. <groupId>velocitygroupId>
  31. <artifactId>velocityartifactId>
  32. <version>1.4version>
  33. dependency>
  34. <dependency>
  35. <groupId>org.apache.mavengroupId>
  36. <artifactId>maven-plugin-apiartifactId>
  37. <version>2.0version>
  38. dependency>
  39. dependencies>
  40. project>

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

xml 代码

  1. <plugin>
  2. <groupId>org.apache.maven.pluginsgroupId>
  3. <artifactId>maven-compiler-pluginartifactId>
  4. <configuration>
  5. <source>1.5source>
  6. <target>1.5target>
  7. configuration>
  8. 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. import java.io.File;

  3. import org.apache.maven.plugin.AbstractMojo;

  4. import org.apache.maven.plugin.MojoExecutionException;

  5. /**

  6. * replace.

  7. *

  8. * @goal replace

  9. */

  10. public class VelocityMojo extends AbstractMojo {

  11. /**

  12. * scriptSourceDirectory.

  13. *

  14. * @parameter default-value="${project.build.scriptSourceDirectory}"

  15. */

  16. private String scriptSourceDirectory;

  17. /**

  18. * outputDirectory.

  19. *

  20. * @parameter default-value="${project.build.outputDirectory}"

  21. */

  22. private String outputDirectory;

  23. /**

  24. * template.

  25. *

  26. * @parameter default-value="${project.build.outputDirectory}"

  27. */

  28. private String template;

  29. public void execute() throws MojoExecutionException {

  30. try {

  31. getLog().info("+-----------------------------------------+");

  32. getLog().info("|             Velocity Files:             |");

  33. getLog().info("+-----------------------------------------+");

  34. listFile();

  35. VelocitySamples _instance = new VelocitySamples();

  36. _instance.dealFile(scriptSourceDirectory + "/", template, outputDirectory + "/");

  37. getLog().info("生成文件已经被放置在路径:"+outputDirectory+" 请核对!");

  38. } catch (Exception e) {

  39. e.printStackTrace();

  40. }

  41. }

  42. /**

  43. * 

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

  44. *

  45. * author  danlley

  46. * coding date  2007-8-6

  47. * @throws Exception

  48. */

  49. public void listFile() throws Exception {

  50. File[] files = (new File(scriptSourceDirectory)).listFiles();

  51. for (File file : files) {

  52. VelocitySamples ve = new VelocitySamples();

  53. if (ve.checkFile(file.getName())) {

  54. getLog().info(file.getName());

  55. }

  56. }

  57. }

  58. }

接下来进行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)

暂无评论。

评论功能维护中,当前仅展示历史评论。