Adding dependency via calling Maven plugin mojo - maven

I have multiple POMs that inherit a dependency via their parent. The dependency is not to a maven plugin, but another project that I have created:
<dependency>
<groupId>com.my.name.group</groupId>
<artifactId>id-of-my-artifact</artifactId>
<version>2.3.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
Now I want to remove this from the parent POM file and instead have the children POMs use a custom maven plugin for the same functionality. In that custom maven plugin (which I will create), I want to call/add above dependency. I have tried the following code in a Mojo of the new maven-plugin, but it is not adding the dependency (and gives compilation error):
private MavenProject project;
public void execute() throws MojoExecutionException, MojoFailureException {
try {
// adding a dependency
Dependency dep = new Dependency();
dep.setArtifactId("id-of-my-artifact");
dep.setGroupId("com.my.name.group");
dep.setScope("compile");
dep.setVersion("2.3.0-SNAPSHOT");
List<Dependency> lst = new ArrayList<Dependency>();
lst.add(dep);
project.setDependencies(lst);
} catch (Exception ex) {
getLog().info(String.format("Exception %s: ", ex));
throw new MojoExecutionException("Exception has occurred" + ex);
}
}
Is it possible to do this? If yes, how?
I looked at this related question and the link provided in that. From the external link, it seems that it is not possible. But in that question, OP seems to have figured it out and provided a short answer, but I cannot understand the answer. Could someone please help me out? I am new to Maven.

Related

Implements Jmeter java request : ClassNotFoundException

I use dependency of jmeter 5.0 in my custom project pom .
<!-- https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_core -->
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_core</artifactId>
<version>5.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_java -->
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_java</artifactId>
<version>5.0</version>
</dependency>
After compiling I copy jar to lib/ext in jmeter5.0 source project pulling from github , and debug by runing NewDriver, then i found the function org.apache.jorphan.reflect.ClassFinder.ExtendsClassFilter#isChildOf at Class.forName(strClassName, false, contextClassLoader) throw exception java.lang.ClassNotFoundException: com.xxxx.xxxx, strClassName has printed my own classs, so it means my class has been scaned?
private final ClassLoader contextClassLoader
= Thread.currentThread().getContextClassLoader(); // Potentially expensive; do it once
private boolean isChildOf(
Class<?>[] parentClasses, String strClassName, ClassLoader contextClassLoader) {
try {
// Here is exception line
Class<?> targetClass = Class.forName(strClassName, false, contextClassLoader);
if (!targetClass.isInterface()
&& !Modifier.isAbstract(targetClass.getModifiers())) {
return Arrays.stream(parentClasses)
.anyMatch(parent -> parent.isAssignableFrom(targetClass));
}
} catch (UnsupportedClassVersionError | ClassNotFoundException
| NoClassDefFoundError | VerifyError e) {
log.debug(e.getLocalizedMessage(), e);
}
return false;
}
My code
public class JmeterSupportTest extends AbstractJavaSamplerClient {
xxxx;
}
Anyone can help!
It is ok now. Couse of plugin compile which did not add depend jars , and config pom add maven-assembly-plugin will solve
If there are any extra libraries which are being used in your Java Request sampler implementation - they should go to "lib" folder of your JMeter installation (see JMeter Classpath user manual entry for more details) or you can think of using i.e. Maven Shade plugin to create "uber" or "fat" .jar containing all the dependencies
According to JMeter Best Practices you should always be using the latest version of JMeter so consider upgrading to JMeter 5.4 (or whatever is the latest stable version available at JMeter Downloads page) on next available opportunity
In addition to point 2 what you're pulling from Github is master (unless you switch to the v5_0 tag so make sure that the source is matching JMeter dependencies, just in case sources for each respective version can be found at JMeter Archives page

Intellij IDEA complains cannot resolve spring boot properties but they work fine

