My SpringBoot project has a outside jar, the jar need to get some configFile, the configfiles are in src/main/resources/config,after mvn package ,the config is in BOOT-INF\classes\config,but the outside jar got the config path is: /BOOT-INF/lib/config-xxx-1.0.8.jar!/config, how the jar get the right path? when i debug in idea,it can get the right path.
jar 's code:
public static String getConfigPathUtil() {
String configPath = ConfigPathUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
try {
configPath = URLDecoder.decode(configPath, "utf-8");
} catch (UnsupportedEncodingException var2) {
throw new RuntimeException("Transcoding mistakes when the configuration file path" + var2.getMessage());
}
File f = new File(configPath);
configPath = f.getAbsolutePath();
if (configPath.endsWith(".jar")) {
configPath = configPath.substring(0, configPath.lastIndexOf(LIB_PATH));
}
if (configPath.endsWith(BIN_PATH_ENDSWITH)) {
configPath = configPath.substring(0, configPath.lastIndexOf(BIN_PATH_ENDSWITH));
}
configPath = configPath.replace(BIN_PATH, File.separator);
configPath = configPath + CONFIG_PATH;
return configPath;
}
maven pom:
<dependency>
<groupId>xxx</groupId>
<artifactId>config-xxx</artifactId>
<version>1.0.8</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/config-xxx-1.0.8.jar</systemPath>
</dependency>
springboo-maven-plugin
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.xxx.ManagementApplication</mainClass>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
Related
I am trying to write a custom maven plugin. Part of what the plugin will do is examine the JAR files in the m2 folder of other dependencies listed along side it in a <plugin> tag. I will need the exact JAR file/location.
Example:
<build>
<plugins>
<plugin>
<groupId>myPluginGroup</groupId>
<artifactId>myPluginArtifact</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<!-- find me -->
<dependency>
<groupId>example</groupId>
<artifactId>example</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
....
</plugin>
</plugins>
</build>
So i want to be able to scan and find "example.example" and point it to "C:\User\username\.m2\repository\example\example\1.0.0\example-1.0.0.jar".
I can find the plugin dependencies with:
final List<Plugin> plugins = project.getBuild().getPlugins();
for (Plugin plugin : plugins) {
final List<Dependency> dependencyArtifacts = plugin.getDependencies();
for (Dependency dependency : dependencyArtifacts) {
...
}
}
This doesn't give me the location of the JARs, but it does provide the list of build plugin dependencies which is part of what I need.
I can get some locations with:
DependencyNode rootNode = treeBuilder.buildDependencyTree(project, localRepository,
artifactFactory, artifactMetadataSource, artifactFilter, artifactCollector);
CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
rootNode.accept(visitor);
List<DependencyNode> nodes = visitor.getNodes();
for (DependencyNode dependencyNode : nodes) {
...
}
But it doesn't provide plugins and even for what it does provide, it doesn't provide all m2 locations.
Is there a way to identify dependency file locations for dependencies in a build plugin?
You can use Maven Resolver Api to resolve artifacts, in your case code can look like:
(example without loops - only final usage of resolver)
public class MyMojo {
#Component
private RepositorySystem repoSystem;
#Parameter( defaultValue = "${repositorySystemSession}", readonly = true )
private RepositorySystemSession repoSession;
#Parameter(defaultValue = "${project}", readonly = true)
protected MavenProject project;
void resolveOneArtifact() throws ArtifactResolutionException {
Dependency dependency = project.getBuild().getPlugins().get(0).getDependencies().get(0);
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(RepositoryUtils.toDependency(dependency, repoSession.getArtifactTypeRegistry()).getArtifact());
request.setRepositories(project.getRemotePluginRepositories());
ArtifactResult artifactResult = repoSystem.resolveArtifact(repoSession, request);
System.out.println(artifactResult.getArtifact().getFile());
}
void resolveArtifactWithTransitiveDependencies() throws DependencyResolutionException {
Dependency dependency = project.getBuild().getPlugins().get(0).getDependencies().get(0);
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(RepositoryUtils.toDependency(dependency, repoSession.getArtifactTypeRegistry()));
collectRequest.setRepositories(project.getRemotePluginRepositories());
DependencyRequest request = new DependencyRequest();
request.setCollectRequest(collectRequest);
DependencyResult dependencyResult = repoSystem.resolveDependencies(repoSession, request);
ArtifactResult artifactResult = dependencyResult.getArtifactResults().get(0);
System.out.println(artifactResult.getArtifact().getFile());
}
}
More examples please investigate code: https://github.com/apache/maven-resolver/tree/master/maven-resolver-demos
I can not make XStream working and I do not know why. I am in a Maven projet, JRE-11, MVC model, XStream 1.4.18. I am french btw. Thanks in advance.
I just put an exemple with the UE class, but I want to do this with "Classe" and "Creneau".
I tried "xstream.alias", but did not work.
pom.xml
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Archi</groupId>
<artifactId>Archi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.18</version>
</dependency>
</dependencies>
</project>
Archi.java
package controlleur;
import com.thoughtworks.xstream.XStream;
import modele.*;
import vue.*;
public class Archi {
public static void main(String[] args) {
Classe classe = new Classe("IATIC5", 2020, 2021);
UE ue = new UE("ARC", "EU-Archi");
Creneau creneau = new Creneau(9, 11, 2021, 20, 22);
Fenetre fenetre = new Fenetre();
XStream xstream = new XStream();
String xml = xstream.toXML(ue);
System.out.println(xml);
Controlleur controlleur = new Controlleur(classe, ue, creneau, fenetre);
}
}
Controller.java
package controlleur;
import modele.*;
import vue.*;
public class Controlleur {
public Controlleur(Classe classe, UE ue, Creneau creneau, Fenetre fenetre) {
fenetre.affiche(classe, ue, creneau);
}
}
UE.java
package modele;
import java.util.UUID;
public class UE {
private String id = UUID.randomUUID().toString(), sigle, nomination;
public UE(String sigle, String nomination) {
this.sigle = sigle;
this.nomination = nomination;
}
//All getter, setter and toString
}
error text
Exception in thread "main" com.thoughtworks.xstream.converters.ConversionException: No converter available
---- Debugging information ----
message : No converter available
type : modele.UE
converter : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
message[1] : Unable to make field private java.lang.String modele.UE.id accessible: module archi does not "opens modele" to module xstream
-------------------------------
at xstream#1.4.18/com.thoughtworks.xstream.core.DefaultConverterLookup.lookupConverterForType(DefaultConverterLookup.java:88)
at xstream#1.4.18/com.thoughtworks.xstream.XStream$1.lookupConverterForType(XStream.java:472)
at xstream#1.4.18/com.thoughtworks.xstream.core.TreeMarshaller.convertAnother(TreeMarshaller.java:48)
at xstream#1.4.18/com.thoughtworks.xstream.core.TreeMarshaller.convertAnother(TreeMarshaller.java:43)
at xstream#1.4.18/com.thoughtworks.xstream.core.TreeMarshaller.start(TreeMarshaller.java:82)
at xstream#1.4.18/com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.marshal(AbstractTreeMarshallingStrategy.java:37)
at xstream#1.4.18/com.thoughtworks.xstream.XStream.marshal(XStream.java:1243)
at xstream#1.4.18/com.thoughtworks.xstream.XStream.marshal(XStream.java:1232)
at xstream#1.4.18/com.thoughtworks.xstream.XStream.toXML(XStream.java:1205)
at xstream#1.4.18/com.thoughtworks.xstream.XStream.toXML(XStream.java:1192)
at archi/controlleur.Archi.main(Archi.java:17)
I had the same issue and I found out what was wrong in my project.
I was developing a JavaFX with data persistence in XML with XStream. When attempting to read the file, I had the same issue.
In order to fix it, I did the following:
Save the models/javabeans on a directory.
MODULE/javabeans/
PeopleXML.java
PersonXML.java
Modify the module to allow XStream to use these classes (module-info.java)
module MODULE {
...
requires xstream;
...
opens MODULE.javabeans to xstream;
exports MODULE.javabeans;
}
Implement the code normally.
XStream xstream = new XStream();
xstream.addPermission(NoTypePermission.NONE);
xstream.addPermission(NullPermission.NULL);
xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
xstream.allowTypes(new Class[]{PersonXML.class, PeopleXML.class});
xstream.allowTypesByWildcard(new String[] {
"MODULE.javabeans.**"
});
xstream.alias("people", PeopleXML.class);
xstream.alias("person", PersonXML.class);
xstream.addImplicitCollection(PeopleXML.class, "lstPeople"); // Collection name
try {
FileInputStream fis = new FileInputStream(xmlFilename);
return (PeopleXML) xstream.fromXML(fis);
}
catch (FileNotFoundException e) {
throw new InvalidDataException("File not found: " + xmlFilename);
}
Note: MODULE is the module you are working on.
I've made a simple library jar that consists of this single class:
import org.apache.commons.codec.binary.Base64;
public class NiceEncoder {
public static String encode(String first, String second) {
String encoded = new String(Base64.encodeBase64((first + ":" + second).getBytes()));
return encoded;
}
}
It has this pom.xml:
<?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>base64tester</groupId>
<artifactId>base64tester</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
</dependency>
</dependencies>
</project>
Then I package it into a jar and install it in local maven repository:
mvn install:install-file -Dfile=/home/base64tester-1.0-SNAPSHOT.jar -DgroupId=base64tester -DartifactId=base64tester -Dversion=1.0-SNAPSHOT -Dpackaging=jar
Then I import it in another project like this:
<dependencies>
<dependency>
<groupId>base64tester</groupId>
<artifactId>base64tester</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
and try running this code:
public class TestNiceEncoder {
public static void main(String[] args) {
String first = "some word";
String second = "other word";
System.out.println(NiceEncoder.encode(first, second));
}
}
I get the java.lang.NoClassDefFoundError: org/apache/commons/codec/binary/Base64 error.
Why? How do I fix it other than importing the commons-codec inside the project with the TestNiceEncoder class? How do I make it so everyone who has the base64tester.jar can run it with no errors or additional actions?
EDIT: It's the same thing with other dependencies in base64tester project. Got it to use JSoup library and then if the method using it gets called from outside project, there's exception:
In project B:
public class TestNiceEncoder {
public static void main(String[] args) {
String first = "some word";
String second = "other word";
// System.out.println(NiceEncoder.encode(first, second));
System.out.println(NiceEncoder.getRedditTitle()); //jsoup error here
}
}
In project A (base64tester):
public class NiceEncoder {
public static String encode(String first, String second) {
String encoded = new String(Base64.encodeBase64((first + ":" + second).getBytes()));
return encoded;
}
public static String getRedditTitle() {
try {
Document doc = Jsoup.connect("http://reddit.com/").get();
String title = doc.title();
System.out.println("title: " + title);
return title;
}
catch (Exception e) {
System.out.println("Couldn't open URL");
return "";
}
}
}
<dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.13.1</version>
</dependency>
</dependencies>
error is this one:
Exception in thread "main" java.lang.NoClassDefFoundError: org/jsoup/Jsoup
This step
Then I package it into a jar and install it in local maven repository
require you to specify pom.xml file, otherwise one is generated, but without dependency info
Something like (of course you need to adjust path to pom.xml)
mvn install:install-file -Dfile=/home/base64tester-1.0-SNAPSHOT.jar -DpomFile=/home/pom.xml
read more in official docs.
Alternatively you can declare explicit dependency on commons-codec in your downstream project (where you're consuming your jar)
Side note, JDK8 already includes support for base64 codec, see here - so maybe you can use it directly without any extra jars on classpath
The dependencies package of Base64Tester are not included in jar file. You should use mvn instal from Base64Test project
Here I have my Maven Mojo:
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.shared.invoker.*;
import java.util.Collections;
#Mojo(name = "run")
public class RunMojo extends AbstractMojo {
#Override
public void execute() throws MojoExecutionException {
InvocationRequest request = new DefaultInvocationRequest();
request.setGoals(Collections.singletonList("myplugin:mygoal"));
// need to set parameters to pass to the goal
Invoker invoker = new DefaultInvoker();
try {
invoker.execute(request);
} catch (MavenInvocationException e) {
e.printStackTrace();
}
}
}
And I need to invoke a second Mojo passing some parameters as I do when defining the plugin inside the pom.xml, as follow.
<build>
<plugins>
<plugin>
<artifactId>myPlugin</artifactId>
<groupId>myGroupId</groupId>
<version>myVersion</version>
<configuration>
<param1>value1</param1>
<param2>value2</param2>
<param3>value3</param3>
</configuration>
</plugin>
</plugins>
</build>
Any solution?
It might be an older question, but found myself in this situation recently and taught I'd show how I created a new plugin where which wraps another plugin.
I've ended up using the mojo-executor plugin (https://github.com/TimMoore/mojo-executor) . Even though it is not actively maintained, it does the job quite well. Here is an example of how I executed the html2pdf-maven-plugin (https://bitbucket.org/prunge/html2pdf-maven-plugin/wiki/Home) from my own maven plugin.
The generatePdf(...) method is called from the execute() method of your Mojo class. The getMvnPlugin(...) method is where I specified the plugin groupId and ArtifactId and the execution details. The getPluginConfiguration(...) method is where the plugin configuration is made, specifying the parameters of the html2pdf-maven-plugin.
private void generatePdf(File inputFilePath, String outputFile) {
String inputDirectory = inputFilePath.getParent();
String inputFileName = inputFilePath.getName();
try {
Plugin html2pdfPlugin = getMvnPlugin(outputFile, inputFile, inputFileName);
MojoExecutor.ExecutionEnvironment executionEnvironment = MojoExecutor.executionEnvironment(mavenProject, mavenSession, pluginManager);
MojoExecutor.executeMojo(html2pdfPlugin, "html2pdf", getPluginConfiguration(outputFile, inputDirectory, inputFileName), executionEnvironment);
} catch (Exception ex) {
String errorMessage = String.format("Failed to generate PDF file [%s] from html file [%s].", outputFile, inputFile);
getLog().error(errorMessage, ex);
}
}
private Plugin getMvnPlugin(String outputFile, String inputDirectory, String inputFileName) {
Plugin plugin = new Plugin();
plugin.setGroupId("au.net.causal.maven.plugins");
plugin.setArtifactId("html2pdf-maven-plugin");
plugin.setVersion("2.0");
PluginExecution pluginExecution = new PluginExecution();
pluginExecution.setGoals(Collections.singletonList("html2pdf"));
pluginExecution.setId("generate-pdf");
pluginExecution.setPhase("generate-resources");
plugin.setExecutions(Collections.singletonList(pluginExecution));
plugin.setConfiguration(getPluginConfiguration(outputFile, inputDirectory, inputFileName));
return plugin;
}
private Xpp3Dom getPluginConfiguration(String outputFile, String inputDirectory, String inputFileName) {
MojoExecutor.Element outputFileElement = new MojoExecutor.Element("outputFile", outputFile);
MojoExecutor.Element includeElement = new MojoExecutor.Element("include", "**/" + inputFileName);
MojoExecutor.Element includesElement = new MojoExecutor.Element("includes", includeElement);
MojoExecutor.Element directoryElement = new MojoExecutor.Element("directory", inputDirectory);
MojoExecutor.Element htmlFileSetElement = new MojoExecutor.Element("htmlFileSet", directoryElement, includesElement);
MojoExecutor.Element htmlFileSetsElement = new MojoExecutor.Element("htmlFileSets", htmlFileSetElement);
return MojoExecutor.configuration(outputFileElement, htmlFileSetsElement);
}
The mavenProject, mavenSession and pluginManager just have to be injected in the Mojo class using the org.apache.maven.plugins.annotations.Component.
#Component
private MavenProject mavenProject;
#Component
private MavenSession mavenSession;
#Component
private BuildPluginManager pluginManager;
I have noticed that in a Maven artifact's JAR, the project.version attribute is included in two files:
META-INF/maven/${groupId}/${artifactId}/pom.properties
META-INF/maven/${groupId}/${artifactId}/pom.xml
Is there a recommended way to read this version at runtime?
You should not need to access Maven-specific files to get the version information of any given library/class.
You can simply use getClass().getPackage().getImplementationVersion() to get the version information that is stored in a .jar-files MANIFEST.MF. Unfortunately Maven does not write the correct information to the manifest as well by default!
Instead one has to modify the <archive> configuration element of the maven-jar-plugin to set addDefaultImplementationEntries and addDefaultSpecificationEntries to true, like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
Ideally this configuration should be put into the company pom or another base-pom.
Detailed documentation of the <archive> element can be found in the Maven Archive documentation.
To follow up the answer above, for a .war artifact, I found I had to apply the equivalent configuration to maven-war-plugin, rather than maven-jar-plugin:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
This added the version information to MANIFEST.MF in the project's .jar (included in WEB-INF/lib of the .war)
Here's a method for getting the version from the pom.properties, falling back to getting it from the manifest
public synchronized String getVersion() {
String version = null;
// try to load from maven properties first
try {
Properties p = new Properties();
InputStream is = getClass().getResourceAsStream("/META-INF/maven/com.my.group/my-artefact/pom.properties");
if (is != null) {
p.load(is);
version = p.getProperty("version", "");
}
} catch (Exception e) {
// ignore
}
// fallback to using Java API
if (version == null) {
Package aPackage = getClass().getPackage();
if (aPackage != null) {
version = aPackage.getImplementationVersion();
if (version == null) {
version = aPackage.getSpecificationVersion();
}
}
}
if (version == null) {
// we could not compute the version so use a blank
version = "";
}
return version;
}
I am using maven-assembly-plugin for my maven packaging. The usage of Apache Maven Archiver in Joachim Sauer's answer could also work:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
<executions>
<execution .../>
</executions>
</plugin>
Because archiever is one of maven shared components, it could be used by multiple maven building plugins, which could also have conflict if two or more plugins introduced, including archive configuration inside.
If you happen to use Spring Boot you can make use of the BuildProperties class.
Take the following snippet from our OpenAPI configuration class as an example:
#Configuration
#RequiredArgsConstructor // <- lombok
public class OpenApi {
private final BuildProperties buildProperties; // <- you can also autowire it
#Bean
public OpenAPI yourBeautifulAPI() {
return new OpenAPI().info(new Info()
.title(buildProperties.getName())
.description("The description")
.version(buildProperties.getVersion())
.license(new License().name("Your company")));
}
}
I know it's a very late answer but I'd like to share what I did as per this link:
I added the below code to the pom.xml:
<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>
And this Advice Controller in order to get the version as model attribute:
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
#ControllerAdvice
public class CommonControllerAdvice
{
#Autowired
BuildProperties buildProperties;
#ModelAttribute("version")
public String getVersion() throws IOException
{
String version = buildProperties.getVersion();
return version;
}
}
I spent some time on the two main approaches here and they didn't work-out for me. I am using Netbeans for the builds, may be there's more going on there. I had some errors and warnings from Maven 3 with some constructs, but I think those were easy to correct. No biggie.
I did find an answer that looks maintainable and simple to implement in this article on DZone:
Stamping Version Number and Build Time in a Properties File with Maven
I already have a resources/config sub-folder, and I named my file: app.properties, to better reflect the kind of stuff we may keep there (like a support URL, etc.).
The only caveat is that Netbeans gives a warning that the IDE needs filtering off. Not sure where/how. It has no effect at this point. Perhaps there's a work around for that if I need to cross that bridge. Best of luck.
To get this running in Eclipse, as well as in a Maven build, you should add the addDefaultImplementationEntries and addDefaultSpecificationEntries pom entries as described in other replies, then use the following code:
public synchronized static final String getVersion() {
// Try to get version number from pom.xml (available in Eclipse)
try {
String className = getClass().getName();
String classfileName = "/" + className.replace('.', '/') + ".class";
URL classfileResource = getClass().getResource(classfileName);
if (classfileResource != null) {
Path absolutePackagePath = Paths.get(classfileResource.toURI())
.getParent();
int packagePathSegments = className.length()
- className.replace(".", "").length();
// Remove package segments from path, plus two more levels
// for "target/classes", which is the standard location for
// classes in Eclipse.
Path path = absolutePackagePath;
for (int i = 0, segmentsToRemove = packagePathSegments + 2;
i < segmentsToRemove; i++) {
path = path.getParent();
}
Path pom = path.resolve("pom.xml");
try (InputStream is = Files.newInputStream(pom)) {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(is);
doc.getDocumentElement().normalize();
String version = (String) XPathFactory.newInstance()
.newXPath().compile("/project/version")
.evaluate(doc, XPathConstants.STRING);
if (version != null) {
version = version.trim();
if (!version.isEmpty()) {
return version;
}
}
}
}
} catch (Exception e) {
// Ignore
}
// Try to get version number from maven properties in jar's META-INF
try (InputStream is = getClass()
.getResourceAsStream("/META-INF/maven/" + MAVEN_PACKAGE + "/"
+ MAVEN_ARTIFACT + "/pom.properties")) {
if (is != null) {
Properties p = new Properties();
p.load(is);
String version = p.getProperty("version", "").trim();
if (!version.isEmpty()) {
return version;
}
}
} catch (Exception e) {
// Ignore
}
// Fallback to using Java API to get version from MANIFEST.MF
String version = null;
Package pkg = getClass().getPackage();
if (pkg != null) {
version = pkg.getImplementationVersion();
if (version == null) {
version = pkg.getSpecificationVersion();
}
}
version = version == null ? "" : version.trim();
return version.isEmpty() ? "unknown" : version;
}
If your Java build puts target classes somewhere other than "target/classes", then you may need to adjust the value of segmentsToRemove.
On my spring boot application, the solution from the accepted answer worked until I recently updated my jdk to version 12. Tried all the other answers as well and couldn't get that to work.
At that point, I added the below line to the first class of my spring boot application, just after the annotation #SpringBootApplication
#PropertySources({
#PropertySource("/META-INF/maven/com.my.group/my-artefact/pom.properties")
})
Later I use the below to get the value from the properties file in whichever class I want to use its value and appVersion gets the project version to me:
#Value("${version}")
private String appVersion;
Hope that helps someone.
The most graceful solutions I've found is that one from J.Chomel: link
Doesn't require any hacks with properties. To avoid issues with broken link in a future I'll duplicate it here:
YourClass.class.getPackage().getImplementationVersion();
And (if you don't have Manifest file in your jar/war yet, for me Intellij Idea's Maven already included them) you will require also a small change in pom.xml:
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
...
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
...
A simple solution which is Maven compatible and works for any (thus also third party) class:
private static Optional<String> getVersionFromManifest(Class<?> clazz) {
try {
File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI());
if (file.isFile()) {
JarFile jarFile = new JarFile(file);
Manifest manifest = jarFile.getManifest();
Attributes attributes = manifest.getMainAttributes();
final String version = attributes.getValue("Bundle-Version");
return Optional.of(version);
}
} catch (Exception e) {
// ignore
}
return Optional.empty();
}
Here’s a version without Optional<> that just returns null if not present (for quick debugging/dumping):
private static String getVersionFromManifest(Class<?> clazz) {
try {
File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI());
if (file.isFile()) {
JarFile jarFile = new JarFile(file);
Manifest manifest = jarFile.getManifest();
Attributes attributes = manifest.getMainAttributes();
return attributes.getValue("Bundle-Version");
}
} catch (Exception e) {
// ignore
}
return null;
}
Tried all the answers above but nothing worked for me:
I did not use Spring
Managed to put Version inside of manifest, but someClass.class.getPackage().getImplementationVersion() returned null
However version was appended to the jar file name so I was able to find a jar file using:
new File(ClassLoader.getSystemResource("").toURI()).getParentFile();
and then extract it from the file name.
Java 8 variant for EJB in war file with maven project. Tested on EAP 7.0.
#Log4j // lombok annotation
#Startup
#Singleton
public class ApplicationLogic {
public static final String DEVELOPMENT_APPLICATION_NAME = "application";
public static final String DEVELOPMENT_GROUP_NAME = "com.group";
private static final String POM_PROPERTIES_LOCATION = "/META-INF/maven/" + DEVELOPMENT_GROUP_NAME + "/" + DEVELOPMENT_APPLICATION_NAME + "/pom.properties";
// In case no pom.properties file was generated or wrong location is configured, no pom.properties loading is done; otherwise VERSION will be assigned later
public static String VERSION = "No pom.properties file present in folder " + POM_PROPERTIES_LOCATION;
private static final String VERSION_ERROR = "Version could not be determinated";
{
Optional.ofNullable(getClass().getResourceAsStream(POM_PROPERTIES_LOCATION)).ifPresent(p -> {
Properties properties = new Properties();
try {
properties.load(p);
VERSION = properties.getProperty("version", VERSION_ERROR);
} catch (Exception e) {
VERSION = VERSION_ERROR;
log.fatal("Unexpected error occured during loading process of pom.properties file in META-INF folder!");
}
});
}
}