List of usage examples for java.lang ProcessBuilder ProcessBuilder
public ProcessBuilder(String... command)
From source file:com.clustercontrol.util.CommandExecutor.java
public Process execute() throws HinemosUnknown { // workaround for JVM(Windows) Bug // Runtime#exec is not thread safe on Windows. try {//from w ww .jav a2 s .c o m synchronized (_runtimeExecLock) { ProcessBuilder pb = new ProcessBuilder(_command); // ???"_JAVA_OPTIONS"???? pb.environment().remove("_JAVA_OPTIONS"); for (Map.Entry<String, String> entry : envMap.entrySet()) { pb.environment().put(entry.getKey(), entry.getValue()); } process = pb.start(); } } catch (Exception e) { log.warn("command executor failure. (command = " + _commandLine + ") " + e.getMessage(), e); throw new HinemosUnknown(e.getMessage()); } return process; }
From source file:bjerne.gallery.service.impl.VideoConversionServiceImpl.java
@Override public void convertVideo(File origVideo, File newVideo, String conversionMode) throws IOException { long startTime = System.currentTimeMillis(); if (newVideo.exists()) { LOG.debug("{} already exists. Trying to delete.", newVideo); newVideo.delete();// ww w. j ava2 s.c o m } if (!newVideo.getParentFile().exists()) { boolean dirsCreated = newVideo.getParentFile().mkdirs(); if (!dirsCreated) { String errorMessage = String.format("Could not create all dirs for %s", newVideo); LOG.error(errorMessage); throw new IOException(errorMessage); } } ProcessBuilder pb = new ProcessBuilder(generateCommandParamList(origVideo, newVideo, conversionMode)); Process pr = null; Thread currentThread = Thread.currentThread(); try { LOG.debug("Adding current thread: {}", currentThread); registerThread(currentThread); pr = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getInputStream())); while (reader.ready()) { Thread.sleep(100); LOG.info("One line: {}", reader.readLine()); } boolean waitResult = pr.waitFor(maxWaitTimeSeconds, TimeUnit.SECONDS); if (!waitResult) { String errorMessage = String.format( "Waiting for video conversion exceeded maximum threshold of %s seconds", maxWaitTimeSeconds); LOG.error(errorMessage); cleanupFailure(pr, newVideo); throw new IOException(errorMessage); } long duration = System.currentTimeMillis() - startTime; LOG.debug("Time in milliseconds to resize {}: {}", newVideo.toString(), duration); } catch (InterruptedException ie) { cleanupFailure(pr, newVideo); LOG.error("Was interrupted while waiting for conversion. Throwing IOException"); throw new IOException(ie); } finally { unregisterThread(currentThread); } }
From source file:com.netscape.cms.profile.constraint.ExternalProcessConstraint.java
public void validate(IRequest request, X509CertInfo info) throws ERejectException { CMS.debug("About to execute command: " + this.executable); ProcessBuilder pb = new ProcessBuilder(this.executable); // set up process environment Map<String, String> env = pb.environment(); for (String k : envVars.keySet()) { String v = request.getExtDataInString(envVars.get(k)); if (v != null) env.put(k, v);//from w w w.jav a 2s .co m } for (String k : extraEnvVars.keySet()) { String v = request.getExtDataInString(extraEnvVars.get(k)); if (v != null) env.put(k, v); } Process p; String stdout = ""; String stderr = ""; boolean timedOut; try { p = pb.start(); timedOut = !p.waitFor(timeout, TimeUnit.SECONDS); if (timedOut) p.destroyForcibly(); else stdout = IOUtils.toString(p.getInputStream()); stderr = IOUtils.toString(p.getErrorStream()); } catch (Throwable e) { String msg = "Caught exception while executing command: " + this.executable; CMS.debug(msg); CMS.debug(e); throw new ERejectException(msg, e); } if (timedOut) throw new ERejectException("Request validation timed out"); int exitValue = p.exitValue(); CMS.debug("ExternalProcessConstraint: exit value: " + exitValue); CMS.debug("ExternalProcessConstraint: stdout: " + stdout); CMS.debug("ExternalProcessConstraint: stderr: " + stderr); if (exitValue != 0) throw new ERejectException(stdout); }
From source file:com.cisco.dvbu.ps.common.util.ScriptExecutor.java
public int executeCommand(String errorFile) { int exitValue = -99; String prefix = "ScriptExecutor::"; String command = ""; try {/*from www . ja va 2 s. c o m*/ // Print out the command and execution directory for (int i = 0; i < scriptArgsList.size(); i++) { command = command + scriptArgsList.get(i) + " "; } if (logger.isDebugEnabled()) { logger.debug(prefix + "-------------------------------------------------"); logger.debug(prefix + "Command: " + CommonUtils.maskCommand(command)); logger.debug(prefix + "Exec Dir: " + execFromDir.toString()); } // Build a new process to execute ProcessBuilder pb = new ProcessBuilder(scriptArgsList); // Setup the environment variables Map<String, String> env = pb.environment(); for (int i = 0; i < envList.size(); i++) { String envVar = envList.get(i).toString(); StringTokenizer st = new StringTokenizer(envVar, "="); if (st.hasMoreTokens()) { String property = st.nextToken(); String propertyVal = ""; try { propertyVal = st.nextToken(); } catch (Exception e) { } env.put(property, propertyVal); if (logger.isDebugEnabled()) { logger.debug(prefix + "Env Var: " + CommonUtils.maskCommand(envVar)); } } } if (logger.isDebugEnabled()) { logger.debug(prefix + "-------------------------------------------------"); } // Setup up the execute from directory File execDir = new File(execFromDir); pb.directory(execDir); if (logger.isDebugEnabled()) { logger.debug(""); logger.debug("ProcessBuilder::pb.command: " + CommonUtils.maskCommand(pb.command().toString())); logger.debug("ProcessBuilder::pb.directory: " + pb.directory().toString()); logger.debug("ProcessBuilder::pb.directory.getAbsolutePath: " + pb.directory().getAbsolutePath()); logger.debug("ProcessBuilder::pb.directory.getCanonicalPath: " + pb.directory().getCanonicalPath()); logger.debug(""); logger.debug("ProcessBuilder::pb.environment: " + CommonUtils.maskCommand(pb.environment().toString())); logger.debug(prefix + "-------------------------------------------------"); logger.debug(""); } // Execute the command Process process = pb.start(); OutputStream stdOutput = process.getOutputStream(); InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); inputStreamHandler = new ScriptStreamHandler(inputStream, stdOutput); errorStreamHandler = new ScriptStreamHandler(errorStream); inputStreamHandler.start(); errorStreamHandler.start(); exitValue = process.waitFor(); if (logger.isDebugEnabled()) { logger.debug(prefix + "exitValue for process.waitFor is: " + exitValue); } if (exitValue > 0) { logger.error("Error executing command=" + CommonUtils.maskCommand(command)); logger.error("Error=" + CommonUtils.maskCommand(getStandardErrorFromCommand().toString())); } else { if (logger.isInfoEnabled()) { logger.info("Successfully executed command:\n" + CommonUtils.maskCommand(command)); logger.info("Output:\n" + getStandardOutputFromCommand().toString()); } } } catch (IOException e) { CompositeLogger.logException(e, e.getMessage()); throw new CompositeException(e); } catch (InterruptedException e) { CompositeLogger.logException(e, e.getMessage()); throw new CompositeException(e); } return exitValue; }
From source file:dk.netarkivet.wayback.aggregator.IndexAggregator.java
/** * Calls the Unix sort command with the options <code>$filesNames -o * $outputfile -T WaybackSettings#WAYBACK_AGGREGATOR_TEMP_DIR. * <p>/* ww w.j a v a 2 s.c o m*/ * Sets the LC_ALL environment variable before making the call. * * @param files The files to merge and sort * @param outputFile The resulting sorted file * @param additionalArgs A list af extra arguments, which (if different from null) are added to the sort call.<p> * Note: If any of the args contain a whitespace the call will fail. */ private void processFiles(File[] files, File outputFile, List<String> additionalArgs) { if (files.length == 0) { // Empty file list will cause sort to wait for further input, // and the call will therefore never return return; } Process p = null; try { List<String> inputFileList = new LinkedList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].exists() && files[i].isFile()) { inputFileList.add(files[i].getCanonicalPath()); } else { log.warn("File " + files[i] + " doesn't exist or isn't a regular file, " + "dropping from list of files to " + "sort and merge"); } } List<String> cmd = new LinkedList<String>(); // Prepare to run the unix sort command, see sort manual page for // details cmd.add("sort"); cmd.addAll(inputFileList); cmd.add("-o"); cmd.add(outputFile.getCanonicalPath()); cmd.add("-T"); cmd.add(Settings.get(WaybackSettings.WAYBACK_AGGREGATOR_TEMP_DIR)); if (additionalArgs != null && !additionalArgs.isEmpty()) { for (String argument : additionalArgs) { ArgumentNotValid.checkTrue(argument.indexOf(' ') == -1, "The argument '" + argument + "' contains spaces, this isn't allowed "); } cmd.addAll(additionalArgs); } ProcessBuilder pb = new ProcessBuilder(cmd); // Reset all locale definitions pb.environment().put("LC_ALL", "C"); // Run the command in the user.dir directory pb.directory(new File(System.getProperty("user.dir"))); p = pb.start(); p.waitFor(); if (p.exitValue() != 0) { log.error("Failed to sort index files, sort exited with " + "return code " + p.exitValue()); } } catch (Exception e) { log.error("Failed to aggregate indexes ", e); } }
From source file:com.blackberry.logtools.LogTools.java
public String parseDate(String time) throws Exception { String parsedTime = time;/*from ww w.j a v a 2 s .c o m*/ if (Pattern.matches("[0-9]+", time) == false) { String[] dateCmd = { "/bin/sh", "-c", "date -d '" + time + "' +%s" }; ProcessBuilder pBuilder = new ProcessBuilder(dateCmd); pBuilder.redirectErrorStream(true); Process p = pBuilder.start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); parsedTime = br.readLine() + "000"; if (parsedTime.contains("invalid date")) { logConsole(true, true, error, "Could not parse start time, invalid date."); System.exit(1); } } else if (time.length() != 13) { logConsole(true, true, error, "Could not parse start time."); logConsole(true, true, error, "Epoch date time must be in miliseconds. (13 digits)"); System.exit(1); } return parsedTime; }
From source file:com.photon.phresco.plugins.xcode.Instrumentation.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("Instrumentation command" + command); try {//from ww w .ja v a 2s .c o m outputFolder = project.getBasedir().getAbsolutePath(); File f = new File(outputFolder); File files[] = f.listFiles(); for (File file : files) { if (file.getName().startsWith("Run 1") || file.getName().endsWith(".trace")) { FileUtils.deleteDirectory(file); } } } catch (IOException e) { getLog().error(e); } Runnable runnable = new Runnable() { public void run() { ProcessBuilder pb = new ProcessBuilder(command); //device takes the highest priority if (StringUtils.isNotBlank(deviceid)) { pb.command().add("-w"); pb.command().add(deviceid); } pb.command().add("-t"); pb.command().add(template); if (StringUtils.isNotBlank(appPath)) { pb.command().add(appPath); } else { getLog().error("Application should not be empty"); } if (StringUtils.isNotBlank(script)) { pb.command().add("-e"); pb.command().add("UIASCRIPT"); String scriptPath = project.getBasedir().getAbsolutePath() + File.separator + script; pb.command().add(scriptPath); } else { getLog().error("script is empty"); } pb.command().add("-e"); pb.command().add("UIARESULTSPATH"); pb.command().add(outputFolder); // Include errors in output pb.redirectErrorStream(true); getLog().info("List of commands" + pb.command()); Process child; try { child = pb.start(); // Consume subprocess output and write to stdout for debugging InputStream is = new BufferedInputStream(child.getInputStream()); int singleByte = 0; while ((singleByte = is.read()) != -1) { System.out.write(singleByte); } } catch (IOException e) { getLog().error(e); } } }; Thread t = new Thread(runnable, "iPhoneSimulator"); t.start(); getLog().info("Thread started"); try { //Thread.sleep(5000); t.join(); t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } preparePlistResult(); generateXMLReport(project.getBasedir().getAbsolutePath() + File.separator + plistResult); }
From source file:edu.cornell.med.icb.R.RUtils.java
/** * Can be used to start a rserve instance. * @param threadPool The ExecutorService used to start the Rserve process * @param rServeCommand Full path to command used to start Rserve process * @param host Host where the command should be sent * @param port Port number where the command should be sent * @param username Username to send to the server if authentication is required * @param password Password to send to the server if authentication is required * @return The return value from the Rserve instance */// w w w.jav a2 s . c o m static Future<Integer> startup(final ExecutorService threadPool, final String rServeCommand, final String host, final int port, final String username, final String password) { if (LOG.isInfoEnabled()) { LOG.info("Attempting to start Rserve on " + host + ":" + port); } return threadPool.submit(new Callable<Integer>() { public Integer call() throws IOException { final List<String> commands = new ArrayList<String>(); // if the host is not local, use ssh to exec the command if (!"localhost".equals(host) && !"127.0.0.1".equals(host) && !InetAddress.getLocalHost().equals(InetAddress.getByName(host))) { commands.add("ssh"); commands.add(host); } // TODO - this will fail when spaces are in the the path to the executable CollectionUtils.addAll(commands, rServeCommand.split(" ")); commands.add("--RS-port"); commands.add(Integer.toString(port)); final String[] command = commands.toArray(new String[commands.size()]); LOG.debug(ArrayUtils.toString(commands)); final ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); final Process process = builder.start(); BufferedReader br = null; try { final InputStream is = process.getInputStream(); final InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { if (LOG.isDebugEnabled()) { LOG.debug(host + ":" + port + "> " + line); } } process.waitFor(); if (LOG.isInfoEnabled()) { LOG.info("Rserve on " + host + ":" + port + " terminated"); } } catch (InterruptedException e) { LOG.error("Interrupted!", e); process.destroy(); Thread.currentThread().interrupt(); } finally { IOUtils.closeQuietly(br); } final int exitValue = process.exitValue(); if (LOG.isInfoEnabled()) { LOG.info("Rserve on " + host + ":" + port + " returned " + exitValue); } return exitValue; } }); }
From source file:com.salsaw.msalsa.clustal.ClustalOmegaManager.java
@Override public void callClustal(String clustalPath, ClustalFileMapper clustalFileMapper) throws IOException, InterruptedException, SALSAException { // Get program path to execute List<String> clustalProcessCommands = new ArrayList<String>(); clustalProcessCommands.add(clustalPath); // Create the name of output files String inputFileName = FilenameUtils.getBaseName(clustalFileMapper.getInputFilePath()); String inputFileFolderPath = FilenameUtils.getFullPath(clustalFileMapper.getInputFilePath()); Path alignmentFilePath = Paths.get(inputFileFolderPath, inputFileName + "-aln.fasta"); Path guideTreeFilePath = Paths.get(inputFileFolderPath, inputFileName + "-tree.dnd"); // Set inside file mapper clustalFileMapper.setAlignmentFilePath(alignmentFilePath.toString()); clustalFileMapper.setGuideTreeFilePath(guideTreeFilePath.toString()); setClustalFileMapper(clustalFileMapper); // Create clustal omega data generateClustalArguments(clustalProcessCommands); // http://www.rgagnon.com/javadetails/java-0014.html ProcessBuilder builder = new ProcessBuilder(clustalProcessCommands); builder.redirectErrorStream(true);//from w w w .j av a 2s. c om System.out.println(builder.command()); final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } process.waitFor(); if (process.exitValue() != 0) { throw new SALSAException("Failed clustal omega call"); } }
From source file:CustomSubmitter.java
/** * Submits the specified PBS job to the PBS queue using the {@code qsub} * program.//from w w w .j a v a2s . c o m * * @param job the PBS job to be submitted * @throws IOException if an error occurred while invoking {@code qsub} */ public void submit(PBSJob job) throws IOException { Process process = new ProcessBuilder("qsub").start(); RedirectStream.redirect(process.getInputStream(), System.out); RedirectStream.redirect(process.getErrorStream(), System.err); String script = toPBSScript(job); System.out.println(script); PrintStream ps = new PrintStream(process.getOutputStream()); ps.print(script); ps.close(); try { int exitStatus = process.waitFor(); if (exitStatus != 0) { throw new IOException("qsub terminated with exit status " + exitStatus); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }