Groovy で、外部コマンドの実行
あまり Groovy ぽくないかな?
// コマンドと引数の組立 ProcessBuilder builder = new ProcessBuilder( "ping", "-n", "2", "localhost" ) ; // 作業ディレクトリの指定 ( デフォルトで Java IO の作業ディレクトリ を指定) File workingDirectory = new File( System.getProperty("java.io.tmpdir" ) ) ; builder.directory( workingDirectory ) ; // 実行して、結果を取得 Process process = builder.start(); process.waitForOrKill( 10 * 1000 ); // 10秒のコマンド実行タイムアウトの設定 int exitValue = process.exitValue(); // 終了コード 取得 // 実行結果の判定と後処理 if(exitValue == 0 ) { // 成功時の処理 // 実行内容を表示 (ロギングされる?) println ( "SUCCESS " + new Date() ); println( builder.command() ) ; println( process.text ) ; // 実行結果 } else { // 失敗時の処理 // 実行コマンド、ディレクトリ、環境変数を、エラーメッセージとして組み立てる user = System.getProperty( "user.name" ) ; command = builder.command() ; workingDirectory = builder.directory() ; environment = builder.environment(); message = "\nuser=" + user ; message += "\nexit code=" + exitValue; message += "\ncommand=" + command; message += "\ndirectory=" + workingDirectory; message += "\nEnvironment:" ; for( each in environment ) { message += "\n" + each; } // 例外をスロー throw new Exception( message ); }