I have a multimodule maven project, as follows:
module: project-assembly;
module: project-implementation;
module: project-application;
module: project-web;
in project-assembly/src/main/assembly/config
i have important configuration files for my project, and i need them to be copied during build process into project-web module into WEB-INF folder.
More important, this has to be done with specific profile.
For example, having a "x" profile, this is the one who needs this files in order to package successfully the project.
is there a way to achieve this? Thanks
You can use the maven-antrun-plugin to copy files between arbitrary folders (ant copy). But I would strongly advise against copying between modules. It is confusing and even more: The build order or the subset of modules that are built are subject to change (depending on the dependencies and also the command line parameters). For this copying, you need to make sure that the build happens in a defined order.
Think about sharing the configuration in another way.
you can use maven resource plugin-
<properties>
<othermodule-dir>...</othermodule-dir>
</properties>
<build>
<resources>
<resource>
<!-- package thumbnail -->
<directory>${sourceDir}</directory>
<targetPath>${othermodule-dir}</targetPath>
<filtering>true</filtering>
</resource>
</resources>
.
.
</build>
I'd like to use values from a properties file (or some other filesystem resource) in my weblogic.xml. For example, I have this section:
<session-descriptor>
<cookie-name>JSESSIONID</cookie-name>
<cookie-domain>${my.domain}</cookie-domain>
</session-descriptor>
I then have a properties file specifying the value:
my.domain=qa.mydomain.com
on the file system specifying the domain.
Is this possible? Many other configuration mechanisms allow for this. The motivation is that the same code could be deployed in multiple environments with multiple domains and weblogic could simply take the appropriate domain from the file without any operator intervention.
Running weblogic 12c here.
Thanks!
This can be simply achieved using maven's resource plugin, assuming you already on mvn build.
You just need to add below configuration under <build> section
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
You can add below property in your main pom in respective profiles:
<my.domain>desiredValue</my.domain>
In my opinion what you need is to use Weblogic's Deployment Plan feature.
I'm not so familar with it (never used it in productive environments) but with a deployment plan you should be able to change values in web.xml/weblogic.xml during deployment time.
Docs/Example:
Oracle Help Center - Creating and Using a Deployment Plan
Oracle Docs - Save Deployment Plan
Example from middlewaremagic.com
I have a maven project with different profiles set in pom.xml with different values. But I don't know how to access those values set in profile via java code.
For example-
My pom.xml:
<profile>
<id>scaler</id>
<properties>
<user>xxxxxxx</user>
<secret>yyyyyyyy</secret>
<proxyHost>172.19.17.13</proxyHost>
<proxyPort>9444</proxyPort>
<environment>SCALER</environment>
</properties>
</profile>
Java code-
String serviceurl = "http://"<proxyhost>":<proxyPort>/";
In the above java code, i want to use proxy host as 172.19.17.13 & port as 9444 as defined in pom.xml but how to access those values from pom??
I will appreciate your help
You should use the maven filtering feature.
http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
Just add a property file in src/main/resources with some placeholders:
key=${myvalue}
then myvalue should be defined as a property in your pom.xml
Be sure to activate the filter on your resources:
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
I'm not sure it depends on maven profile. You can try to use properties-maven-plugin (or other solution) like it described here. Just to write your properties into file and then use it in java code.
Let's assume I have a Java project called com.example:awesome-project, which has a dependency called com.external:awesome-library.
If this awesome-library has resources like configuration.xml, how do I filter this resource so that Maven property placeholders are replaced properly before I use it in the project's code?
Things like <tag name="${groupId}:${artifact}"> need to be changed to <tag name="com.example:awesome-project">, for instance.
Assumptions:
The awesome-library is external to this project, and is not built by
me.
I have no knowledge about the variable placeholders used in the
.xml files. All I know is that they are defined somehow by Maven.
Let's take project meta-data, for example ${artifact}, as an example.
Use dependency:unpack, which will extract resources, by default to ${project.build.directory}/dependency (which you can change if you want).
Then, either use either:
resources:copy-resource and define your filtering in that plugin's execution and also configure its resources configuration to point to ${project.build.directory}/dependency
it might be simpler to just put a resources element in your POM's build section and point it to ${project.build.directory}/dependency with appropriate filtering. Though if you want the standard src/main/resources as well you will need to put it there also.
You can use this solution:
Create parent (builder) project, and place in it constant which will be replaced in resource file:
<properties>
<some.constant>123</some.constant>
</properties>
Define both projects as modules in parent project:
<modules>
<module>../awesome-project</module>
<module>../awesome-library</module>
</modules>
In my-configuration.xml place constant reference as
${some.constant}
In awesome-library.pom config filter processor (for example, suppose that my-configuration.xml is placed in src/main/resources/META-INF:
<build>
<resources>
<resource>
<directory>src/main/resources/META-INF</directory>
<targetPath>META-INF</targetPath>
<filtering>true</filtering>
<includes>
<include>**/my-configuration.xml</include>
</includes>
</resource>
Run maven clean install in parent project.
What is the simplest way to retrieve version number from maven's pom.xml in code, i.e., programatically?
Assuming you're using Java, you can:
Create a .properties file in (most commonly) your src/main/resources directory (but in step 4 you could tell it to look elsewhere).
Set the value of some property in your .properties file using the standard Maven property for project version:
foo.bar=${project.version}
In your Java code, load the value from the properties file as a resource from the classpath (google for copious examples of how to do this, but here's an example for starters).
In Maven, enable resource filtering. This will cause Maven to copy that file into your output classes and translate the resource during that copy, interpreting the property. You can find some info here but you mostly just do this in your pom:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
You can also get to other standard properties like project.name, project.description, or even arbitrary properties you put in your pom <properties>, etc. Resource filtering, combined with Maven profiles, can give you variable build behavior at build time. When you specify a profile at runtime with -PmyProfile, that can enable properties that then can show up in your build.
The accepted answer may be the best and most stable way to get a version number into an application statically, but does not actually answer the original question: How to retrieve the artifact's version number from pom.xml? Thus, I want to offer an alternative showing how to do it dynamically during runtime:
You can use Maven itself. To be more exact, you can use a Maven library.
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model</artifactId>
<version>3.3.9</version>
</dependency>
And then do something like this in Java:
package de.scrum_master.app;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.FileReader;
import java.io.IOException;
public class Application {
public static void main(String[] args) throws IOException, XmlPullParserException {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(new FileReader("pom.xml"));
System.out.println(model.getId());
System.out.println(model.getGroupId());
System.out.println(model.getArtifactId());
System.out.println(model.getVersion());
}
}
The console log is as follows:
de.scrum-master.stackoverflow:my-artifact:jar:1.0-SNAPSHOT
de.scrum-master.stackoverflow
my-artifact
1.0-SNAPSHOT
Update 2017-10-31: In order to answer Simon Sobisch's follow-up question I modified the example like this:
package de.scrum_master.app;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Application {
public static void main(String[] args) throws IOException, XmlPullParserException {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model;
if ((new File("pom.xml")).exists())
model = reader.read(new FileReader("pom.xml"));
else
model = reader.read(
new InputStreamReader(
Application.class.getResourceAsStream(
"/META-INF/maven/de.scrum-master.stackoverflow/aspectj-introduce-method/pom.xml"
)
)
);
System.out.println(model.getId());
System.out.println(model.getGroupId());
System.out.println(model.getArtifactId());
System.out.println(model.getVersion());
}
}
Packaged artifacts contain a META-INF/maven/${groupId}/${artifactId}/pom.properties file which content looks like:
#Generated by Maven
#Sun Feb 21 23:38:24 GMT 2010
version=2.5
groupId=commons-lang
artifactId=commons-lang
Many applications use this file to read the application/jar version at runtime, there is zero setup required.
The only problem with the above approach is that this file is (currently) generated during the package phase and will thus not be present during tests, etc (there is a Jira issue to change this, see MJAR-76). If this is an issue for you, then the approach described by Alex is the way to go.
There is also the method described in Easy way to display your apps version number using Maven:
Add this to pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>test.App</mainClass>
<addDefaultImplementationEntries>
true
</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
Then use this:
App.class.getPackage().getImplementationVersion()
I have found this method to be simpler.
If you use mvn packaging such as jar or war, use:
getClass().getPackage().getImplementationVersion()
It reads a property "Implementation-Version" of the generated META-INF/MANIFEST.MF (that is set to the pom.xml's version) in the archive.
To complement what #kieste has posted, which I think is the best way to have Maven build informations available in your code if you're using Spring-boot: the documentation at http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready-application-info is very useful.
You just need to activate actuators, and add the properties you need in your application.properties or application.yml
Automatic property expansion using Maven
You can automatically expand info properties from the Maven project using resource filtering. If you use the spring-boot-starter-parent you can then refer to your Maven ‘project properties’ via #..# placeholders, e.g.
project.artifactId=myproject
project.name=Demo
project.version=X.X.X.X
project.description=Demo project for info endpoint
info.build.artifact=#project.artifactId#
info.build.name=#project.name#
info.build.description=#project.description#
info.build.version=#project.version#
When using spring boot, this link might be useful: https://docs.spring.io/spring-boot/docs/2.3.x/reference/html/howto.html#howto-properties-and-configuration
With spring-boot-starter-parent you just need to add the following to your application config file:
# get values from pom.xml
pom.version=#project.version#
After that the value is available like this:
#Value("${pom.version}")
private String pomVersion;
Sometimes the Maven command line is sufficient when scripting something related to the project version, e.g. for artifact retrieval via URL from a repository:
mvn help:evaluate -Dexpression=project.version -q -DforceStdout
Usage example:
VERSION=$( mvn help:evaluate -Dexpression=project.version -q -DforceStdout )
ARTIFACT_ID=$( mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout )
GROUP_ID_URL=$( mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout | sed -e 's#\.#/#g' )
curl -f -S -O http://REPO-URL/mvn-repos/${GROUP_ID_URL}/${ARTIFACT_ID}/${VERSION}/${ARTIFACT_ID}-${VERSION}.jar
Use this Library for the ease of a simple solution. Add to the manifest whatever you need and then query by string.
System.out.println("JAR was created by " + Manifests.read("Created-By"));
http://manifests.jcabi.com/index.html
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
Get Version using this.getClass().getPackage().getImplementationVersion()
PS Don't forget to add:
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
Step 1: If you are using Spring Boot, your pom.xml should already contain spring-boot-maven-plugin. You just need to add the following configuration.
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
It instructs the plugin to execute also build-info goal, which is not run by default. This generates build meta-data about your application, which includes artifact version, build time and more.
Step2: Accessing Build Properties with buildProperties bean. In our case we create a restResource to access to this build info in our webapp
#RestController
#RequestMapping("/api")
public class BuildInfoResource {
#Autowired
private BuildProperties buildProperties;
#GetMapping("/build-info")
public ResponseEntity<Map<String, Object>> getBuildInfo() {
Map<String, String> buildInfo = new HashMap();
buildInfo.put("appName", buildProperties.getName());
buildInfo.put("appArtifactId", buildProperties.getArtifact());
buildInfo.put("appVersion", buildProperties.getVersion());
buildInfo.put("appBuildDateTime", buildProperties.getTime());
return ResponseEntity.ok().body(buldInfo);
}
}
I hope this will help
I had the same problem in my daytime job. Even though many of the answers will help to find the version for a specific artifact, we needed to get the version for modules/jars that are not a direct dependency of the application. The classpath is assembled from multiple modules when the application starts, the main application module has no knowledge of how many jars are added later.
That's why I came up with a different solution, which may be a little more elegant than having to read XML or properties from jar files.
The idea
use a Java service loader approach to be able to add as many components/artifacts later, which can contribute their own versions at runtime. Create a very lightweight library with just a few lines of code to read, find, filter and sort all of the artifact versions on the classpath.
Create a maven source code generator plugin that generates the service implementation for each of the modules at compile time, package a very simple service in each of the jars.
The solution
Part one of the solution is the artifact-version-service library, which can be found on github and MavenCentral now. It covers the service definition and a few ways to get the artifact versions at runtime.
Part two is the artifact-version-maven-plugin, which can also be found on github and MavenCentral. It is used to have a hassle-free generator implementing the service definition for each of the artifacts.
Examples
Fetching all modules with coordinates
No more reading jar manifests, just a simple method call:
// iterate list of artifact dependencies
for (Artifact artifact : ArtifactVersionCollector.collectArtifacts()) {
// print simple artifact string example
System.out.println("artifact = " + artifact);
}
A sorted set of artifacts is returned. To modify the sorting order, provide a custom comparator:
new ArtifactVersionCollector(Comparator.comparing(Artifact::getVersion)).collect();
This way the list of artifacts is returned sorted by version numbers.
Find a specific artifact
ArtifactVersionCollector.findArtifact("de.westemeyer", "artifact-version-service");
Fetches the version details for a specific artifact.
Find artifacts with matching groupId(s)
Find all artifacts with groupId de.westemeyer (exact match):
ArtifactVersionCollector.findArtifactsByGroupId("de.westemeyer", true);
Find all artifacts where groupId starts with de.westemeyer:
ArtifactVersionCollector.findArtifactsByGroupId("de.westemeyer", false);
Sort result by version number:
new ArtifactVersionCollector(Comparator.comparing(Artifact::getVersion)).artifactsByGroupId("de.", false);
Implement custom actions on list of artifacts
By supplying a lambda, the very first example could be implemented like this:
ArtifactVersionCollector.iterateArtifacts(a -> {
System.out.println(a);
return false;
});
Installation
Add these two tags to all pom.xml files, or maybe to a company master pom somewhere:
<build>
<plugins>
<plugin>
<groupId>de.westemeyer</groupId>
<artifactId>artifact-version-maven-plugin</artifactId>
<version>1.1.0</version>
<executions>
<execution>
<goals>
<goal>generate-service</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>de.westemeyer</groupId>
<artifactId>artifact-version-service</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
Feedback
It would be great if maybe some people could give the solution a try. Getting feedback about whether you think the solution fits your needs would be even better. So please don't hesitate to add a new issue on any of the github projects if you have any suggestions, feature requests, problems, whatsoever.
Licence
All of the source code is open source, free to use even for commercial products (MIT licence).
It's very easy and no configuration is needed if you use Spring with Maven.
According to the “Automatic Property Expansion Using Maven” official documentation you can automatically expand properties from the Maven project by using resource filtering. If you use the spring-boot-starter-parent, you can then refer to your Maven ‘project properties’ with #..# placeholders, as shown in the following example:
project.version=#project.version#
project.artifactId=#project.artifactId#
And you can retrieve it with #Value annotation in any class:
#Value("${project.artifactId}#${project.version}")
private String RELEASE;
I hope this helps!
With reference to ketankk's answer:
Unfortunately, adding this messed with how my application dealt with resources:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
But using this inside maven-assemble-plugin's < manifest > tag did the trick:
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
So I was able to get version using
String version = getClass().getPackage().getImplementationVersion();
Preface: Because I remember this often referred-to question after having answered it a few years ago, showing a dynamic version actually accessing Maven POM infos dynamically (e.g. also during tests), today I found a similar question which involved accessing module A's Maven info from another module B.
I thought about it for a moment and spontaneously had the idea to use a special annotation, applying it to a package declaration in package-info.java. I also created a multi-module example project on GitHub. I do not want to repeat the whole answer, so please see solution B in this answer. The Maven setup involves Templating Maven Plugin, but could also be solved in a more verbose way using a combination of resource filtering and adding generated sources directory to the build via Build Helper Maven. I wanted to avoid that, so I simply used Templating Maven.
Accepted answer worked for me once in the step #2 I changed ${project.version} to ${pom.version}