What I need to do is enter interactive mode of an application, and then start sending commands to it. The application is graphicsmagick. batch mode puts you in a state similar to how mysql works, where you can then send commands without the name of the application prefixing the command. Here is what I have done:
public Executor startBatchMode( OutputStream input ) {
Executor executor = new DefaultExecutor();
CommandLine cmdLine = new CommandLine( cmdPath );
cmdLine.addArgument( "batch" );
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
// AutoFlushingPumpStreamHandler: https://gist.github.com/martypitt/4653381
// AutoFlushingPumpStreamHandler streamHandler = new AutoFlushingPumpStreamHandler( System.out );
PumpStreamHandler streamHandler = new PumpStreamHandler( System.out );
streamHandler.setProcessInputStream(input );
executor.setStreamHandler( streamHandler );
try {
executor.execute( cmdLine, resultHandler );
streamHandler.start();
} catch ( IOException e ) {
e.printStackTrace();
}
return executor;
}
public static void main( String[] args ) throws IOException {
ExecWrapper exec = new ExecWrapper( "/usr/local/bin/gm" );
OutputStream stream = new PipedOutputStream( );
PrintWriter writer = new PrintWriter(stream);
Executor executor = exec.startBatchMode( stream );
for(int i=0;i<5;i++) {
writer.write( "convert /Users/latu/Desktop/400.jpg /Users/latu/Desktop/"+i+".png\n" );
writer.flush();
}
writer.close();
For the output, the application enters the batch mode, and then terminates. When used from terminal it will enter batch mode and then wait for a command from user until EOF character. I have tried adding commands to the writer before calling startBatchMode() but made no difference. Also tried moving things around quite a lot, but the outcome is always the same.
Any suggestions as to how I can make this work?
Update
Turns out this is very straight forward using Java runtime, and works like this:
private void runExec() throws IOException {
Process process = Runtime.getRuntime().exec( "/usr/local/bin/gm batch" );
OutputStream stdin = process.getOutputStream();
for ( int i = 0; i < 5; i++ ) {
String line = "convert /Users/latu/Desktop/400.jpg /Users/latu/Desktop/" + i + ".png" + "\n";
stdin.write( line.getBytes() );
stdin.flush();
}
}
Although I am hoping to stay with exec as it has some nice features which ideally I wouldn't need to reimplement.