Search code examples
javascriptjavamavenbuild

generate javascript from java class as a maven build step


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?


Solution

  • 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()
        }
    }