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.

2 comments:

  1. Hello Branislav,

    Many thanks to your post since I was looking exactly this.
    Although I should point one important thing: project.parent.activeProfiles array will contain only profiles existed in parent pom.

    So if you activate some profile which is not in the parent pom, it won't be stored in project.parent.activeProfiles array. But probably will be applied in some other child module.

    Best regards,
    Denis Kostovarov.

    ReplyDelete
  2. Thanks for the comment and I am glad that it helped you.

    Regards

    ReplyDelete