how to pass parameters to java files using pom.xml - java

I want to pass parameters from the pom.xml to the java files.
I tried to set a properties in the pom.
The java files didn't read them.

---- Here's the 2 minute introduction to filtering resource files ----
First you need to specify that you want your resource filtered, by adding a "filtering" element, containing the "true" value.
In this example, I reconfigured the default resource directory:
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.edwinbuck.examples</groupId>
<artifactId>template-value</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Template example</name>
<description>
A simple pom file that copies a value into a propertie file.
</description>
<licenses>
<license>
<name>The MIT License</name>
<url>http://www.opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<project.build.outputEncoding>UTF-8</project.build.outputEncoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.project.outputEncoding>UTF-8</project.project.outputEncoding>
<property.to.be.copied>some-value</property.to.be.copied>
</properties>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
This implies that the default resource directory exists, which (to match the example) should be at
${basedir}/src/main/resources
Inside that directory, there should be a resource (a file). For this example, the file's contents look like
maven.build.number=${project.version}
customValue=${property.to.be.copied}
And the file is named
${basedir}/src/main/resources/example.properties
Upon a mvn build this will create a copy of the file into
${basedir}/target/classes/example.properties
but the contents of the file under the target directory will be
maven.build.number=1.0-SNAPSHOT
customValue=some-value
I hope this example (tested on Maven 3.5.4) will provide you with enough of a template to make better use of the documentation.
Cheers!
---- Original posts follow ----
Maven strives to have reproducible builds. That means that if the build required input, you would have to provide exactly the same input to get a proper reproduction, each time.
Effectively this won't happen, as you might be unavailable, or might not type in the same item. So, I would look to the src/main/resources directory and create a properties file. Put the settings in there, and then rewrite your program to use settings from there.
When reading the properties file, there are a number of options. Look to the technique that loads the properties file from the ClassLoader, as it is the approach that has the best maintainability, and offers the most amount of flexibility in the placement of the properties file.
In the event you want to support more than one kind of build, and all the builds can be done without human input, you might create a maven profile for each build. That said, each profile will still be a reproducible build.
--- I see you've changed your wording, here's an update ---
Use a template, and the copy-resources target of the resources plugin. You can leverage it to replace items in the resources as they get moved into the target directory

Related

Maven UTF-8 encoding issue

