List of usage examples for java.lang ProcessBuilder redirectErrorStream
boolean redirectErrorStream
To view the source code for java.lang ProcessBuilder redirectErrorStream.
Click Source Link
From source file:com.bekwam.resignator.commands.KeytoolCommand.java
public List<KeystoreEntry> findKeystoreEntries(String keytoolExec, String keystore, String storepass) throws CommandExecutionException { List<KeystoreEntry> entries = new ArrayList<>(); Preconditions.checkNotNull(keytoolExec); Preconditions.checkNotNull(keystore); Preconditions.checkNotNull(storepass); File outputFile = null;/*from ww w .ja va 2 s . co m*/ try { String[] cmdAndArgs = { keytoolExec, "-keystore", keystore, "-storepass", storepass, "-list" }; File resignatorDir = new File(System.getProperty("user.home"), ".resignator"); String outputFileName = OUTPUTFILE_PREFIX + StringUtils.lowerCase(RandomStringUtils.randomAlphabetic(12)) + OUTPUTFILE_SUFFIX; outputFile = new File(resignatorDir, outputFileName); ProcessBuilder pb = new ProcessBuilder(cmdAndArgs); pb.redirectErrorStream(false); pb.redirectOutput(outputFile); Process p = pb.start(); boolean exitted = p.waitFor(TIMEOUT_SECS, TimeUnit.SECONDS); if (exitted) { if (p.exitValue() == 0) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile))); entries.addAll(parseKeystoreEntries(br)); br.close(); } else { String firstLine = ""; if (outputFile != null && outputFile.exists()) { BufferedReader br = new BufferedReader(new FileReader(outputFile)); firstLine = br.readLine(); br.close(); } if (logger.isErrorEnabled()) { logger.error("error running exec={}; firstLine={}", keytoolExec, firstLine); } throw new CommandExecutionException( "Command '" + keytoolExec + "' failed to run" + newLine + firstLine); } } else { if (logger.isErrorEnabled()) { logger.error("command '" + keytoolExec + "' timed out"); } throw new CommandExecutionException("Command '" + keytoolExec + "' timed out"); } } catch (Exception exc) { // includes interrupted exception if (logger.isErrorEnabled()) { logger.error("error running keytool", exc); } throw new CommandExecutionException("Error running keytool command" + newLine + exc.getMessage()); } finally { if (outputFile != null) { outputFile.delete(); } } return entries; }
From source file:org.apache.nutch.storage.TestGoraStorage.java
/** * Tests multiple processes reading and writing to the same store backend, * this is to simulate a multi process Nutch environment (i.e. MapReduce). * /* ww w . j a v a2 s. c om*/ * @throws Exception */ @Test public void testMultiProcess() throws Exception { // create and start a hsql server, a stand-alone (memory backed) db // (important: a stand-alone server should be used because simple // file based access i.e. jdbc:hsqldb:file is NOT process-safe.) Server server = new Server(); server.setDaemon(true); server.setSilent(true); // disables LOTS of trace final String className = getClass().getName(); String dbName = "test"; server.setDatabasePath(0, "mem:" + dbName); server.setDatabaseName(0, dbName); server.start(); //create the store so that the tests can start right away StorageUtils.createWebStore(conf, String.class, WebPage.class); // create a fixed thread pool int numThreads = 4; ExecutorService pool = Executors.newFixedThreadPool(numThreads); // spawn multiple processes, each thread spawns own process Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(); for (int i = 0; i < numThreads; i++) { tasks.add(new Callable<Integer>() { @Override public Integer call() { try { String separator = System.getProperty("file.separator"); String classpath = System.getProperty("java.class.path"); String pathSeparator = System.getProperty("path.separator"); // connect local sql service classpath = "./src/testprocess" + pathSeparator + classpath; String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; ProcessBuilder processBuilder = new ProcessBuilder(path, "-cp", classpath, className); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); InputStream in = process.getInputStream(); int exit = process.waitFor(); //print the output of the process System.out.println("===Process stream for " + Thread.currentThread() + "\n" + IOUtils.toString(in) + "===End of process stream."); in.close(); // process should exit with zero code return exit; } catch (Exception e) { e.printStackTrace(); // this will fail the test return 1; } } }); } // submit them at once List<Future<Integer>> results = pool.invokeAll(tasks); // check results for (Future<Integer> result : results) { assertEquals(0, (int) result.get()); } //stop db server.stop(); }
From source file:org.lesscss.mojo.NodeJsLessCompiler.java
private String compile(String input) throws LessException, IOException, InterruptedException { long start = System.currentTimeMillis(); File inputFile = File.createTempFile("lessc-input-", ".less"); FileOutputStream out = new FileOutputStream(inputFile); IOUtils.write(input, out);// w w w.j a va 2 s .co m out.close(); File outputFile = File.createTempFile("lessc-output-", ".css"); File lesscJsFile = new File(tempDir, "lessc.js"); ProcessBuilder pb = new ProcessBuilder("node", lesscJsFile.getAbsolutePath(), inputFile.getAbsolutePath(), outputFile.getAbsolutePath(), String.valueOf(compress)); pb.redirectErrorStream(true); Process process = pb.start(); IOUtils.copy(process.getInputStream(), System.out); int exitStatus = process.waitFor(); FileInputStream in = new FileInputStream(outputFile); String result = IOUtils.toString(in); in.close(); if (!inputFile.delete()) { log.warn("Could not delete temp file: " + inputFile.getAbsolutePath()); } if (!outputFile.delete()) { log.warn("Could not delete temp file: " + outputFile.getAbsolutePath()); } if (exitStatus != 0) { throw new LessException(result, null); } log.debug("Finished compilation of LESS source in " + (System.currentTimeMillis() - start) + " ms."); return result; }
From source file:org.opencastproject.videoeditor.ffmpeg.FFmpegEdit.java
private String run(List<String> params) { BufferedReader in = null;//from w w w .j av a2s .co m Process encoderProcess = null; try { params.add(0, binary); logger.info("executing command: " + StringUtils.join(params, " ")); ProcessBuilder pbuilder = new ProcessBuilder(params); pbuilder.redirectErrorStream(true); encoderProcess = pbuilder.start(); in = new BufferedReader(new InputStreamReader(encoderProcess.getInputStream())); String line; int n = 5; while ((line = in.readLine()) != null) { if (n-- > 0) logger.info(line); } // wait until the task is finished encoderProcess.waitFor(); int exitCode = encoderProcess.exitValue(); if (exitCode != 0) { throw new Exception("Ffmpeg exited abnormally with status " + exitCode); } } catch (Exception ex) { logger.error("VideoEditor ffmpeg failed", ex); return ex.toString(); } finally { IoSupport.closeQuietly(in); IoSupport.closeQuietly(encoderProcess); } return null; }
From source file:com.quartzdesk.executor.core.job.LocalCommandExecutorJob.java
@Override protected void executeJob(JobExecutionContext context) throws JobExecutionException { log.debug("Inside job: {}", context.getJobDetail().getKey()); JobDataMap jobDataMap = context.getMergedJobDataMap(); // command/* ww w . ja va 2s .c om*/ String command = jobDataMap.getString(JDM_KEY_COMMAND); if (command == null) { throw new JobExecutionException("Missing required '" + JDM_KEY_COMMAND + "' job data map parameter."); } // command arguments (optional) String commandArgs = jobDataMap.getString(JDM_KEY_COMMAND_ARGS); // command work directory (optional) String commandWorkDir = jobDataMap.getString(JDM_KEY_COMMAND_WORK_DIR); File commandWorkDirFile = null; if (commandWorkDir != null) { commandWorkDirFile = new File(commandWorkDir); if (!commandWorkDirFile.exists() || !commandWorkDirFile.isDirectory()) { throw new JobExecutionException( "Command work directory '" + commandWorkDirFile.getAbsolutePath() + "' specified in the '" + JDM_KEY_COMMAND_WORK_DIR + "' job data map parameter does not exist."); } } // execute the command List<String> commandLine = prepareCommandLine(command, commandArgs); ProcessBuilder processBuilder = new ProcessBuilder(commandLine); processBuilder.redirectErrorStream(true); // set the process work directory if specified; otherwise the default work directory is used if (commandWorkDirFile != null) { processBuilder.directory(commandWorkDirFile); } // we could possibly set the process environment here //processBuilder.environment() try { log.info("Executing local command using command line: {}", commandLine); ExecutorService standardOutputExecutor = getProcessOutputExecutor(context); Process process = processBuilder.start(); StandardOutputReaderCallable stdOutCallable = new StandardOutputReaderCallable( process.getInputStream()); Future<String> stdOutDataFuture = standardOutputExecutor.submit(stdOutCallable); int exitCode = process.waitFor(); // wait for the process to finish log.debug("Local command finished with exit code: {}", exitCode); context.setResult(exitCode); // exit code is used as the job's execution result (visible in the QuartzDesk GUI) try { String output = stdOutDataFuture.get(); if (StringUtils.isBlank(output)) { log.info("Local command produced no output."); } else { log.info("Local command produced the following output:{}{}", CommonConst.NL, output); } } catch (Exception e) // CancellationException, ExecutionException, InterruptedException { log.warn("Error getting process data.", e); } // if result != 0, we typically want to throw JobExecutionException indicating a job execution failure if (exitCode != 0) { throw new JobExecutionException("Command finished with non-zero exit code: " + exitCode); } } catch (IOException e) { throw new JobExecutionException("Error starting command process.", e); } catch (InterruptedException e) { throw new JobExecutionException("Command process has been interrupted.", e); } }
From source file:functionaltests.matlab.AbstractMatlabTest.java
protected ProcessBuilder initCommand(String testName, int nb_iter) throws Exception { ProcessBuilder pb = new ProcessBuilder(); pb.directory(mat_tb_home);/* w w w. j a v a 2 s .c o m*/ pb.redirectErrorStream(true); int runAsMe = 0; if (System.getProperty("proactive.test.runAsMe") != null) { runAsMe = 1; } logFile = new File(mat_tb_home, testName + ".log"); if (logFile.exists()) { logFile.delete(); } // If no property specified for matlab exe suppose it's in the PATH String matlabExe = System.getProperty("matlab.bin.path", "matlab"); // Build the matlab command that will run the test String matlabCmd = String.format("addpath('%s');", this.test_home); if (System.getProperty("disable.popup") != null) { matlabCmd += "PAoptions('EnableDisconnectedPopup', false);"; } matlabCmd += getMatlabFunction(nb_iter, testName, runAsMe); return pb.command(matlabExe, "-nodesktop", "-nosplash", "-logfile", logFile.getAbsolutePath(), "-r", matlabCmd); }
From source file:org.jellycastle.maven.Maven.java
/** * Run new Maven os process with given arguments and commands. *//*from w w w . j av a 2s. c o m*/ public void execute() { Process process = null; BufferedReader br = null; try { ProcessBuilder processBuilder = getProcessBuilder(); processBuilder.redirectErrorStream(true); log.info("Starting process: " + processBuilder.command()); process = processBuilder.start(); // Read output br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } process.waitFor(); } catch (Exception e) { throw new RuntimeException(e); } finally { close(br); destroyProcess(process); } }
From source file:abs.backend.erlang.ErlangTestDriver.java
/** * Executes mainModule/*w ww .j a va 2 s. c om*/ * * We replace the run script by a new version, which will write the Result * to STDOUT Furthermore to detect faults, we have a Timeout process, which * will kill the runtime system after 2 seconds */ private String run(File workDir, String mainModule) throws Exception { String val = null; File runFile = new File(workDir, "run"); Files.write(RUN_SCRIPT, runFile, Charset.forName("UTF-8")); runFile.setExecutable(true); ProcessBuilder pb = new ProcessBuilder(runFile.getAbsolutePath(), mainModule); pb.directory(workDir); pb.redirectErrorStream(true); Process p = pb.start(); Thread t = new Thread(new TimeoutThread(p)); t.start(); // Search for result BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); while (true) { String line = br.readLine(); if (line == null) break; if (line.startsWith("RES=")) val = line.split("=")[1]; } int res = p.waitFor(); t.interrupt(); if (res != 0) return null; return val; }
From source file:com.migratebird.script.runner.impl.Application.java
protected ProcessBuilder createProcessBuilder(List<String> commandWithArguments) { ProcessBuilder processBuilder = new ProcessBuilder(commandWithArguments); Map<String, String> processEnvironment = processBuilder.environment(); processEnvironment.putAll(environmentVariables); processBuilder.redirectErrorStream(true); return processBuilder; }
From source file:org.abs_models.backend.erlang.ErlangTestDriver.java
/** * Executes mainModule/*from ww w .j a v a 2s . c o m*/ * * To detect faults, we have a Timeout process which will kill the * runtime system after 10 seconds */ private String run(File workDir, String mainModule) throws Exception { String val = null; String runFileName = ErlangBackend.isWindows() ? "run.bat" : "run"; File runFile = new File(workDir, runFileName); ProcessBuilder pb = new ProcessBuilder(runFile.getAbsolutePath(), mainModule); pb.directory(workDir); pb.redirectErrorStream(true); Process p = pb.start(); Thread t = new Thread(new TimeoutThread(p)); t.start(); // Search for result BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); while (true) { String line = br.readLine(); if (line == null) break; if (line.startsWith("RES=")) // see `genCode' above val = line.split("=")[1]; } int res = p.waitFor(); t.interrupt(); if (res != 0) return null; return val; }