如何外化maven构建文件? [英] How to externalize pieces of maven build file?

查看:156
本文介绍了如何外化maven构建文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了如何以XML格式对配置文件进行版本化的问题。最简单的方法是编写XSLT更新。应用程序的每个版本都有自己的XSLT更新。所有这些更新文件都足够小,可以通过IDE进行管理,尤其是 DIFF 工具。

I was faced to a problem how to version a configuration file in XML format. The easiest way is to write XSLT updates. Every release of the application has its own XSLT update. All these update files are small enough to be managable by the IDE, especially its DIFF tool.

由于项目已经开发为Maven2 Java逻辑解决方案是通过maven构建文件触发这些更新。

Since the project is already been developed as Maven2 Java logical solution was to trigger these updates through maven build file.

这就是今天应用一组更新的部分:

This is how the section for applying a set of updates looks today:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xml-maven-plugin</artifactId>
  <executions>
    <execution>
    <phase>compile</phase>
      <goals>
        <goal>transform</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <transformationSets>
      <transformationSet>
        <dir>config/xsltUpdates/input</dir>
        <stylesheet>config/xsltUpdates/update1-8-3.xsl</stylesheet>
        <outputDir>config/xsltUpdates/update1-8-3</outputDir>
      </transformationSet>
      <transformationSet>
         <dir>config/xsltUpdates/update1-8-3</dir>
         <stylesheet>config/xsltUpdates/update1-8-9.xsl</stylesheet>
         <outputDir>config/xsltUpdates/update1-8-9</outputDir>
      </transformationSet>
      <transformationSet>
        <dir>config/xsltUpdates/update1-8-9</dir>
        <stylesheet>config/xsltUpdates/update1-9-0.xsl</stylesheet>
        <outputDir>config/xsltUpdates/update1-9-0</outputDir>
      </transformationSet>
      <transformationSet>
        <dir>config/xsltUpdates/update1-9-0</dir>
        <stylesheet>config/xsltUpdates/update1-10-0.xsl</stylesheet>
        <outputDir>config/xsltUpdates/update1-10-0</outputDir>
      </transformationSet>
      <transformationSet>
        <dir>config/xsltUpdates/update1-10-0</dir>
        <stylesheet>config/xsltUpdates/update1-10-0-1.xsl</stylesheet>
        <outputDir>config/xsltUpdates/update1-10-0-1</outputDir>
      </transformationSet>
      <transformationSet>
        <dir>config/xsltUpdates/update1-10-0-1</dir>
        <stylesheet>config/xsltUpdates/update1-10-0-2.xsl</stylesheet>
        <outputDir>config/xsltUpdates/update1-10-0-2</outputDir>
      </transformationSet>
      <transformationSet>
        <dir>config/xsltUpdates/update1-10-0-2</dir>
        <stylesheet>config/xsltUpdates/updateCurrent.xsl</stylesheet>
        <outputDir>config/xsltUpdates/output</outputDir>
      </transformationSet>
    </transformationSets>
  </configuration>
  <dependencies>
    <dependency>
      <groupId>net.sf.saxon</groupId>
      <artifactId>saxon</artifactId>
      <version>8.7</version>
    </dependency>
  </dependencies>
</plugin>

我想在一些properties / xml文件导入中外化有关transformationSet的信息。我的pom.xml文件更干净,外化信息更易于维护。

I would like to externalize information about transformationSet in some properties/xml file import. My pom.xml file will be cleaner and externalized info easier for maintenance.

我该怎么做?

我可以在构建文件中使用一些迭代控制语句吗?有没有办法从一些外部文件导入数据?

Can I use some iterating control statement inside the build file? Is there a way to import data from some external file?

推荐答案

