After a few days of research and trial and error got the function of restarting tomcat from our web app working.
Essntially, you need to create your own script that kicks off the tomcat script in the background (see step# 1 below. This script will be called from your web app through the Process object (see step# 2 below). The gotchas that bit us are mentioned in the method's javadoc.
Here's are the steps:
(1) Create a shell script that calls the tomcat script in the background:
#! /bin/sh
# This script simply calls the tomcat script in the background using nohup ... &
echo Calling tomcat shell script in background...
nohup 2>&1 /your/tomcat/shell/script.sh $1 > /your/tomcat/shell/script.log &
echo Done calling the tocat shell script
(2) In the web app, the following method is called:
/**
* Run shell script.
* <p>
* CAUTION: The following could cause problems:
* <ol>
* 1) Calling process.waitFor(). This call blocks the thread until the
* process is terminated. This could be an issue when calling the script to
* restart tomcat: the JVM is waiting for the process to finish
* before it stops while the process is waiting for the JVM to stop.
* <ol>
* 2) Redirecting the process's streams (which could be obtained by calling
* process.getInputStream() and process.getErrorStream()) to a separate
* thread. This could be an issue when calling the script to restart: JVM is
* waiting for the thread to terminate while the thread is awaiting for more
* input to come through the stream.
* <ol>
* 3) Calling the actual script directly. This could be a similar issue to
* (1) above when calling the script to restart. Better approach is to have
* another script that executes the main script in the background (using
* nohup ... &).
*
*/
private void kickOffProcess(String scriptOption) {
String executeScript = null;
try {
File workingDir = new File(WORKING_DIRECTORY_PATH);
// This script calls the tomcat script in the background
executeScript = "/your/shell/script.sh";
logger.info("Executing the following script: [" + executeScript
+ "] ");
// Call the shell script
ProcessBuilder processBuilder = new ProcessBuilder(executeScript,
scriptOption);
// processBuilder.redirectErrorStream(true);
processBuilder.directory(workingDir);
Process process = processBuilder.start();
int exitValue = process.exitValue();
if (exitValue != 0) {
logger.error("Script failed to execute. " + "exitValue["
+ exitValue + "] ");
}
logger.info("Done with calling the script. " + "exitValue["
+ exitValue + "] ");
} catch (IOException e) {
String errorMessage = "Failed with IOException trying to run the script. "
+ "executeScript[" + executeScript + "] ";
logger.error(errorMessage, e);
}
}