如何从Maven中的属性文件生成枚举? [英] How to generate enum from properties file in Maven?

查看:156
本文介绍了如何从Maven中的属性文件生成枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原来的标题是
如何使用ant生成属性文件中的枚举?



我想迭代所有属性并生成枚举类,有每个财产。



我正在考虑编写自定义任务,但我想我需要把它放在额外的jar中:|



im使用maven,我想在生成源阶段执行。

解决方案

虽然我有点同意 Peter Tilemans ,我也是受到这个问题的诱惑,我使用groovy和 GMaven-Plugin 编辑:关于GMaven的好处是,您可以直接访问maven对象模型,而不必首先创建插件,并且仍然具有groovy的完整编程能力。



我在这样的情况下做的是创建一个名为src / main / groovy的源文件夹,这不是实际构建过程的一部分(因此不会对jar / war等造成影响)。在这里我可以放入groovy源文件,从而允许eclipse将它们用作groovy源文件夹进行自动完成,而无需更改构建。



所以在这个文件夹中我有三个文件: EnumGenerator.groovy,enumTemplate.txt和enum.properties(为了简单起见,我做了这个,你可能会从别的地方获取属性文件)



这里是: / p>

EnumGenerator.groovy

  import java .util.Arrays; 
import java.util.HashMap;
import java.util.TreeMap;
import java.io.File;
import java.util.Properties;

class EnumGenerator {

public EnumGenerator(
File targetDir,
文件propfile,
文件templateFile,
String pkgName,
String clsName
){
def properties = new Properties();
properties.load(propfile.newInputStream());
def bodyText = generateBody(new TreeMap(properties));
def enumCode = templateFile.getText();
def templateMap = [body:bodyText,packageName:pkgName,className:clsName];
templateMap.each {key,value - >
enumCode = enumCode.replace(\ $ {$ key},value)}
writeToFile(enumCode,targetDir,pkgName,clsName)
}

void writeToFile(code,dir,pkg,cls){
def parentDir = new File(dir,pkg.replace('。','/'))
parentDir.mkdirs();
def enumFile = new File(parentDir,cls +'.java')
enumFile.write(code)
System.out.println(写入文件$ enumFile成功)
}

String generateBody(values){

//创建构造函数调用PROPERTY_KEY(value)
// from property.key = value
def body =;
values.eachWithIndex {
key,value,index - >
body + =

(index> 0?,\\\
\t:\t)
+ toConstantCase(key)+' '+ value +')'

}
body + =;;
返回体;

}

String toConstantCase(value){
//将camelCase和dot.notation分配给CAMEL_CASE和DOT_NOTATION
返回Arrays.asList(
value.split((?:(?= \\p {Upper})| \\。))
).join('_')toUpperCase();
}

}

enumTemplate.txt

  package $ {packageName}; 

public enum $ {className} {

$ {body}

private $ {className}(String value){
this .value = value;
}

私有字符串值;

public String getValue(){
return this.value;
}

}

enum.properties

  simple = value 
not.so.simple = secondvalue
propertyWithCamelCase = thirdvalue

这是pom配置:

 < plugin> 
< groupId> org.codehaus.groovy.maven< / groupId>
< artifactId> gmaven-plugin< / artifactId>
< version> 1.0< / version>
<执行>
< execution>
< id> create-enum< / id>
< phase> generate-sources< / phase>
< goals>
< goal> execute< / goal>
< / goals>
< configuration>
< scriptpath>
< element> $ {pom.basedir} / src / main / groovy< / element>
< / scriptpath>
< source>
import java.io.File
import EnumGenerator

文件groovyDir =新文件(pom.basedir,
src / main / groovy)
新的EnumGenerator(
new File(pom.build.directory,
generated-sources / enums),
new File(groovyDir,
enum.properties),
new File(groovyDir,
enumTemplate.txt),
com.mycompany.enums,
ServiceProperty
);

< / source>
< / configuration>
< / execution>
< / executions>
< / plugin>

结果如下:

  package com.mycompany.enums; 

public enum ServiceProperty {

NOT_SO_SIMPLE(secondvalue),
PROPERTY_WITH_CAMEL_CASE(thirdvalue),
SIMPLE(value);

private ServiceProperty(String value){
this.value = value;
}

私有字符串值;

public String getValue(){
return this.value;
}

}

使用模板,您可以自定义该枚举可以满足您的需求。因为gmaven嵌入在maven中,所以您不必安装任何内容或更改构建配置。