有些插件允许你使用外部描述符(例如< a href =http://maven.apache.org/plugins/maven-assembly-plugin/examples/sharing-descriptors.html =nofollow noreferrer> maven-assembly-plugin )。不幸的是,xml-maven-plugin还不是其中之一。

Some plugins allow you to use external descriptors (for example the maven-assembly-plugin). Unfortunately the xml-maven-plugin isn't yet one of them.

一个选项是从xml-maven-plugin复制相关目标并从中窃取处理maven-shared-io进入目标。我一直在寻找这样做,以期针对各种插件提出请求以使用描述符文件和LocatorStrategy方法来查找描述符。这里有一些处理将修改xml-maven-plugin以允许使用描述符。请注意,所涉及的文件几乎没有验证,因此它有点脆弱,但确实有效。

One option is to copy the relevant goals from the xml-maven-plugin and shoehorn the processing from maven-shared-io into the goal. I've been looking to do this myself with a view to raising requests against various plugins to use descriptor files and the LocatorStrategy approach to find the descriptors. Here's some processing that will modify the xml-maven-plugin to allow descriptors to be used. Note there is little validation of the files involved so it is a bit fragile as is, but it does work.

1)创建一个新的maven-plugin项目(比如说xml-ext-maven-plugin)具有以下依赖项:

1) Create a new maven-plugin project (say called xml-ext-maven-plugin) with the following dependencies:

<dependencies>
  <dependency>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>xml-maven-plugin</artifactId>
    <version>1.0-beta-2</version>
  </dependency>
  <dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.2-beta-2</version>
  </dependency>
</dependencies>

2)从xml-maven-plugin复制TransformMojo和AbstractXmlMojo .java文件(需要)父mojo从其javadoc继承属性。)

2) Copy the TransformMojo and the AbstractXmlMojo .java files from the xml-maven-plugin (you need the parent mojo to inherit the properties from its javadoc).

3)向TransformMojo添加描述符属性:

3) Add a descriptors property to the TransformMojo:

/**
 * A list of descriptor files to obtain the transformation sets from
 * 
 * @parameter
 */
private String[] descriptors;

4)修改execute()方法以读取transformationSets的描述符

4) modify the execute() method to read the descriptors for transformationSets

public void execute() throws MojoExecutionException, MojoFailureException {
    //insert at start of method to resolve transformationSets fronm descriptors
    if (descriptors != null && descriptors.length > 0) {
        transformationSets = readDescriptors(descriptors);
    }

    ...

5)实施 readDescriptors()允许您在类路径或项目内定位描述符(读取器处理主要从程序集插件的DefaultAssemblyReader中提取)。请注意,在此实现中几乎没有验证,正确的插件会检查是否设置了值等。

5) Implement readDescriptors() to allow you to locate descriptors on the classpath or within the project (the reader processing is largely lifted from the assembly-plugin's DefaultAssemblyReader). Note there is little validation in this implementation, a proper plugin would check if values are set etc.

private TransformationSet[] readDescriptors(String[] descriptors)
        throws MojoExecutionException {

    List descriptorSets = new ArrayList();
    // add all the existing transformationSets
    if (transformationSets != null && transformationSets.length != 0) {
        descriptorSets.addAll(Arrays.asList(transformationSets));
    }

    for (int i = 0; i < descriptors.length; i++) {
        getLog().info(
                "Reading transformation descriptor: " + descriptors[i]);

        Location location = getLocation(descriptors[i]);

        Reader reader = null;
        try {
            reader = new InputStreamReader(location.getInputStream(),
                    "UTF-8");

            Xpp3Dom dom = Xpp3DomBuilder.build(reader);

            descriptorSets.addAll(parseTransformationSets(dom));
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "Error reading transformation descriptor: "
                            + descriptors[i], e);
        } catch (XmlPullParserException e) {
            throw new MojoExecutionException(
                    "Error parsing transformation descriptor: "
                            + descriptors[i], e);
        } finally {
            IOUtil.close(reader);
        }
    }

    return (TransformationSet[]) descriptorSets
            .toArray(new TransformationSet[descriptorSets.size()]);
}

/**
 * Create transformationSets from the Xpp3Dom.
 * TODO use plexus utilities to resolve these elegantly?
 */
private List parseTransformationSets(Xpp3Dom dom) {
    // TODO validation of the input files!
    Xpp3Dom[] setDoms = dom.getChildren("transformationSet");

    List sets = new ArrayList();
    for (int i = 0; i < setDoms.length; i++) {
        TransformationSet set = new TransformationSet();
        set.setDir(new File(setDoms[i].getChild("dir").getValue()));
        set.setStylesheet(new File(setDoms[i].getChild("stylesheet")
                .getValue()));

        Xpp3Dom outDom = setDoms[i].getChild("outputDir");

        if (outDom != null) {
            set.setOutputDir(new File(outDom.getValue()));
        }

        sets.add(set);
    }
    return sets;
}

