Chapter 5. Deploying pre-configured databases 229
Creating the database from Java
Since there is no call interface for Java, we use a script to generate the
database. The script is named createdb.cmd — see 5.6.2, “Shell scripts” on
page 252 for details. Example 5-10 shows how to execute a script from a Java
application.
Example 5-10 Executing a script from within Java
//---------------------------------------------------------------------------
// Step 1 : executing the script
//---------------------------------------------------------------------------
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmdFilename);
//---------------------------------------------------------------------------
// Step 2 : catching stderr and stdout
//---------------------------------------------------------------------------
OutputStreamCatcher outputCatcher =
new OutputStreamCatcher(proc.getInputStream());
ErrorStreamCatcher errorCatcher =
new ErrorStreamCatcher(proc.getErrorStream());
// Start the errorcatcher and the outputcatcher
errorCatcher.start();
outputCatcher.start();
//---------------------------------------------------------------------------
// Step 3 : retreive the return code
//---------------------------------------------------------------------------
int exitValue = proc.waitFor();
System.out.println( "Exit code : " + exitValue);
Step 1:
Executing an external program, like a script, is straightforward in Java. The
class Runtime is used in Java to interact with the runtime environment. This
class provide the exec method to start the external applications. In our case,
the external application is the script file createdb.bat. The exec method
returns reference to a process object which gives us access to the exit code,
standard output, and so on.
Step 2:
We have to pay attention to the output from the script file. If there is a lot of
output from the script, the default buffer used by the process object can run
full, which causes the process to hang. To avoid this, we create a couple of
buffer streams to collect the output. Additional benefit from this is that the
output from the process is logged.