Robert3452
Robert3452

Reputation: 1476

Setting maven properties depending on the presence of other properties

I have a maven property question I can't find referred to in the Docs. From the command line I will input the property "from.command". This property will always be present.

mvn deploy -Dfrom.command=COMMANDVALUE

Inside the pom.xml I will specify another property:

  <properties>
    <from.pom>POMVALUE</from.pom>
  </properties>

This property will some times be there and other times be missing.

I want to have a third property named used.value

I want used.value to be set to the value of "from.pom" if that property is present otherwise it should be set to the value of "from.command"

This need arrises because I need to run maven builds from another script and I don't want the script to have to inspect all pom files.

Is this possible?

Upvotes: 2

Views: 3571

Answers (1)

Tunaki
Tunaki

Reputation: 137064

You could use the build-helper-maven-plugin:bsh-property mojo.

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <version>1.10</version>
  <executions>
    <execution>
      <id>bsh-property</id>
      <goals>
        <goal>bsh-property</goal>
      </goals>
      <configuration>
        <properties>
          <property>used.value</property>
        </properties>
        <source>
          used.value = project.getProperties().getProperty("from.pom", session.getUserProperties().getProperty("from.command"));
        </source>
      </configuration>
    </execution>
  </executions>
</plugin>

This goal enables to write BeanShell scripts. It automatically defines the variable project as the actual Maven project and session as the executing Maven session.

The script above gets the property "from.pom" from the Maven project's properties, and defaults to the "from.command" property set on the command line. It sets it to the used.value variable, which is then exported as a Maven property by the plugin after execution of the script. Command line properties are retrieved from the Maven session with getUserProperties():

The user properties have been configured directly by the user on his discretion, e.g. via the -Dkey=value parameter on the command line.

This goal automatically binds to the validate phase, which is the first phase that is run in the default lifecycle, so you will be able to use ${used.value} as a property inside the rest of the build.

Upvotes: 6

Related Questions