Can not resolve configuration property '...
I have no problem accessing my properties through the #Value annotation or through an autowired Evironment. But all of my own defined properties get this warning in IDEA. What should I be doing to get IDEA to recognize these and not bother me?
In order for IntelliJ IDEA to know your Spring Boot properties, you can define Spring Boot configuration metadata in your project.
Option 1:
If you can use a #ConfigurationProperties-annotated class for your properties, you can add the Spring Boot configuration annotation processor to your classpath and IntelliJ IDEA will generate the configuration metadata for you in target or out:
Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
Gradle:
implementation 'org.springframework.boot:spring-boot-configuration-processor'
Option 2:
Create the configuration metadata file yourself src/main/resources/META-INF/spring-configuration-metadata.json:
Content:
{
"properties": [
{
"name": "myapp.someprop",
"type": "java.lang.String"
},
{
"name": "myapp.someintprop",
"type": "java.lang.Integer"
}
]
}
Options 1 and 2:
In the IntelliJ IDEA tool window of your build system (Maven/Gradle), click the "Refresh" button.
Select Build > Rebuild Project from the menu.
If the warning still appears, you can try to restart the IDE. Select File > Invalidate Caches / Restart and click on Invalidate and Restart.
Please use the following for Gradle Kotlin Script for Kotlin project:
plugins {
kotlin("jvm")
kotlin("kapt")
}
/* ... */
dependencies {
val configurationProcessor ="org.springframework.boot:spring-boot-configuration-processor:${BuildConstants.springBootVersion}"
kapt(configurationProcessor) // for jar
kaptTest(configurationProcessor) // for jar
annotationProcessor(configurationProcessor) // for IntelliJ Idea
}
/* ... */
kapt {
annotationProcessor("org.springframework.boot.configurationprocessor.ConfigurationMetadataAnnotationProcessor")
}
/* ... */
tasks {
withType<KotlinCompile> {
dependsOn(processResources)
}
}
Kotlin Kapt is needed to work with metadata and memory.
From official Spring documentation, Spring Boot Configuration Processor generates special json file with properties metadata.
Therefore, to distribute jar with property syntax highlight you need:
Ask Gradle to generate this file
Update task sequence to generate file before jar packaging by using dependsOn (not sure, that my code above is the most effective solution, however problem is solved)
However IntelliJ Idea works with annotationProcessor Gradle configuration (unfortunately, I don't have exact answer, why it requires exact it). Therefore you need add the same processor into the annotationProcessor configuration as well.
I had the same problem plus not showing auto completion found out that it works with IntelliJ Ultimate edition and not community version. link
couple of useful steps to take would be:
adding Maven dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
refresh Maven to download dependencies.
coping exact name of property from target/classes/META-INF/spring-configuration-metadata.js to prevent errors.
making sure that your config class is annotated with #ConfigurationProperties("name-here") and that you have enabled it by #EnableConfigurationProperties(NameOfTheConfigClass.class)
A Gradle-based workaround is this:
afterEvaluate {
val kaptKotlinTasks = tasks.named("kaptKotlin") {
doLast {
val kaptKotlin = this
tasks.named<ProcessResources>("processResources") {
from(kaptKotlin.outputs) {
include("META-INF/spring-configuration-metadata.json")
}
}
}
}
tasks.named("processResources") {
this.dependsOn(kaptKotlinTasks)
}
}
After running a build (or just the processResources task) from the Intellij Gradle panel, the warnings about the properties should disappear.
Not ideal, but IntelliJ not supporting kapt is not ideal either :-/
As an additional requirement for the answers above. After Spring-boot 2.2 you can use final keyword on the attributes together with the annotation #ConstructorBinding in order to see IntelliJ auto-complete the property name on the application.properties file. IntelliJ also recognizes if you add a java docs on the attribute.
#ConfigurationProperties(prefix = "my-config")
#ConstructorBinding
public class ConfigImportService {
/**
* the name of the bucket
* (IntelliJ shows this comment on the application.properties file)
*/
private final String bucketName;
private final String databaseName;
#Autowired
public ConfigImportService(
#Value("${bucket.name}") String bucketName,
#Value("${db.name}") String databaseName
) {
this.bucketName = bucketName;
this.databaseName = databaseName;
}
}
And still necessary the dependency, of course.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

Add plugin dependency in grails

I am trying to add dependency of a plugin into my grails application, but it doesnot have any plugins in grails repo. It can be added to maven project as :
<dependency>
<groupId>com.plaid</groupId>
<artifactId>plaid-java</artifactId>
<version>0.2.12</version>
</dependency>
As my project is also maven based. How do i add this plugin into my project.
P.S. : IT cannot be added in plugins and dependencies since there is no grails plugin associated with that.
Any help is appreciated.
You can use the create-pom org.mycompany to create your pom.xml file to make grails read the pom.xml you need to set in BuildConfig.groovy this code
grails.project.dependency.resolution = {
/*YOUR CONFIG*/
pom true
repositories {
/*YOUR RESPOSITORIES*/
}
}
Then you need to add your dependency in this pom.xml
You can see the official doc. in this link
We can add dependency for any plugin in grails under dependencies{} in BuildConfig.groovy as:
<groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>
For your case, the equivalent for:
<dependency>
<groupId>com.plaid</groupId>
<artifactId>plaid-java</artifactId>
<version>0.2.12</version>
</dependency>
is:
dependencies{
compile "com.plaid:plaid-java:0.2.12"
}
For more you can have a look into http://docs.grails.org/2.3.1/guide/conf.html

Error: ClassCastException occured while adding dependency jar in pom.xml

Can any one suggest how to resolve the ClassCastException while adding dependency jar in pom.xml?
I have created a new maven project having returning the object in runtime and then execute the ovverride method definition as based upon client request.
Ex: actionPerform(actionType) -- this method return the 'Object'
public static CommonActions action(ActionTypes actionType)
{
return (CommonActions)actionPerform(actionType);
}
Code is working fine and then successfully executing. There is no ClassCastExceptions while adding this jar into library tab on project properties using eclipse.
Getting ClassCastExceptions on above return statement while adding the below depenedency in pom.xml
<dependency>
<groupId>com.amadeus.selenium.merci</groupId>
<artifactId>appium-amadeus-utilities</artifactId>
<version>1.4-SNAPSHOT</version>
<scope>runtime</scope>
</dependency>
I am using maven version 3.0.4
Please suggest how I resolve the ClassCastException at runtime while adding dependency jar in pom.xml.

Override sonar projectKey when using maven

I want to group 25 modules under a single project key so I can get a consolidated view of code duplication. However the sonar maven plugin uses the <groupId>:<artifactId> so each project is separate.
I've tried overriding the sonar.projectKey but the maven plugin doesn't consider it.
Is there a way of grouping modules together under a single name so that you can have an aggregate view?
Or is there some other in the sonarqube server to get that aggregate view?
As far as I can tell, and contrary to some other forum posts, with at least v3.2 of the maven-sonar-plugin (maybe earlier) the sonar.projectKey property is respected and overrides the default of ${project.groupId}:${project.artifactId}.
Checking the source code also confirms it first looks for the property before defaulting it.
org.sonarsource.scanner.maven.bootstrap.MavenSonarRunner.java
private static void defineProjectKey(MavenProject pom, Properties props) {
String key;
if (pom.getModel().getProperties().containsKey(ScanProperties.PROJECT_KEY)) {
key = pom.getModel().getProperties().getProperty(ScanProperties.PROJECT_KEY);
} else {
key = getSonarKey(pom);
}
props.setProperty(MODULE_KEY, key);
}
private static String getSonarKey(MavenProject pom) {
return new StringBuilder().append(pom.getGroupId()).append(":").append(pom.getArtifactId()).toString();
}
org.sonarsource.scanner.api.ScanProperties
String PROJECT_KEY = "sonar.projectKey";
So by setting the following in the POM, for example, the projectKey can be overriden:
<properties>
<sonar.projectKey>myprefix:${project.groupId}:${project.artifactId}</sonar.projectKey>
</properties>
Tested on Maven 3.3.9. In case this helps anyone!
Link to original GitHub Source:
https://github.com/SonarSource/sonar-scanner-maven/blob/master/src/main/java/org/sonarsource/scanner/maven/bootstrap/MavenProjectConverter.java
I have a similar setup and use a multi modules / aggregator project for that http://maven.apache.org/pom.html#Aggregation.
Just pass the aggregator pom that contains the modules to the sonar build and it should group all modules together. The grouping name is taken from the aggregator artifact-property (and can be overwritten by its name-property).
<groupId>...</groupId>
<artifactId>aggregator-project</artifactId>
<version>...</version>
<packaging>pom</packaging>
<name>Group name overrites artifactId</name>
<modules>
<module>my-project</module>
<module>another-project</module>
</modules>

Resources