唯一要记住的是,您需要使用添加生成的源文件夹到构建。


The original title was "How to generate enum from properties file using ant?"

I want to iterate over all properties and generate enum class that have every property.

Im thinking about writing custom task, but I think i would need to put it in extra jar :|

im using maven and i want to do it in generate-sources phase.

解决方案

Although I somewhat agree with Peter Tilemans, I was also tempted by this problem and I hacked up a solution using groovy and the GMaven-Plugin. EDIT: The great thing about GMaven is that you can access the maven object model directly without creating a plugin first and still have groovy's full programming power.

What I do in cases like this is to create a source folder called src/main/groovy that is not part of the actual build process (and hence will not contribute to the jar / war etc). There I can put groovy source files, thus allowing eclipse to use them as groovy source folders for autocompletion etc without changing the build.

So in this folder I have three files: EnumGenerator.groovy, enumTemplate.txt and enum.properties (I did this for simplicity's sake, you will probably get the properties file from somewhere else)

Here they are:

EnumGenerator.groovy

import java.util.Arrays;
import java.util.HashMap;
import java.util.TreeMap;
import java.io.File;
import java.util.Properties;

class EnumGenerator{

    public EnumGenerator(
        File targetDir, 
        File propfile,
        File templateFile,
        String pkgName,
        String clsName 
    ) {
        def properties = new Properties();
        properties.load(propfile.newInputStream());
        def bodyText = generateBody( new TreeMap( properties) );
        def enumCode = templateFile.getText();
        def templateMap = [ body:bodyText, packageName:pkgName, className: clsName  ];
        templateMap.each{ key, value -> 
                                enumCode = enumCode.replace( "\${$key}", value ) } 
        writeToFile( enumCode, targetDir, pkgName, clsName )
    }

    void writeToFile( code, dir, pkg, cls ) {
        def parentDir = new File( dir, pkg.replace('.','/') )
        parentDir.mkdirs();
        def enumFile = new File ( parentDir, cls + '.java' )
        enumFile.write(code)
        System.out.println( "Wrote file $enumFile successfully" )
    }

    String generateBody( values ) {

        // create constructor call PROPERTY_KEY("value")
        // from property.key=value
        def body = "";
        values.eachWithIndex{
            key, value, index ->
                body += 
                ( 
                    (index > 0 ? ",\n\t" : "\t")
                    + toConstantCase(key) + '("' + value + '")'
                )   
        }
        body += ";";
        return body;

    }

    String toConstantCase( value ) {
        // split camelCase and dot.notation to CAMEL_CASE and DOT_NOTATION
        return Arrays.asList( 
            value.split( "(?:(?=\\p{Upper})|\\.)" ) 
        ).join('_').toUpperCase();
    }

}

enumTemplate.txt

package ${packageName};

public enum ${className} {

${body}

    private ${className}(String value){
        this.value = value;
    }

    private String value;

    public String getValue(){
        return this.value;
    }

}

enum.properties

simple=value
not.so.simple=secondvalue
propertyWithCamelCase=thirdvalue

Here's the pom configuration:

<plugin>
    <groupId>org.codehaus.groovy.maven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <version>1.0</version>
    <executions>
        <execution>
            <id>create-enum</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <scriptpath>
                    <element>${pom.basedir}/src/main/groovy</element>
                </scriptpath>
                <source>
                    import java.io.File
                    import EnumGenerator

                    File groovyDir = new File( pom.basedir,
                      "src/main/groovy")
                    new EnumGenerator(
                        new File( pom.build.directory,
                          "generated-sources/enums"),
                        new File( groovyDir,
                          "enum.properties"),
                        new File( groovyDir,
                          "enumTemplate.txt"),
                        "com.mycompany.enums",
                        "ServiceProperty" 
                    );

                </source>
            </configuration>
        </execution>
    </executions>
</plugin>

And here's the result:

package com.mycompany.enums;

public enum ServiceProperty {

    NOT_SO_SIMPLE("secondvalue"),
    PROPERTY_WITH_CAMEL_CASE("thirdvalue"),
    SIMPLE("value");

    private ServiceProperty(String value){
        this.value = value;
    }

    private String value;

    public String getValue(){
        return this.value;
    }

}

using the template, you can customize the enum to suit your needs. and since gmaven embeds groovy in maven, you don't have to install anything or change your build configuration.

The only thing to remember is that you'll need to use the buildhelper plugin to add the generated source folder to the build.

这篇关于如何从Maven中的属性文件生成枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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