In ProjectA, I have a MethodA
in ClassA
, and ProjectA jar is added in different projects as a Maven dependency, and different projects are calling MethodA
.
Requirement is
Whenever MethodA
of ClassA
is called by any other project, we would require to log the called project artifact id and version, considering ProjectA dependency is added in these projects pom.xml.
NOTE
Below works only on self project (ProjectA), creation of property file and turning on maven resource filtering
Create a property file
src/main/resources/project.properties
with the below content
version=${project.version}
artifactId=${project.artifactId}
Now turn on maven resource filtering
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
MethodA
public class ClassA {
final static Logger logger = Logger.getLogger(ClassA.class);
public void MethodA{
final Properties properties = new Properties();
properties.load(this.getClassLoader().getResourceAsStream("project.properties"));
logger.info(properties.getProperty("version"));
logger.info(properties.getProperty("artifactId"));
}
}
When called MethodA in Project B, I get the below output in logger
version=${project.version}
artifactId=${project.artifactId} which is incorrect.
Expected output:
version = 1.0.0
artifactId = ProjectB
Is there any better way to log the calling project artifact id? If MethodA
is called by ProjectC, we want to get ProjectC artifactid and version.
Requirement: We have 30+ projects calling MethodA from ProjectA, so we should not make any changes in the calling projects.
Your POM snippet should replace the variables correctly, if you put it in the right POM section:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
You can inspect the result in the target/classes
folder. After I fixed your faulty pseudo code by adding an empty argument list ()
to your method name and replaced the nonsensical this.getClassLoader()
by getClass().getClassLoader()
, the code even compiles and does something meaningful. Do you ever test before you post something to a public platform like StackOverflow?
import java.io.IOException;
import java.util.Properties;
public class ClassA {
public void methodA() throws IOException {
final Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("project.properties"));
System.out.println(properties.getProperty("version"));
System.out.println(properties.getProperty("artifactId"));
}
public static void main(String[] args) throws IOException {
new ClassA().methodA();
}
}
Console log when running from IntelliJ IDEA after mvn compile
(because we need Maven to process the resources and copy them to target/classes
):
1.9.8-SNAPSHOT
util
Or whatever your module name and version are.
If you see the variable names instead, either your classpath does not point to the JAR but to the source directory somehow, or you have multiple modules with a project.properties
file and in one of them forgot resource filtering. Whichever file is found first on the class path, will be loaded. So in a multi-module project, you better use different file names, otherwise it is more or less a lottery which one if found first.
The next problem would then be for your aspect or other module to know which resource file to load, so that better be linked to class or package names somehow in order for the other module to be able to guess the resource file from the package name. You do need clean package name separation between modules then. I really wonder if it is worth the trouble.
package-info.java
+ custom annotationAnother idea would be to use resource filtering or a plugin like org.codehaus.mojo:templating-maven-plugin
for replacing the versions directly into package annotation values in a package-info.java
file and then simply fetch the values during runtime from the package info. I made a quick & dirty local test with that plugin, and it works nicely. I recommend to keep it simple for now and just fix your resource filtering problem. If you need the more generic solution I just described, please let me know.
Update: I extracted the quick solution I hacked into one of my projects into a new Maven multi-module project in order to show you a clean solution as follows:
Say, we have a parent POM with 3 sub-modules:
annotation
- contains an annotation to be used on packages in package-info.java
files. Can easily be modified to also be applicable to classes.library
- example library to be accessed by an application moduleapplication
- example applicationYou can find the full project on GitHub: https://github.com/kriegaex/SO_Maven_ArtifactInfoRuntime_68321439
The project's directory layout is as follows:
$ tree
.
├── annotation
│ ├── pom.xml
│ └── src
│ └── main
│ └── java
│ └── de
│ └── scrum_master
│ └── stackoverflow
│ └── q68321439
│ └── annotation
│ └── MavenModuleInfo.java
├── application
│ ├── pom.xml
│ └── src
│ ├── main
│ │ ├── java
│ │ │ └── de
│ │ │ └── scrum_master
│ │ │ └── stackoverflow
│ │ │ └── q68321439
│ │ │ └── application
│ │ │ └── Application.java
│ │ └── java-templates
│ │ └── de
│ │ └── scrum_master
│ │ └── stackoverflow
│ │ └── q68321439
│ │ └── application
│ │ └── package-info.java
│ └── test
│ └── java
│ └── de
│ └── scrum_master
│ └── stackoverflow
│ └── q68321439
│ └── application
│ └── ModuleInfoTest.java
├── library
│ ├── pom.xml
│ └── src
│ └── main
│ ├── java
│ │ └── de
│ │ └── scrum_master
│ │ └── stackoverflow
│ │ └── q68321439
│ │ └── library
│ │ └── LibraryClass.java
│ └── java-templates
│ └── de
│ └── scrum_master
│ └── stackoverflow
│ └── q68321439
│ └── library
│ └── package-info.java
└── pom.xml
Please note the src/java-templates
directories in both the library and the application modules, containing package-info.java
files. The directory name is the default for Templating Maven Plugin, making plugin configuration less verbose.
<?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>de.scrum-master.stackoverflow.q68321439</groupId>
<artifactId>maven-artifact-info-runtime</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<modules>
<module>annotation</module>
<module>library</module>
<module>application</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>templating-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<id>filter-src</id>
<goals>
<goal>filter-sources</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
annotation
<?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>
<groupId>de.scrum-master.stackoverflow.q68321439</groupId>
<artifactId>maven-artifact-info-runtime</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>annotation</artifactId>
</project>
package de.scrum_master.stackoverflow.q68321439.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
public @interface MavenModuleInfo {
String groupId();
String artifactId();
String version();
}
library
<?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>
<groupId>de.scrum-master.stackoverflow.q68321439</groupId>
<artifactId>maven-artifact-info-runtime</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>library</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>templating-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>de.scrum-master.stackoverflow.q68321439</groupId>
<artifactId>annotation</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>
package de.scrum_master.stackoverflow.q68321439.library;
public class LibraryClass {}
Please note that the following file needs to be located in library/src/main/java-templates/de/scrum_master/stackoverflow/q68321439/library/package-info.java
. Here you can see how we use Maven properties to be replaced by their corresponding values during the build process by Templating Maven Plugin:
/**
* This is the package description (...)
*/
@MavenModuleInfo(groupId = "${project.groupId}", artifactId = "${project.artifactId}", version = "${project.version}")
package de.scrum_master.stackoverflow.q68321439.library;
import de.scrum_master.stackoverflow.q68321439.annotation.MavenModuleInfo;
application
<?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>
<groupId>de.scrum-master.stackoverflow.q68321439</groupId>
<artifactId>maven-artifact-info-runtime</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>application</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>templating-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>de.scrum-master.stackoverflow.q68321439</groupId>
<artifactId>annotation</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.scrum-master.stackoverflow.q68321439</groupId>
<artifactId>library</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.scrum-master.stackoverflow.q68321439</groupId>
<artifactId>library</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
package de.scrum_master.stackoverflow.q68321439.application;
public class Application {
public static void main(String[] args) {}
}
Please note that the following file needs to be located in application/src/main/java-templates/de/scrum_master/stackoverflow/q68321439/application/package-info.java
. Here you can see how we use Maven properties to be replaced by their corresponding values during the build process by Templating Maven Plugin:
/**
* This is the package description (...)
*/
@MavenModuleInfo(groupId = "${project.groupId}", artifactId = "${project.artifactId}", version = "${project.version}")
package de.scrum_master.stackoverflow.q68321439.application;
import de.scrum_master.stackoverflow.q68321439.annotation.MavenModuleInfo;
package de.scrum_master.stackoverflow.q68321439.application;
import de.scrum_master.stackoverflow.q68321439.annotation.MavenModuleInfo;
import de.scrum_master.stackoverflow.q68321439.library.LibraryClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ModuleInfoTest {
@Test
public void test() {
String groupId = "de.scrum-master.stackoverflow.q68321439";
MavenModuleInfo libMavenInfo = logAndGetMavenModuleInfo("Library Maven info", LibraryClass.class.getPackage());
assertEquals(groupId, libMavenInfo.groupId());
assertEquals("library", libMavenInfo.artifactId());
MavenModuleInfo appMavenInfo = logAndGetMavenModuleInfo("Application Maven info", Application.class.getPackage());
assertEquals(groupId, appMavenInfo.groupId());
assertEquals("application", appMavenInfo.artifactId());
}
private MavenModuleInfo logAndGetMavenModuleInfo(String message, Package aPackage) {
MavenModuleInfo moduleInfo = aPackage.getAnnotation(MavenModuleInfo.class);
System.out.println(message);
System.out.println(" " + moduleInfo.groupId());
System.out.println(" " + moduleInfo.artifactId());
System.out.println(" " + moduleInfo.version());
return moduleInfo;
}
}
Now run the Maven build via mvn clean test
:
(...)
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ application ---
[INFO] Surefire report directory: C:\Users\alexa\Documents\java-src\SO_Maven_ArtifactInfoRuntime_68321439\application\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running de.scrum_master.stackoverflow.q68321439.application.ModuleInfoTest
Library Maven info
de.scrum-master.stackoverflow.q68321439
library
1.0-SNAPSHOT
Application Maven info
de.scrum-master.stackoverflow.q68321439
application
1.0-SNAPSHOT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.094 sec
(...)
Assuming that all calling modules implement the same scheme with package info + special annotation, you can print the caller info like this:
package de.scrum_master.stackoverflow.q68321439.library;
import de.scrum_master.stackoverflow.q68321439.annotation.MavenModuleInfo;
public class LibraryClass {
public void doSomething() {
StackTraceElement callerStackTraceElement = new Exception().getStackTrace()[1];
try {
Class<?> callerClass = Class.forName(callerStackTraceElement.getClassName());
MavenModuleInfo mavenModuleInfo = callerClass.getPackage().getAnnotation(MavenModuleInfo.class);
System.out.println(mavenModuleInfo.groupId());
System.out.println(mavenModuleInfo.artifactId());
System.out.println(mavenModuleInfo.version());
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void doSomethingJava9() {
Class<?> callerClass = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass();
MavenModuleInfo mavenModuleInfo = callerClass.getPackage().getAnnotation(MavenModuleInfo.class);
System.out.println(mavenModuleInfo.groupId());
System.out.println(mavenModuleInfo.artifactId());
System.out.println(mavenModuleInfo.version());
}
}
While doSomething()
also works in old Java versions (tested on Java 8), on Java 9+ you can use the JEP 259 Stack-Walking API as shown in doSomethingJava9()
. In that case, you do not need to manually parse an exception stack trace and handle exceptions.
Assuming that you use my sample project and call the library from the application module (like in the previous section), a quick & dirty way to print JAR information would be this:
Add this method to LibraryClass
:
public void doSomethingClassLoader() {
StackTraceElement callerStackTraceElement = new Exception().getStackTrace()[1];
try {
Class<?> callerClass = Class.forName(callerStackTraceElement.getClassName());
// Cheap way of getting Maven artifact name - TODO: parse
System.out.println(
callerClass
.getClassLoader()
.getResource(callerStackTraceElement.getClassName().replaceAll("[.]", "/") + ".class")
);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Again, on Java 9+ you could make the code nicer by using the Stack-Walking API, see above.
Call the method from Application
:
public class Application {
public static void main(String[] args) {
// new LibraryClass().doSomething();
// new LibraryClass().doSomethingJava9();
new LibraryClass().doSomethingClassLoader();
}
}
Now build the Maven application from the command line and run with 3 different classpaths, pointing to
target/classes
directorytarget
directory$ mvn install
(...)
$ java -cp "annotation\target\annotation-1.0-SNAPSHOT.jar;library\target\library-1.0-SNAPSHOT.jar;application\target\classes" de.scrum_master.stackoverflow.q68321439.application.Application
file:/C:/Users/alexa/Documents/java-src/SO_Maven_ArtifactInfoRuntime_68321439/application/target/classes/de/scrum_master/stackoverflow/q68321439/application/Application.class
$ java -cp "annotation\target\annotation-1.0-SNAPSHOT.jar;library\target\library-1.0-SNAPSHOT.jar;application\target\application-1.0-SNAPSHOT.jar" de.scrum_master.stackoverflow.q68321439.application.Application
jar:file:/C:/Users/alexa/Documents/java-src/SO_Maven_ArtifactInfoRuntime_68321439/application/target/application-1.0-SNAPSHOT.jar!/de/scrum_master/stackoverflow/q68321439/application/Application.class
$ java -cp "annotation\target\annotation-1.0-SNAPSHOT.jar;library\target\library-1.0-SNAPSHOT.jar;c:\Users\Alexa\.m2\repository\de\scrum-master\stackoverflow\q68321439\application\1.0-SNAPSHOT\application-1.0-SNAPSHOT.jar" de.scrum_master.stackoverflow.q68321439.application.Application
jar:file:/C:/Users/alexa/.m2/repository/de/scrum-master/stackoverflow/q68321439/application/1.0-SNAPSHOT/application-1.0-SNAPSHOT.jar!/de/scrum_master/stackoverflow/q68321439/application/Application.class
As you can see
Of course, you could parse that information and print it in a more structured way, but I suggest to simply print it like this and let the human brain reading the log do the parsing.
Like I said in a comment before, this works nicely in the case I showed you, also with different projects, not just in a single multi-module project. What kinds of information you would see in case of an application server deployment or uber JAR situation, strongly depends on the exact situation. There is no single, generic answer, and I cannot do your whole job for you. I showed you several options, now you can select one.