We are using install4j version 6.1.5 and I need to install glassfish as a windows service. Therefore I read the documentation and tried to implement a windows service wrapper class to be able to create a service launcher for the installation to use this for the service actions. This is the code:
public class WindowsServiceWrapper implements Runnable {
private static volatile boolean keepRunning = true;
public static void main(String[] args) {
final Thread mainThread = Thread.currentThread();
String glassfishInstallDir = System.getProperty("installation.dir");
if (glassfishInstallDir == null || glassfishInstallDir.isEmpty()) {
System.err.println("Path not set to glassfish installation but required for startup the service.");
System.exit(1);
} else if (!new File(glassfishInstallDir).exists()) {
System.err.println("Path '" + glassfishInstallDir + "' do not exists. Startup of the service aborted.");
System.exit(1);
}
System.out.println("Starting the service.");
String asadminPath = glassfishInstallDir + "/bin/asadmin.bat";
CommandLine commandLine = CommandLine.parse(asadminPath + " start-domain");
runCommand(commandLine);
// register to jvm shutdown to handle service shutdown
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
keepRunning = false;
try {
System.out.println("Shutdown of the service was triggered.");
mainThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
new WindowsServiceWrapper(asadminPath).run();
}
private final String ASADMIN_PATH;
private WindowsServiceWrapper(String asadminPath) {
ASADMIN_PATH = asadminPath;
}
public void run() {
while (keepRunning) {
// nothing to do here but waiting for shutdown hook
}
System.out.println("Shutdown the service.");
CommandLine commandLine = CommandLine.parse(ASADMIN_PATH + " stop-domain");
runCommand(commandLine);
}
private static int runCommand(CommandLine cmdLine) {
DefaultExecutor executor = new DefaultExecutor();
int exitCode;
try {
exitCode = executor.execute(cmdLine);
} catch (IOException e) {
System.out.println("Error occured during command execution: " + cmdLine.toString());
e.printStackTrace();
exitCode = 1;
keepRunning = false;
}
return exitCode;
}
}
To start and stop the glassfish server I used the commons-exec library from Apache. This code works well to install and start the service as well as uninstall the service. There is only one thing left: during the startup of the service I need to wait until the glassfish startup has finished completely and the commons-exec call will be done. It's needed to go ahead with dependent installation steps. For now the "Start Service" action returns immediately. I guess the main method of my wrapper class is instantiated as an unforked thread, is it? So is there a recommended way how to handle things like this?