Is it possible to call Maven goals from Java, for instance, can I do the equivalent of:
mvn clean package
from a Java class?
thanks, Ni
I would not recommend to use MAVEN CLI
because it works differently comparing to command line alternative. For example:
With CLI, I want to reproduce "mvn dependency:resolve validate"
cli.doMain(
new String[]{
"dependency:resolve", // download deps if needed
"validate"}, // just validates, no need even to compile
projectPath ...
But actually it will go all over the folders (recursively) and will try to validate all projects there even if I don't want it. If if something wrong - it fails.
If, though, you try to do the same just with command line - it will invoke only pom.xm and will finish successfully (even if some project inside 'projectPath' is not resolvable.
With CLI
I could NOT manage to use "-f " flag to specify particular pom.xml
!
This is quite good for me:
private int resolveAsCommandLine() {
try {
String command = "mvn " +
"-f " + projectPath + "\\pom.xml " +
"-Dmaven.repo.local=" + localRepoPath + "\\repository " +
"-Dmaven.test.skip=true " + // ignore tests
"dependency:resolve " + // download deps if needed
"validate";
System.out.println("%> Executing command: '" + command + "'...");
Process p = Runtime.getRuntime().exec( // "cmd - for windows only"
"cmd /c " + command
);
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()) );
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
if(line.contains("[ERROR]")) return ERROR_STATUS;
if(line.contains("BUILD FAILURE")) return ERROR_STATUS;
if(line.contains("BUILD SUCCESS")) return OK_STATUS;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return ERROR_STATUS;
}
return ERROR_STATUS;
}