I'm trying to execute the Main method within a class in a jar file by using Java's ProcessBuilder from a servlet. I need to run this in a separate process due to other dependencies.
I'm getting the following exception, so I guess that I am not correctly passing the package and Main method name (com.test.Main) in the arguments array. I am not sure how to do this correctly.
I'd appreciate any suggestions. Thanks.
ERROR -- java.lang.NoClassDefFoundError: com/test/Main ERROR -- Caused by: java.lang.ClassNotFoundException: com.test.Main ERROR -- at java.net.URLClassLoader$1.run(URLClassLoader.java:202) ERROR -- at java.security.AccessController.doPrivileged(Native Method) ERROR -- at java.net.URLClassLoader.findClass(URLClassLoader.java:190) ERROR -- at java.lang.ClassLoader.loadClass(ClassLoader.java:307) ERROR -- at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
ERROR -- at java.lang.ClassLoader.loadClass(ClassLoader.java:248) ERROR -- Could not find the main class: com.test.Main. Program will exit. ERROR -- Exception in thread "main"
Here's my code.
public int runProcessBuilder() throws IOException, InterruptedException{
{
// Get absolute path
File dir_location = new File(".");
String appPath = dir_location.getCanonicalPath() + "\\Tomcat 6.0\\webapps\\TestServer\\WEB-INF";
// Args to run
String[] argList = {"java.exe","-Djava.library.path="+appPath+"\\lib","-classpath",appPath+"\\lib\\test.jar","com.test.Main","-pTEST_ARG","123"};
// Create ProcessBuilder
ProcessBuilder builder = new ProcessBuilder(argList);
// Set Environment variable(s)
Map<String, String> environ = builder.environment();
environ.put("TEST_HOME", appPath);
// Set java directory - TODO: use system property
String java_exe = "C:\\Program Files\\Java\\jdk1.6.0_18\\bin";
builder.directory(new File(java_exe));
// Start Process
final Process process = builder.start();
// Read error stream
StreamReader errorReader = new StreamReader(process
.getErrorStream(), "ERROR");
// Read input stream
StreamReader outputReader = new StreamReader(process
.getInputStream(), "OUTPUT");
// Start both reader threads
errorReader.start();
outputReader.start();
// Wait for process end and get Exit Code
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
return exitCode;
}
}