When I run below code with two different project I get different outputs.
String myString = "Türkçe Karakter Testi : ğüşiöçĞÜİŞÇÖĞ";
String value = new String(myString.getBytes("UTF-8"));
System.out.println(value);
First project is non-maven java application created in Netbeans 8.2. And it gives me following result which i expect.
"Türkçe Karakter Testi : ğüşiöçĞÜİŞÇÖĞ"
And second project is maven java application project which is created in same way with following pom.xml file:
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>mavenproject1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>
This project gives me:
"Türkçe Karakter Testi : ğüşiöçÄ?ÜİÅ?ÇÖÄ?"
I checked both file with notepad++ and both of them are encoded with UTF-8
You're missing the encoding from your new String() constructor, so it's using the default encoding of your platform which isn't UTF-8 (looks like some variant of ISO-8859-1).
If you use the following code (which doesn't make much sense, but shows the default encoding botching things), you'll see that it's printed properly everywhere.
String myString = "Türkçe Karakter Testi : ğüşiöçĞÜİŞÇÖĞ";
String value = new String(myString.getBytes("UTF-8"), "UTF-8");
System.out.println(value);
What's the lesson here? Always specify the encoding to use when dealing with byte/character conversion! This includes such methods as String.getBytes(), new String() and new InputStreamReader().
This is just one of the many ways that character encoding can bite you in the behind. It may seem like a simple problem, but it catches unsuspecting developers all the time.
I also often faced with the same problems.
Configuring Maven Character Encoding
The problem
Run my code in IDE (idea/eclipse). All correct. Output had correct encoding and in the console and in output files.
Run my app after built Maven. When I try to run my App (jar) built with help maven mvn clean install
I got incorrect values in output related to incorrect encoding.
In the console and in output files which were generated in my app I saw incorrect and unexpected symbols
Warning in your console. This warning means that you have not set any character encoding for your project/environment.
Let's solve this problem. There are a couple of options you can consider.
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
Configuring Maven Character Encoding
1. Properties
A most popular and common way to set Maven Character Encoding is to use properties. These properties are supported by most plugins. These properties are easy to add. Just add them as a child element of the project element.
<?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">
[...]
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
[...]
</project>
2. Maven Resources Plugin
You can also specify Maven Character Encoding using the maven resources plugin.
The only drawback is that you have to include this plugin to your Maven pom.xml file.
JUST ADD THIS PLUGIN - It`s always helped me ))
<?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.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
[...]
</project>
3. Commandline
If you cannot alter the source code of a maven project, or you need to specify maven character encoding on a built server like Jenkins, Hudson, or Bamboo you can also add the encoding through the command line.
mvn -Dproject.build.sourceEncoding=UTF-8 -Dproject.reporting.outputEncoding=UTF-8 clean deploy
4. Maven Options
If you do a lot of small projects for personal gain you can also set this property globally in MAVEN_OPTS. The only drawback is that if you share your code base with another developer then the developer also has to add these MAVEN_OPTS. That’s why I do not recommend it.
set MAVEN_OPTS= -Dfile.encoding="UTF-8"
#See How to Configure Maven Character Encoding

How do I include maven environment variables in eclipse to war file

I have environment variables in my application.properties like this spring.mail.username=${username}
The ${username} is declare in eclipse environment variable. When I build maven package and install, then deploy it to tcServer. The TC Server does not know ${username}. Another word, the environment variables do not include in the war file during build.
How do I get the environment variable in eclipse to include in war file for deployment?
Using Maven filtering as described in alexbt's answer, is the right approach for including values defined elsewhere. His example touches on including an operating system environment variable. You can extend this to Maven properties also. For example,
<project ...>
<properties>
<spring.mailuser>bob#mycompany.com</spring.mailuser>
</properties>
...
<build>
...
</build>
</project>
defines a Maven properties whose value is retrieved by ${spring.mailuser} and can be used as part
of other Maven configurations or injected as content via Maven filtering. Given this, changing
applicable.properties as follows
spring.mail.username=${spring.mailuser}
will inject the value of the property at build time.
If you wish to have a build-time variable replaced, I would suggest you to use maven filtering:
Have an environment variable (not an eclipse one):
export username=user3184890
Then, in your pom.xml, activate maven filtering on resources (assuming your application.properties is in src/main/resources:
<build>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
...
Also, change your application.properties to this:
spring.mail.username=${env.username}
or
spring.mail.username=#env.username#

Maven with an explicit finalName won't work properly

1. Background
My maven project has a lot of modules and submodules with jars and wars and everything works. I also can deploy it on server without any problem.
I decided to follow this maven naming conversion, I am making some tests with project.name and project.build.finalName to have an appropriate name.
The pattern I defined to create project.name for the root artifact is company-${project.artifactId} and for the modules and sub-modules is ${project.parent.name}-${project.artifactId}:
company-any-artifact-any-module1
company-any-artifact-any-module2-any-submodule1
company-any-artifact-any-module2-any-submodule2
The pattern for project.build.finalName is ${project.name}-${project.version}:
company-any-artifact-any-module1-1.0.jar
company-any-artifact-any-module2-any-submodule1-2.0.jar
company-any-artifact-any-module2-any-submodule2-3.0.war
But instead of producing these files, maven gives me a StackOverflowError.
2. The example to reproduce the error
You can clone this example from github: https://github.com/pauloleitemoreira/company-any-artifact
In github, there is the master branch, that will reproduce this error. And there is only-modules branch, that is a working example that uses ${project.parent.name} to generate the jar finalName as I want.
Let's consider a maven project with one root pom artifact, one pom module and one submodule.
-any-artifact
|
|-any-module
|
|-any-submodule
2.1 any-artifact
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.company</groupId>
<artifactId>any-artifact</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>company-${project.artifactId}</name>
<modules>
<module>any-module</module>
</modules>
<!-- if remove finalName, maven will not throw StackOverflow error -->
<build>
<finalName>${project.name}-${project.version}</finalName>
</build>
</project>
2.2 any-module
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>any-artifact</artifactId>
<groupId>com.company</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.company.any-artifact</groupId>
<artifactId>any-module</artifactId>
<packaging>pom</packaging>
<name>${project.parent.name}-${project.artifactId}</name>
<modules>
<module>any-submodule</module>
</modules>
</project>
2.3 any-submodule
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>any-module</artifactId>
<groupId>com.company.any-artifact</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.company.any-artifact.any-module</groupId>
<artifactId>any-submodule</artifactId>
<name>${project.parent.name}-${project.artifactId}</name>
</project>
3. Problem
When try to mvn clean install, maven gives me a StackOverflowError:
Exception in thread "main" java.lang.StackOverflowError
at org.codehaus.plexus.util.StringUtils.isEmpty(StringUtils.java:177)
at org.codehaus.plexus.util.introspection.ReflectionValueExtractor.evaluate(ReflectionValueExtractor.java:194)
at org.codehaus.plexus.util.introspection.ReflectionValueExtractor.evaluate(ReflectionValueExtractor.java:163)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:266)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:143)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:174)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:143)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:429)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:143)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:174)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:143)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:429)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:143)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:174)
at org.apache.maven.plugin.PluginParameterExpressionEvaluator.evaluate(PluginParameterExpressionEvaluator.java:143)
It is important to know that the error occurs only when we are working with submodules. If we create a project with a root POM artifact and a jar module, the error don't occur.
4. The question
Why this error occurs only when we are using submodules?
Any suggestion to solve my problem? Should I forget it and set project.name and project.build.fileName manually for each project, following the pattern I want?
IMPORTANT UPDATED:
Some answers just say to use &{parent.name}, but it does not work. Please, it is a question with a bounty, consider test your solution with Maven version 3.3.9, before answering this question.
Maven version 3.3.9
Edit - Adding details to the question with the phase when the error occurs, things are working fine until the prepare-package phase, but the StackOverflow occurs at the package phase on maven lifecycle for the project.
The strict answer to your question is that ${project.parent.name} will not be resolved as part the model interpolation process. And in turn, you have a StackOverflowError, in a completely different place of the code, namely when... building the final JAR of your project.
Part 1: The Model built is wrong
Here's what happens. When you're launching a Maven command on a project, the first action it takes is creating the effective model of the project. This means reading your POM file, reasoning with activated profiles, applying inheritance, performing interpolation on properties... all of this to build the final Maven model for your project. This work is done by the Maven Model Builder component.
The process of building the model is quite complicated, with a lot of steps divided in possibly 2 phases, but the part we're interested in here in the model interpolation part. This is when Maven will replace in the model all tokens denoted by ${...} with a calculated value. It happens after profiles are injected, and inheritance is performed. At that point in time, the Maven project, as represented by a MavenProject object, doesn't exist yet, only its Model is being built. And it is only after you have a full model that you can start constructing the Maven project from it.
As such, when interpolation is done, it only reasons in terms of the information present in the POM file, and the only valid values are the ones mentioned in the model reference. (This replacement is performed by the StringSearchModelInterpolator class, if you want to look at the source code.) Quite notably, you will notice that the <parent> element in the model does not contain the name of the parent model. The class Model in Maven is actually generated with Modello from a source .mdo file, and that source only defines groupId, artifactId, version and relativePath (along with a custom id) for the <parent> element. This is also visible in the documentation.
The consequence of all that, is that after model interpolation is performed, the token ${project.parent.name} will not be replaced. And, further, the MavenProject constructed from it will have a name containing ${project.parent.name} unreplaced. You can see this in the logs, in your sample project, we have
[INFO] Reactor Build Order:
[INFO]
[INFO] company-any-artifact
[INFO] ${project.parent.name}-any-module
[INFO] ${project.parent.name}-any-submodule
Meaning that Maven consider the actual name of the project any-module to be ${project.parent.name}-any-module.
Part 2: The weirdness begins
We're now at a time when all of the projects in the reactor were correctly created and even compiled. Actually, everything should theoretically work just fine, but with only completely borked names for the projects themselves. But you have a strange case, where it fails at the creation of the JAR with the maven-jar-plugin. The build fails in your example with the following logs:
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) # any-submodule ---
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] company-any-artifact ............................... SUCCESS [ 0.171 s]
[INFO] ${project.parent.name}-any-module .................. SUCCESS [ 0.002 s]
[INFO] ${project.parent.name}-any-submodule ............... FAILURE [ 0.987 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
meaning that something went wrong well after the model was built. And the reason is that the plugin injects the name of the project as a parameter:
/**
* Name of the generated JAR.
*
* #parameter alias="jarName" expression="${jar.finalName}" default-value="${project.build.finalName}"
* #required
*/
private String finalName;
Notice project.build.finalName as the default value of the generated JAR name for the submodule. This injection, and the interpolation of the variables are done by another class called PluginParameterExpressionEvaluator.
So what happens in this:
The JAR plugin on the any-submodule injects the final name of the project, named ${project.parent.name}-any-submodule.
Thanks for inheritance from the parent projects, and the declaration of <finalName> in your top-most POM project, it inherits <finalName>${project.name}-${project.version}</finalName>.
Maven now tries to interpolate ${project.name} for any-submodule.
This resolves to ${project.parent.name}-any-submodule, due to Part 1.
Maven tries now to interpolate ${project.parent.name} for any-submodule. This works correctly: the MavenProject is built and getParent() will be called on the project instance, returning the concrete Maven parent project. As such, ${project.parent.name} will try to resolve the name of any-module, which is actually ${project.parent.name}-any-module.
Maven now tries to interpolate ${project.parent.name}-any-module, but still on the any-submodule project instance. For PluginParameterExpressionEvaluator, the root "project" on which to evaluate tokens hasn't changed.
Maven now tries to interpolate ${project.parent.name} on any-submodule, which, again, works correctly and returns ${project.parent.name}-any-module.
Maven now tries to interpolate ${project.parent.name} on any-submodule... which works and returns ${project.parent.name}-any-module so it tries to evaluate ${project.parent.name}...
And you can see the endless recursion happening here, which results in the StackOverflowError you have. Is this a bug in PluginParameterExpressionEvaluator? This is unclear: it reasons on model values that were not correctly replaced in the first place. In theory, it could handle the special case of evaluating ${project.parent} and create a new PluginParameterExpressionEvaluator working on this parent project, instead of always working on the current project. If you feel strongly about this, feel free to create a JIRA issue.
Part 3: Why it works without the sub module
With what has been said above, you could now deduce why it works in this case. Let's reason with what Maven needs to do to evaluate the final name, as has to be injected in the Maven Jar Plugin:
The JAR plugin on the any-module injects the final name of the project, named ${project.parent.name}-any-module.
Thanks for inheritance from the parent project, and the declaration of <finalName> in your top-most POM project, it inherits <finalName>${project.name}-${project.version}</finalName>.
Maven now tries to interpolate ${project.name} for any-module.
This resolves to ${project.parent.name}-any-module, same as before.
Maven tries now to interpolate ${project.parent.name} for any-module. Just like before, this works correctly: the MavenProject is built and getParent() will be called on the project instance, returning the concrete Maven parent project. As such, ${project.parent.name} will try to resolve the name of any-artifact, which is actually company-any-artifact.
Interpolation has succeeded and stops.
And you don't have any errors.
As I stated in my answer to Difference between project.parent.name and parent.name ans use of finalName in pom.xml
Let's first look at the basics:
as stated in POM Reference:
finalName: This is the name of the bundled project when it is finally built (sans the file extension, for example: my-project-1.0.jar). It defaults to ${artifactId}-${version}.
name: Projects tend to have conversational names, beyond the artifactId.
So these two have different uses.
name is purely informational and mainly used for generated documentation and in the build logs. It is not inherited nor used anywhere else. It is a human readable String and can thus contain any character, i.e. spaces or characters not allowed in filenames. So, this would be valid: <name>My Turbo Project on Speed!</name>. Which is clearly at least a questionable file name for an artifact.
as stated above, finalName is the name of the generated artifact. It is inherited, so it should usually rely on properties. The only two really useful options are the default ${artifactId}-${version} and the versionless ${artifactId}. Everything else leads to confusion (such as a project named foo creating an artifact bar.jar). Actually, My turbo Project! would be valid, since this is a valid filename, but in reality, filenames like that tend to be rather unusable (try adressing a filename containing ! from a bash, for example)
So, as to why the Stackoverflow happens:
name is not inherited
project.parent.name also is not evaluated during interpolation, since the name is one of the few properties which are completey invisible to the children
parent.name actually used to work in older Maven versions, but more due to a bug (also it is deprecated to access properties without the leading project).
a missing property is not interpolated, i.e. stays in the model as is
Therefore, in your effective pom for any-submodule, the value for finalName is (try it with mvn help:effective-pom) still: ${project.parent.name}-any-submodule
So far so bad. Now comes the reason for the StackOverflow
Maven has an addtional feature called late interpolation that evaluates values in plugin parameters when they are actually used. This allows a pluing to use properties that are not part of the model, but are generated by plugins earlier in the lifecycle (this allows, for instance plugins to contribute a git revision to the final name).
So what happens is this:
edit: made the actual reason for the error clearer (see comments):
The finalName for the jar plugin is evaluated:
#Parameter( defaultValue = "${project.build.finalName}", readonly = true )
The PluginParameterExpressionEvaluator kicks in and tries to evaluate the final name (${project.parent.name}-any-submodule, which contains a property expression ${project.parent.name}.
The evaluator asks the model, which in turn returns the name of the parent project, which is: ${project.parent.name}-any-module.
So the evaluator tries to resolve this, which return ${project.parent.name}-any-module (again), since a property is always resolved against the current project, the cycle begins again.
A StackOverflowError is thrown.
How to solve this
Sadly, you can't.
You need to explicitly specify name (as well as artifactId) for every project. There is no workaround.
Then, you could let finalName rely on it. I would however advise against it (see my answer to Difference between project.parent.name and parent.name ans use of finalName in pom.xml)
The problem in changing the final name that way is that the name of the locally build artifact and the one in the repository would differ, so locally your artifact is named any-artifact-any-module-any-submodule.jar, but the artifact name in your repository would be still any-submodule.jar
Suggestion
If you really need to differentiate that fine, change the artifactId instead: <artifactId>artifact-anymodule-anysubmodule</artifactId>.
Don't use dashes for the shortname to differentiate between levels of your structure.
hint: the path of the module can be still anymodule, is does not need to be the actual artifactId of the module!
While we are at it: use the name for what it was intended, to be human readable, so you might consider something more visually appealling (since this is the name that appears in the build log): <name>Artifact :: AnyModule :: AnySubModule</name>.
It is actually very easy to simply create the name entries automatically using a very short groovy script.
You could also write an enforce rule to enforce the naming of the artifactIds
This is issue with attribute inheritance.
Try to use ${parent.name} instead of ${project.parent.name}.
Look at: Project name declared in parent POM isn't expanded in a module filtered web.xml.
---UPDATE---
Benjamin Bentmann (maven committier) said: "In general though, expressions of the form ${project.parent.*} are a bad practice as they rely on a certain build state and do not generally work throughout the POM, giving rise to surprises".
https://issues.apache.org/jira/browse/MNG-5126?jql=text%20~%20%22parent%20name%22
Maybe you should consider is using ${project.parent.*} is a good way.
change pom.xml in company-any-artifact to below and it will work .
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.company</groupId>
<artifactId>any-artifact</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>${project.groupId}</name>
<modules>
<module>any-module</module>
</modules>
<!-- if remove finalName, maven will not throw StackOverflow error -->
<build>
<finalName>${project.groupId}-${project.version}</finalName>
</build>
</project>
change pom.xml in submodule to below
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>any-artifact</artifactId>
<groupId>com.company</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.company.any-artifact</groupId>
<artifactId>any-module</artifactId>
<packaging>pom</packaging>
<!-- <name>${project.parent.name}-${project.artifactId}</name> -->
<modules>
<module>any-submodule</module>
</modules>
<build>
<finalName>${project.parent.name}-${project.artifactId}</finalName>
</build>
</project>
change submodule pom.xml to below
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>any-module</artifactId>
<groupId>com.company.any-artifact</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.company.any-artifact.any-module</groupId>
<artifactId>any-submodule</artifactId>
<!-- <name>${project.parent.name}-${project.artifactId}-${project.version}</name> -->
<build>
<finalName>company-${project.parent.name}-${project.artifactId}-${project.version}</finalName>
</build>
</project>
then the output was : company-any-module-any-submodule-1.0-SNAPSHOT
Interesting! I started off cloning the repo and reproducing the error. I would appreciate any leads that can be taken from any of the steps mentioned below that helped me debug the problem -
Maven Life Cycle Phases
The phase where the issue occurred was the package phase of the lifecycle. Meaning mvn package reproduces the issue with your project.
Went through the stack trace lines in the error. Getting to know its the expression evaluation where it's failing -
#Override
public Object evaluate( String expr ) throws ExpressionEvaluationException {
return evaluate( expr, null ); // Line 143
}
It's also not the finalName attribute which was causing it. Since specifying the default value of the same
<finalName>${artifactId}-${version}</finalName>
works fine with the same project configs.
Then tried changing the packaging of the any-submodule as
<packaging>pom</packaging>
and the error went away. Meaning while packaging as jar , war etc the expression evaluation is different and results in an overflow.
Modifying the any-module or the any-submodule pom.xml content I can say with some confidence that it's the project.parent.name that is causing a recursion in evaluating the expression and causing the stack overflow(How? - is something I am still looking for..). Also, changing
<name>${project.parent.name}-${project.artifactId}</name>
to
<name>${parent.name}-${project.artifactId}</name>
works for me in the sense that I do not get an error but the jar generated is of type -
${parent.name}-any-module-any-submodule-1.0-SNAPSHOT.jar and
${parent.name}-any-submodule-1.0-SNAPSHOT respectively with the change.
Looking for the solution according to the requirement, I am seeking a tail to the recursion that you are using.
Note - Still working on finding an appropriate solution to this problem.

Getting property from pom.xml within java

I have a maven project, and in the pom.xml I set properties as such:
<project>
<modelVersion>4.0.0</modelVersion>
<artifactId>myArtifact</artifactId>
<name>SomeProject</name>
<packaging>jar</packaging>
<properties>
<some-system-property>1.9.9</some-system-property>
</properties>
<...>
</project>
I want to pull the some-system-property value from within the java code, similar to
String someSystemPropery = System.getProperty("some-system-property");
But, this always returns null. Looking over StackOverflow, most of the answers seem to revolve around enhanced maven plugins which modify the code - something that's a nonstarter in my environment.
Is there a way to just get a property value from a pom.xml within the codebase? Alternatively, can one get the version of a dependency as described in the pom.xml (the 1.9.9 value below):
<dependencies>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.9</version>
</dependency>
</dependencies>
from code? Either one would solve my needs
Those are Maven properties that apply during the build, not runtime system properties. One typical approach is to use Maven resource filtering to write the value into a properties file in the target directory.
Maven properties and not system properties.
Generally you should set the system property for a maven plugin that is triggering the execution:
surefire for unit tests,
exec for execution,
jetty or similar for starting a web container
There is also properties maven plugin than can set properties:
http://mojo.codehaus.org/properties-maven-plugin/set-system-properties-mojo.html
Property values are accessible anywhere within a POM by using the notation ${X}, where X is the property, not outside. All properties accessible via java.lang.System.getProperties() are available as POM properties, such as ${java.home}, but not the other way around. So for your java code, it will need to scan the pom.xml as a xml parsing use case, but not sure why you want to do it.

Can I move maven2 "target" folder to another device?

I would really like to make maven write the "target" folder to a different device (ramdisk), which I would normally consider to be a different path. Is there any maven2-compliant way to do this ?
I am trying to solve this problem on windows, and a maven-compliant strategy would be preferred.
If you happen to have all of your projects extending a corporate parent pom, then you could try adding Yet Another Layer of Indirection as follows:
Corporate POM:
<build>
<directory>${my.build.directory}</directory>
</build>
<properties>
<!-- sensible default -->
<my.build.directory>target</my.build.directory>
</properties>
In your settings.xml:
<properties>
<!-- Personal overridden value, perhaps profile-specific -->
<my.build.directory>/mnt/other/device/${project.groupId}-${project.artifactId}/target</my.build.directory>
</properties>
If the local POM definition takes precedence over the settings.xml definition, then you could try omitting the default value at the cost of having every Maven instance in your control (developers, build machines, etc) specify ${my.build.directory} in its settings.xml.
Actually, Maven is not as constrained as everybody thinks, all the POMs are extended of one Super POM in which is defined the name of the target folder
<build>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<finalName>${artifactId}-${version}</finalName>
<testOutputDirectory>target/test-classes</testOutputDirectory>
.
.
.
</build>
Of course you can overwrite with any value you want, so just go ahead and change the <directory /> element (and other related elements) in your POM
just in case if you want to fix this for your own Maven3 and not touch anything in the project, locate file:
$MAVEN_HOME/lib/maven-model-builder-3.X.Y.jar
and update super-pom inside
org/apache/maven/model/pom-4.0.0.xml
changing line
<directory>${project.basedir}/target</directory>
in
<directory>/tmp/maven2/${project.groupId}-${project.artifactId}/target</directory>
so next time when you will build any maven project - it will put all classes under /tmp/

Categories