Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Maven archetype from Java code

I want to know if it's possible to run the maven command: archetype:generate in Java code. I've tried this with the maven embedder, but this library is deprecated.

I want to do an archetype:generate from a remote catalog, and capture the required properties of the archetype.

The maven command I want to run is for example:

mvn archetype:generate \
    -DgroupId=com.maven \
    -DartifactId=test \
    -DarchetypeVersion=1.0-alpha-4 \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-j2ee-simple \
    -DinteractiveMode=false \
    -DarchetypeCatalog=http://repo1.maven.org/maven2/archetype-catalog.xml

for some archetypes there are required properties, after you do this request. I want to display these properties on a GUI screen, just like the m2eclipse plugin does, so the user can fill in these properties.

Does anybody has a suggestion?

like image 433
Elmar Maan Avatar asked Feb 12 '26 23:02

Elmar Maan


2 Answers

You could try to use the Maven Invoker.

Add this dependency to the pom.xml:

<dependency>
    <groupId>org.apache.maven.shared</groupId>
    <artifactId>maven-invoker</artifactId>
    <version>2.1.1</version>
</dependency>

And here is what the code might look like:

import org.apache.maven.shared.invoker.*;

import java.util.Collections;
import java.util.Properties;

public class MavenInvoker {

    public static void main(String[] args) throws MavenInvocationException {
        InvocationRequest request = new DefaultInvocationRequest();
        request.setGoals( Collections.singletonList("archetype:generate") );
        request.setInteractive(false);
        Properties properties = new Properties();
        properties.setProperty("groupId", "com.maven");
        properties.setProperty("artifactId", "test");
        properties.setProperty("archetypeVersion", "1.0-alpha-4");
        properties.setProperty("archetypeGroupId", "org.apache.maven.archetypes");
        properties.setProperty("archetypeArtifactId", "maven-archetype-j2ee-simple");
        properties.setProperty("archetypeCatalog", "http://repo1.maven.org/maven2/archetype-catalog.xml");
        request.setProperties(properties);
        Invoker invoker = new DefaultInvoker();
        InvocationResult result = invoker.execute( request );
    }
}
like image 174
maba Avatar answered Feb 14 '26 12:02

maba


If all else fails, you can use Runtime.exec().

like image 25
tbsalling Avatar answered Feb 14 '26 12:02

tbsalling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!