Monday, October 01, 2012

Accessing Maven Profiles

I have just spent some time trying to figure out how to determine which profiles are active  during the build using Maven. This functionality would be useful if you needed to put your profile activation in JAR MANIFEST file if your project supported various versions of dependency files (for example different servers, portals or Ajax libraries ...) and in case that your version information did not include this.

Here is a snippet that will make you life easier using GMaven plugin:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.gmaven</groupId>
                <artifactId>gmaven-plugin</artifactId>
                <version>1.4</version>
                <executions>
                    <execution>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>execute</goal>
                        </goals>
                        <configuration>
                            <source>
                                project.properties.setProperty('activatedProfiles','')
                                if(project.parent!=null){
                                project.parent.activeProfiles.each() { item-> project.properties.setProperty('activatedProfiles',project.properties.activatedProfiles + "${item.id} ")}
                                }
                            </source>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifestEntries>
                            <Active-Profiles>${activatedProfiles}</Active-Profiles>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>    
</project>

If you know easier way, please let me know.