Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a mvn command from a java program?

Tags:

java

maven

I am building a Java program for automating a procedure in my server side. Normally I cd to Desktop/GIT/ and use this maven command "mvn integration-test -DskipTests -P interactive -e".

I am building a java program and I am trying to run that command line but so far I wasn't successful.

So far, here is the code:

public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub 

Process theProcess = null;


try
  {
      theProcess = Runtime.getRuntime().exec("mvn integration-test -DskipTests -P interactive -e");
  }
 catch(IOException e)
  {
     System.err.println("Error on exec() method");
     e.printStackTrace();  
  }

// read from the called program's standard output stream
  try
  {
     inStream = new BufferedReader(new InputStreamReader( theProcess.getInputStream()));  
     System.out.println(inStream.readLine());
  }
  catch(IOException e)
  {
     System.err.println("Error on inStream.readLine()");
     e.printStackTrace();  
  }

break;

    }

}

in.close();
}
like image 711
phedon rousou Avatar asked Jun 21 '26 03:06

phedon rousou


1 Answers

You should check out maven embedder; which is exactly the tool which you should use in case of embedding maven.


OK apparently maven embedder is not supported any more. Probably you can still get it working though, but I rather created a small sample for you which should work. Of course, replace the path for Maven:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Q {

public static void main(String[] args) throws IOException, InterruptedException {

    Process p = null;

    try {
        p = Runtime.getRuntime().exec("C:/Applications/apache-maven-3.0.3/bin/mvn.bat integration-test -DskipTests -P interactive -e");
    } catch (IOException e) {
        System.err.println("Error on exec() method");
        e.printStackTrace();
    }

    copy(p.getInputStream(), System.out);
    p.waitFor();

}

static void copy(InputStream in, OutputStream out) throws IOException {
    while (true) {
        int c = in.read();
        if (c == -1)
            break;
        out.write((char) c);
    }
}
}
like image 165
abalogh Avatar answered Jun 24 '26 12:06

abalogh