2

I have a java enum that is used in my web application. I also have a lot of javascript code that refers to the values of the enum. It would be ideal If I could generate a javascript file from the enum as part of the maven build process. Does anyone know of a project that solves this problem or of an elegant way to tackle it?

2 Answers 2

3

It turns out that there is a great way to do it using a groovy maven plugin as a "prepare-package" phase. This is the code : In your pom.xml add this entry :

<plugin>
                <groupId>org.codehaus.groovy.maven</groupId>
                <artifactId>gmaven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>script-prepare-package1</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>execute</goal>
                        </goals>
                        <configuration>
                            <source>${basedir}/src/main/groovy/GenerateJavaScriptEnum.groovy</source>
                        </configuration>
                    </execution>

                </executions>
            </plugin>

This is how the groovy script, GenerateJavaScriptEnum.groovy, looks like :

    def fields = []


com.foo.bar.YourEnum.values().each() { f->
    fields << "${f.name()} : \"${f.getId()}\""
}

if (fields) {
    log.info("Generating Javascript for com.foo.bar.YourEnum")

    [
            new File("${project.build.directory}/${project.build.finalName}/js"),
            new File("${project.basedir}/src/main/webapp/js")
    ].each() { baseOutputDir->
        if (!baseOutputDir.exists()) {
            baseOutputDir.mkdirs()
            log.info("Created output dir ${baseOutputDir}")
        }

        def outfile = new File(baseOutputDir, "YourEnum.js")

        log.info("Generating ${outfile}")

        def writer = outfile.newWriter("UTF-8")
        writer << "// FILE IS GENERATED FROM com.foo.bar.YourEnum.java.\n"
        writer << "// DO NOT EDIT IT.  CHANGES WILL BE OVERWRITTEN BY THE BUILD.\n"
        writer << "YourEnum = {\n"
        writer << fields.join(",\n")
        writer << "\n}"
        writer.close()
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

I had the same problem and ended up creating a custom tag that would allow me to iterate over the enum in my jsp,

public static Enum<?>[] getValues(String klass) {
    try {
        Method m = Class.forName(klass).getMethod("values", (Class<?>[]) null);
        Object obj = m.invoke(null, (Object[]) null);
        return (Enum<?>[]) obj;
    } catch (Exception ex) {
        return null;
    }
}

Then in my jsp I just do,

var MyEnum = [
<c:forEach var="type" items="${foocustomtags:enumiter('com.foo.MyEnum')}">
  '${type.value}': '${type.text}',
</c:forEach>
];

1 Comment

This is pretty useful so upvoted it, but I would still love to have some code generation so that I would be able to remove all the magic strings from the javascript code. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.