6)实施 getLocation()以使用各种将文件作为相对路径,url或类路径发现的策略。

6) Implement getLocation() to use various strategies to discover the file either as a relative path, url, or from the classpath.

private Location getLocation(String path) {
    List strategies = new ArrayList();
    strategies.add(new RelativeFileLocatorStrategy(getBasedir()));
    strategies.add(new ClasspathResourceLocatorStrategy());
    strategies.add(new FileLocatorStrategy());
    strategies.add(new URLLocatorStrategy());

    List refStrategies = new ArrayList();
    refStrategies.add(classpathStrategy);

    Locator locator = new Locator();

    locator.setStrategies(strategies);

    Location location = locator.resolve(path);
    return location;
}

7)覆盖 asAbsoluteFile()来解析文件使用定位器策略(允许我们在描述符项目中定义xsl文件)。

7) Override asAbsoluteFile() to resolve files using the locator strategy (allows us to define the xsl files in the descriptor project as well).

protected File asAbsoluteFile(File f) {
    String path = f.getPath();

    // ensure we're getting a path in the form that URL can handle
    if (path != null) {
        path = path.replaceAll("\\\\", "/");
    }
    Location location = getLocation(path);

    if (location == null) {
        //can't find the file, let the parent implementation have a try
        return super.asAbsoluteFile(f);
    }
    try {
        return location.getFile();
    } catch (IOException e) {
        throw new RuntimeException("unable to read file " + f.getPath(), e);
    }
}

8)将插件安装到存储库。

8) Install the plugin to your repository.

9)创建一个新的maven项目来托管您的transformationSets(比如称为xml-ext-test-descriptor)。该过程与共享描述符< a> of assembly-plugin,即创建一个项目,在src / main / resources下添加一些xml文件,然后安装项目。 xml文件采用标准transformationSets配置的形式。例如,在src / main / resources / transformations1.xml中放置一些转换:

9) Create a new maven project to host your transformationSets (say called xml-ext-test-descriptor). the process is the same as for the shared descriptors of the assembly-plugin, i.e. create a project, add some xml files under src/main/resources, and install the project. The xml files are of the form of the standard transformationSets configuration. For example put a couple of the transformations in src/main/resources/transformations1.xml:

<transformationSets>
  <transformationSet>
    <!--the config directory is in the root of the project -->
    <dir>config/xsltUpdates/input</dir>
    <!-- the stylesheet can be in the descriptor project-->
    <stylesheet>/stylesheets/update1-8-3.xsl</stylesheet>       
    <outputDir>config/xsltUpdates/update1-8-3</outputDir>
  </transformationSet>
  <transformationSet>
     <dir>config/xsltUpdates/update1-8-3</dir>
     <stylesheet>/stylesheets/update1-8-9.xsl</stylesheet>
     <outputDir>config/xsltUpdates/update1-8-9</outputDir>
  </transformationSet>
</transformationSets>

10)将xsl文件放入描述符项目中,例如: src / main / resources / stylesheets / update1-8-3.xsl

10) Put your xsl files in the descriptor project, e.g. src/main/resources/stylesheets/update1-8-3.xsl

11)在项目中配置新插件以引用描述符项目作为依赖项并引用xml文件作为描述符:

11) Configure the new plugin in your project to reference the descriptor project as a dependency and reference the xml file as a descriptor:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xml-maven-plugin</artifactId>
  <executions>
    <execution>
      <phase>compile</phase>
      <goals>
        <goal>transform</goal>
      </goals>
    </execution>
  </executions>
  <dependencies>
    <dependency>
      <groupId>name.seller.rich</groupId>
      <artifactId>xml-ext-test-descriptor</artifactId>
      <version>0.0.1</version>
    </dependency>
  </dependencies>
  <configuration>
   <descriptors>
     <!-- will be resolved from xml-ext-test-descriptor -->
     <descriptor>/transformationSet1.xml</descriptor>
   </descriptors>
 </plugin>

如果以上所有步骤都有效,则执行时自定义插件将解析transformationSet1.xml和xsl文件来自xml-ext-test-descriptor依赖关系并正常处理它们。

If all the above steps worked, when executed the custom plugin will resolve transformationSet1.xml and your xsl files from the xml-ext-test-descriptor dependency and process them as normal.

这篇关于如何外化maven构建文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