List of usage examples for java.lang ProcessBuilder directory
File directory
To view the source code for java.lang ProcessBuilder directory.
Click Source Link
From source file:es.amplia.research.maven.protodocbook.cmd.Factory.java
public void executeAll() throws IOException, InterruptedException { File target = new File("target"); target.mkdir();/*from w ww . j a va 2 s . c o m*/ ProcessBuilder pb = new ProcessBuilder("/usr/bin/make", "clean"); Map<String, String> env = pb.environment(); pb.directory(new File(homeDir, "linux")); File logFile = new File("log"); pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(logFile)); Process p = pb.start(); p.waitFor(); pb = new ProcessBuilder("/usr/bin/make"); pb.directory(new File(homeDir, "linux")); pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(logFile)); p = pb.start(); p.waitFor(); pb = new ProcessBuilder("/usr/local/bin/protoc", "-I/usr/include", "--proto_path=src/main/protobuf", "src/main/protobuf/sample.proto", "--plugin=" + this.homeDir.getAbsolutePath() + "/linux/protoc-gen-docbook", "--docbook_out=target"); pb.directory(new File(".")); pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(logFile)); p = pb.start(); p.waitFor(); pb = new ProcessBuilder("/usr/bin/fop", "-xml", "target/docbook_out.xml", "-xsl", "/usr/share/xml/docbook/stylesheet/docbook-xsl/fo/docbook.xsl", "-pdf", "target/docbook_out.pdf", "-param", "page.orientation", "landscape", "-param", "paper.type", "USletter"); pb.directory(new File(".")); pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(logFile)); p = pb.start(); p.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = br.readLine()) != null) { if (this.log.isInfoEnabled()) this.log.info(line); } }
From source file:de.huberlin.wbi.hiway.common.Worker.java
private int exec() { File script = new File("./" + containerId); script.setExecutable(true);/*from w w w . j a va2s. c o m*/ ProcessBuilder processBuilder = new ProcessBuilder(script.getPath()); processBuilder.directory(new File(".")); Process process; int exitValue = -1; try { File stdOutFile = new File(Invocation.STDOUT_FILENAME); File stdErrFile = new File(Invocation.STDERR_FILENAME); processBuilder.redirectOutput(stdOutFile); processBuilder.redirectError(stdErrFile); process = processBuilder.start(); exitValue = process.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); System.exit(-1); } return exitValue; }
From source file:org.dbgl.util.FileUtils.java
private static void executeCommand(final DosboxVersion dbversion, final List<String> execCommands, final File cwd, Map<String, String> env, final boolean waitFor) throws IOException { StringBuffer cmd = new StringBuffer(); try {//ww w. j av a 2 s . com File dir = (cwd == null) ? DOSROOT_DIR_FILE : cwd; if (PlatformUtils.IS_OSX && dbversion != null && dbversion.isUsingCurses()) { String terminalCommand = StringUtils.join(execCommands, ' '); execCommands.clear(); execCommands.add("osascript"); execCommands.add("-e"); execCommands.add("tell application \"Terminal\" to do script \"cd '" + dir + "'; " + terminalCommand + "; exit;\""); } System.out.print(StringUtils.join(execCommands, ' ')); ProcessBuilder pb = new ProcessBuilder(execCommands.toArray(new String[execCommands.size()])); pb.directory(dir); Map<String, String> environment = pb.environment(); if (env != null) { environment.putAll(env); System.out.print(env); } System.out.println(); Process proc = pb.start(); StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "DOSBox stderr"); StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "DOSBox stdout"); outputGobbler.start(); errorGobbler.start(); if (waitFor) { try { proc.waitFor(); } catch (InterruptedException e) { } } } catch (IOException e) { e.printStackTrace(); throw new IOException(Settings.getInstance().msg("general.error.startdosbox", new Object[] { cmd })); } }
From source file:org.sonar.runner.api.CommandExecutor.java
int execute(Command command, StreamConsumer stdOut, StreamConsumer stdErr, long timeoutMilliseconds, @Nullable ProcessMonitor processMonitor) { ExecutorService executorService = null; Process process = null;//from www .j a v a2 s . co m StreamGobbler outputGobbler = null; StreamGobbler errorGobbler = null; try { ProcessBuilder builder = new ProcessBuilder(command.toStrings()); builder.directory(command.directory()); builder.environment().putAll(command.envVariables()); process = builder.start(); outputGobbler = new StreamGobbler(process.getInputStream(), stdOut); errorGobbler = new StreamGobbler(process.getErrorStream(), stdErr); outputGobbler.start(); errorGobbler.start(); executorService = Executors.newSingleThreadExecutor(); final Future<Integer> futureTask = executeProcess(executorService, process); if (processMonitor != null) { monitorProcess(processMonitor, executorService, process); } int exitCode = futureTask.get(timeoutMilliseconds, TimeUnit.MILLISECONDS); waitUntilFinish(outputGobbler); waitUntilFinish(errorGobbler); verifyGobbler(command, outputGobbler, "stdOut"); verifyGobbler(command, errorGobbler, "stdErr"); return exitCode; } catch (TimeoutException te) { process.destroy(); throw new CommandException("Timeout exceeded: " + timeoutMilliseconds + " ms", command, te); } catch (CommandException e) { throw e; } catch (Exception e) { throw new CommandException("Fail to execute command", command, e); } finally { waitUntilFinish(outputGobbler); waitUntilFinish(errorGobbler); closeStreams(process); if (executorService != null) { executorService.shutdown(); } } }
From source file:org.atemsource.dojo.build.DojoBuildMojo.java
private void execute(List<String> params) throws IOException, MojoExecutionException, InterruptedException { ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.directory(workDir); processBuilder.command(params);//from w ww. j a v a 2s .c o m Process process = processBuilder.start(); InputStream in = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); InputStream ein = process.getErrorStream(); BufferedReader ereader = new BufferedReader(new InputStreamReader(ein)); boolean finished = false; do { if (reader.ready()) { String line = reader.readLine(); if (line != null) { System.out.println(line); } } else if (ereader.ready()) { String line = ereader.readLine(); if (line != null) { System.err.println(line); } } else { try { int exit = process.exitValue(); if (exit != 0) { throw new MojoExecutionException("dojo build ended with exit code " + exit); } else { finished = true; } } catch (IllegalThreadStateException e) { } Thread.sleep(100); } } while (!finished); }
From source file:org.eclipse.xtend.util.stdlib.SystemCommand.java
@Override protected void invokeInternal(final WorkflowContext ctx, final ProgressMonitor monitor, final Issues issues) { try {/*from www . j a v a2 s . c om*/ int rc; final List<String> pbArgs = new ArrayList<String>(); pbArgs.add(command); pbArgs.addAll(args); final ProcessBuilder pb = new ProcessBuilder(pbArgs); if (directory != null) { pb.directory(directory); } for (final String env : enventry) { final String[] keyvalue = env.split(","); pb.environment().put(keyvalue[0], keyvalue[1]); } if (inheritEnvironment) { log.debug("Inheriting system environment."); pb.environment().putAll(System.getenv()); } if (log.isDebugEnabled()) { log.debug("Environment:"); log.debug(pb.environment()); log.debug(System.getenv()); } log.info("Running command '" + pb.command() + "' in directory " + pb.directory().getAbsolutePath() + " ..."); final Process p = pb.start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String lineRead; while ((lineRead = br.readLine()) != null) { log.info(lineRead); } br = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((lineRead = br.readLine()) != null) { log.error(lineRead); } rc = p.waitFor(); if (rc != 0) { issues.addError("Error running '" + command + "'"); return; } rc = p.exitValue(); if (rc != 0) { issues.addError("Execution of command failed with error."); } else { log.info("Execution of command was successful."); } } catch (final Exception re) { issues.addError("Runtime error: " + re.getMessage()); } }
From source file:net.urlgrey.mythpodcaster.transcode.SegmentedVodTranscoderImpl.java
public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile, File outputFile) throws Exception { LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile [" + outputFile.getAbsolutePath() + "]"); SegmenterTranscoderConfigurationItem config = (SegmenterTranscoderConfigurationItem) genericConfig; List<String> commandList = new ArrayList<String>(); commandList.add(niceLocation);/*w w w.j a v a2s. c o m*/ commandList.add("-n"); commandList.add(Integer.toString(config.getNiceness())); commandList.add(segmenterLocation); commandList.add(inputFile.getAbsolutePath()); commandList.add(config.getSegmentDuration()); commandList.add(config.getSegmentFilePrefix()); commandList.add(config.getPlaylistFileName()); commandList.add(config.getHttpPrefix()); ProcessBuilder pb = new ProcessBuilder(commandList); pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:"); pb.redirectErrorStream(true); pb.directory(outputFile.getParentFile()); Process process = null; try { // Get the segmenter process process = pb.start(); // We give a couple of secs to complete task if needed Future<List<String>> stdout = pool.submit(new OutputMonitor(process.getInputStream())); List<String> result = stdout.get(config.getTimeout(), TimeUnit.SECONDS); process.waitFor(); final int exitValue = process.exitValue(); LOG.info("Segmenter exit value: " + exitValue); if (exitValue != 0) { for (String line : result) { LOG.error(line); } throw new Exception("Segmenter return code indicated failure: " + exitValue); } } catch (InterruptedException e) { throw new Exception("Segmenter process interrupted by another thread", e); } catch (ExecutionException ee) { throw new Exception("Something went wrong parsing Segmenter output", ee); } catch (TimeoutException te) { // We could not get the result before timeout throw new Exception("Segmenter process timed out", te); } catch (RuntimeException re) { // Unexpected output from Segmenter throw new Exception("Something went wrong parsing Segmenter output", re); } finally { if (process != null) { process.destroy(); } } LOG.debug("transcoding finished"); }
From source file:org.fusesource.ide.buildtools.DownloadLatestXsds.java
public void run() { if (!rootDir.exists()) { throw new IllegalArgumentException("XSD root dir " + rootDir + " does not exist!"); }// w ww . ja v a2 s .c om File outputDir = new File(rootDir, "xsd/fuse"); // lets delete all the XSDs to start with if (delete && outputDir.exists()) { try { FileUtils.deleteDirectory(outputDir); } catch (IOException e) { LOG.warn(e.getMessage(), e); } } outputDir.mkdirs(); StringBuilder pluginXmlBuffer = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); pluginXmlBuffer.append("<?eclipse version=\"3.4\"?>\n"); pluginXmlBuffer.append("<plugin>\n"); pluginXmlBuffer.append(" <extension point=\"org.eclipse.wst.xml.core.catalogContributions\">\n"); pluginXmlBuffer.append(" <catalogContribution id=\"default\">\n"); for (Schema schema : xsdArchetypes) { try { String n = schema.name; String postfix = schema.postfix; String group = schema.group; String version = schema.version; LOG.info("Finding " + n + ", group: " + group + ", postfix '" + postfix + "'"); while (version.endsWith("/")) { version = version.substring(0, version.length() - 1); } String fileName = n + "-" + version + postfix + ".xsd"; String xsd = "http://repository.jboss.org/" + UpdateReleases.releaseRepo + "/org/apache/" + group + "/" + n + "/" + version + "/" + fileName; File outFile = new File(outputDir, fileName); try { LOG.info("Downloading xsd: " + xsd + " to " + outFile); InputStream input = new URL(xsd).openStream(); FileOutputStream output = new FileOutputStream(outFile); IOUtils.copy(input, output); IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } catch (FileNotFoundException e) { try { xsd = "https://repo1.maven.org/maven2/org/apache/" + group + "/" + n + "/" + version + "/" + fileName; LOG.info("Downloading xsd: " + xsd + " to " + outFile); InputStream input = new URL(xsd).openStream(); FileOutputStream output = new FileOutputStream(outFile); IOUtils.copy(input, output); IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } catch (Exception ex) { xsd = "http://repository.jboss.org/" + UpdateReleases.eaRepo + "/org/apache/" + group + "/" + n + "/" + version + "/" + fileName; LOG.info("Downloading xsd: " + xsd + " to " + outFile); InputStream input = new URL(xsd).openStream(); FileOutputStream output = new FileOutputStream(outFile); IOUtils.copy(input, output); IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } pluginXmlBuffer.append(" <uri\n"); pluginXmlBuffer.append(" name=\"http://" + group + ".apache.org/schema/"); if (postfix.trim().length() > 0) { pluginXmlBuffer.append(postfix.substring(postfix.indexOf('-') + 1) + "/"); } pluginXmlBuffer.append(n.substring(n.indexOf('-') + 1) + "\"\n"); pluginXmlBuffer.append(" uri=\"platform:/plugin/org.fusesource.ide.catalogs/xsd/fuse/" + fileName + "\" />\n"); } catch (IOException e) { LOG.error("WARNING: not found: " + e.getMessage(), e); } } pluginXmlBuffer.append(" </catalogContribution>\n"); pluginXmlBuffer.append(" </extension>\n"); pluginXmlBuffer.append("</plugin>\n"); File pluginXml = new File(rootDir, "plugin.xml"); LOG.info("Regenerating " + pluginXml); try { FileOutputStream output = new FileOutputStream(pluginXml); IOUtils.write(pluginXmlBuffer.toString(), output); IOUtils.closeQuietly(output); } catch (IOException e) { LOG.error(e.getMessage(), e); } LOG.info("Running git add..."); ProcessBuilder pb = new ProcessBuilder("git", "add", "*"); pb.directory(outputDir); try { pb.start(); } catch (IOException e) { LOG.error(e.getMessage(), 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); pb.redirectErrorStream(true);/* w ww . j av a2s.co m*/ 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:io.stallion.utils.ProcessHelper.java
public CommandResult run() { String cmdString = String.join(" ", args); System.out.printf("----- Execute command: %s ----\n", cmdString); ProcessBuilder pb = new ProcessBuilder(args); if (!empty(directory)) { pb.directory(new File(directory)); }// w ww. j av a 2 s.c o m Map<String, String> env = pb.environment(); CommandResult commandResult = new CommandResult(); Process p = null; try { if (showDotsWhileWaiting == null) { showDotsWhileWaiting = !inheritIO; } if (inheritIO) { p = pb.inheritIO().start(); } else { p = pb.start(); } BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream())); if (!empty(input)) { Log.info("Writing input to pipe {0}", input); IOUtils.write(input, p.getOutputStream(), UTF8); p.getOutputStream().flush(); } while (p.isAlive()) { p.waitFor(1000, TimeUnit.MILLISECONDS); if (showDotsWhileWaiting == true) { System.out.printf("."); } } commandResult.setErr(IOUtils.toString(err)); commandResult.setOut(IOUtils.toString(out)); commandResult.setCode(p.exitValue()); if (commandResult.succeeded()) { info("\n---- Command execution completed ----\n"); } else { Log.warn("Command failed with error code: " + commandResult.getCode()); } } catch (IOException e) { Log.exception(e, "Error running command: " + cmdString); commandResult.setCode(999); commandResult.setEx(e); } catch (InterruptedException e) { Log.exception(e, "Error running command: " + cmdString); commandResult.setCode(998); commandResult.setEx(e); } Log.fine( "\n\n----Start shell command result----:\nCommand: {0}\nexitCode: {1}\n----------STDOUT---------\n{2}\n\n----------STDERR--------\n{3}\n\n----end shell command result----\n", cmdString, commandResult.getCode(), commandResult.getOut(), commandResult.getErr()); return commandResult; }