List of usage examples for java.lang ProcessBuilder start
public Process start() throws IOException
From source file:edu.illinois.cs.cogcomp.CleanMojo.java
public void execute() throws MojoExecutionException { dFlag = FileUtils.getPlatformIndependentFilePath(dFlag); gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag); sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag); classpath.add(dFlag);//w ww . j a va 2s . c o m classpath.add(gspFlag); String newpath = StringUtils.join(classpath, File.pathSeparator); // We need to reverse the order we do the cleaning since there might be dependencies across // files List<String> fileList = Arrays.asList(lbjavaInputFileList); Collections.reverse(fileList); for (String lbjInputFile : fileList) { if (StringUtils.isEmpty(lbjInputFile)) { // making the optional-compile-step parameter happy. continue; } getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main with the -x flag (for cleaning)..."); lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile); try { // The -x flag makes all the difference. String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-x", "-d", dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile }; ProcessBuilder pr = new ProcessBuilder(args); pr.inheritIO(); Process p = pr.start(); p.waitFor(); } catch (Exception e) { e.printStackTrace(); System.out.println("Yeah, an error."); } } }
From source file:net.openhft.chronicle.VanillaChronicleTestBase.java
public void lsof(final String pid, final String pattern) throws IOException { String cmd = null;// w ww . j a v a 2s . com if (new File("/usr/sbin/lsof").exists()) { cmd = "/usr/sbin/lsof"; } else if (new File("/usr/bin/lsof").exists()) { cmd = "/usr/bin/lsof"; } if (cmd != null) { final ProcessBuilder pb = new ProcessBuilder(cmd, "-p", pid); final Process proc = pb.start(); final BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; while ((line = br.readLine()) != null) { if (StringUtils.isBlank(pattern) || line.matches(pattern) || line.contains(pattern)) { System.out.println(line); } } br.close(); proc.destroy(); } }
From source file:com.netscape.cmstools.profile.ProfileEditCLI.java
public void execute(String[] args) throws Exception { // Always check for "--help" prior to parsing if (Arrays.asList(args).contains("--help")) { printHelp();/*from w ww . j a va 2 s .c o m*/ return; } CommandLine cmd = parser.parse(options, args); String[] cmdArgs = cmd.getArgs(); if (cmdArgs.length < 1) { throw new Exception("No Profile ID specified."); } String profileId = cmdArgs[0]; ProfileClient profileClient = profileCLI.getProfileClient(); // read profile into temporary file byte[] orig = profileClient.retrieveProfileRaw(profileId); ProfileCLI.checkConfiguration(orig, false /* requireProfileId */, true /* requireDisabled */); Path tempFile = Files.createTempFile("pki", ".cfg"); try { Files.write(tempFile, orig); // invoke editor on temporary file String editor = System.getenv("EDITOR"); String[] command; if (editor == null || editor.trim().isEmpty()) { command = new String[] { "/usr/bin/env", "vi", tempFile.toString() }; } else { command = new String[] { editor.trim(), tempFile.toString() }; } ProcessBuilder pb = new ProcessBuilder(command); pb.inheritIO(); int exitCode = pb.start().waitFor(); if (exitCode != 0) { throw new Exception("Exited abnormally."); } // read data from temporary file and modify if changed byte[] cur = ProfileCLI.readRawProfileFromFile(tempFile); if (!Arrays.equals(cur, orig)) { profileClient.modifyProfileRaw(profileId, cur); } System.out.write(cur); } finally { Files.delete(tempFile); } }
From source file:com.ikon.servlet.TextToSpeechServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String cmd = "espeak -v mb-es1 -f input.txt | mbrola -e /usr/share/mbrola/voices/es1 - -.wav " + "| oggenc -Q - -o output.ogg"; String text = WebUtils.getString(request, "text"); String docPath = WebUtils.getString(request, "docPath"); response.setContentType("audio/ogg"); FileInputStream fis = null;/*from ww w .j a va 2s. c o m*/ OutputStream os = null; try { if (!text.equals("")) { FileUtils.writeStringToFile(new File("input.txt"), text); } else if (!docPath.equals("")) { InputStream is = OKMDocument.getInstance().getContent(null, docPath, false); Document doc = OKMDocument.getInstance().getProperties(null, docPath); DocConverter.getInstance().doc2txt(is, doc.getMimeType(), new File("input.txt")); } // Convert to voice ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", cmd); Process process = pb.start(); process.waitFor(); String info = IOUtils.toString(process.getInputStream()); process.destroy(); if (process.exitValue() == 1) { log.warn(info); } // Send to client os = response.getOutputStream(); fis = new FileInputStream("output.ogg"); IOUtils.copy(fis, os); os.flush(); } catch (InterruptedException e) { log.warn(e.getMessage(), e); } catch (IOException e) { log.warn(e.getMessage(), e); } catch (PathNotFoundException e) { log.warn(e.getMessage(), e); } catch (AccessDeniedException e) { log.warn(e.getMessage(), e); } catch (RepositoryException e) { log.warn(e.getMessage(), e); } catch (DatabaseException e) { log.warn(e.getMessage(), e); } catch (ConversionException e) { log.warn(e.getMessage(), e); } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(os); } }
From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java
public static String runCliCommands(File cliExecutablePath, List<List<String>> commands, boolean isDebug) throws IOException, InterruptedException { if (!cliExecutablePath.isFile()) { throw new IllegalArgumentException(cliExecutablePath + " is not a file"); }//from w w w .j av a 2 s . co m File workingDirectory = cliExecutablePath.getAbsoluteFile().getParentFile(); if (!workingDirectory.isDirectory()) { throw new IllegalArgumentException(workingDirectory + " is not a directory"); } int argsCount = 0; for (List<String> command : commands) { argsCount += command.size(); } // needed to properly intercept error return code String[] cmd = new String[(argsCount == 0 ? 0 : 1) + 4 /* cmd /c call cloudify.bat ["args"] */]; int i = 0; cmd[i] = "cmd"; i++; cmd[i] = "/c"; i++; cmd[i] = "call"; i++; cmd[i] = cliExecutablePath.getAbsolutePath(); i++; if (argsCount > 0) { cmd[i] = "\""; //TODO: Use StringBuilder for (List<String> command : commands) { if (command.size() > 0) { for (String arg : command) { if (cmd[i].length() > 0) { cmd[i] += " "; } cmd[i] += arg; } cmd[i] += ";"; } } cmd[i] += "\""; } final ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(workingDirectory); pb.redirectErrorStream(true); String extCloudifyJavaOptions = ""; if (isDebug) { extCloudifyJavaOptions += "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9000 -Xnoagent -Djava.compiler=NONE"; } pb.environment().put("EXT_CLOUDIFY_JAVA_OPTIONS", extCloudifyJavaOptions); final StringBuilder sb = new StringBuilder(); logger.info("running: " + cliExecutablePath + " " + Arrays.toString(cmd)); // log std output and redirected std error Process p = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = reader.readLine(); while (line != null) { sb.append(line).append("\n"); line = reader.readLine(); logger.info(line); } final String readResult = sb.toString(); final int exitValue = p.waitFor(); logger.info("Exit value = " + exitValue); if (exitValue != 0) { Assert.fail("Cli ended with error code: " + exitValue); } return readResult; }
From source file:com.epimorphics.registry.util.RunShell.java
public Future<Boolean> run(String... args) { String[] argA = new String[2 + args.length]; argA[0] = DEFAULT_SHELL;//from w ww . j a v a2 s. com argA[1] = scriptFile; for (int i = 0; i < args.length; i++) { argA[2 + i] = args[i]; } ProcessBuilder scriptPB = new ProcessBuilder(argA); scriptPB.redirectErrorStream(true); try { Process scriptProcess = scriptPB.start(); Future<Boolean> scriptStatus = TimerManager.get().submit(new TrackShell(scriptProcess)); return scriptStatus; } catch (IOException e) { log.error("Error invoking script: " + scriptFile, e); return ConcurrentUtils.constantFuture(false); } }
From source file:com.synopsys.integration.executable.ProcessBuilderRunner.java
private ExecutableOutput executeProcessBuilder(ProcessBuilder processBuilder) throws ExecutableRunnerException { try {/*from w ww .ja v a 2 s. c o m*/ final Process process = processBuilder.start(); try (InputStream standardOutputStream = process.getInputStream(); InputStream standardErrorStream = process.getErrorStream()) { final ExecutableStreamThread standardOutputThread = new ExecutableStreamThread(standardOutputStream, logger::info, logger::trace); standardOutputThread.start(); final ExecutableStreamThread errorOutputThread = new ExecutableStreamThread(standardErrorStream, logger::info, logger::trace); errorOutputThread.start(); final int returnCode = process.waitFor(); logger.info("process finished: " + returnCode); standardOutputThread.join(); errorOutputThread.join(); final String standardOutput = standardOutputThread.getExecutableOutput().trim(); final String errorOutput = errorOutputThread.getExecutableOutput().trim(); final ExecutableOutput output = new ExecutableOutput(returnCode, standardOutput, errorOutput); return output; } } catch (final Exception e) { throw new ExecutableRunnerException(e); } }
From source file:com.bancvue.mongomigrate.MongoShellExecutor.java
@Override public int executeJsFile(String pathToJsFile) throws IOException, InterruptedException { ProcessBuilder builder = new ProcessBuilder(pathToMongoExe, mongoConnectionString + "/" + databaseName, pathToJsFile);/*from ww w .ja va2s. c om*/ final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); InputStream errorStream = process.getErrorStream(); InputStreamReader errorStreamReader = new InputStreamReader(errorStream); BufferedReader errorStreamBufferedReader = new BufferedReader(errorStreamReader); String line; while ((line = br.readLine()) != null) { System.out.println(line); } while ((line = errorStreamBufferedReader.readLine()) != null) { System.out.println("ERROR: " + line); } int exitCode = process.waitFor(); return exitCode; }
From source file:io.wcm.maven.plugins.nodejs.mojo.Task.java
private void startProcess(ProcessBuilder processBuilder) throws MojoExecutionException { try {/*w w w .j a v a 2 s . c o m*/ final Process process = processBuilder.start(); getLog().info("Running process: " + StringUtils.join(processBuilder.command(), " ")); initLogging(process); int result = process.waitFor(); if (result != 0) { throw new MojoExecutionException("Process: " + StringUtils.join(processBuilder.command(), " ") + " terminated with " + result); } } catch (IOException ex) { throw new MojoExecutionException( "Error executing process: " + StringUtils.join(processBuilder.command(), " "), ex); } catch (InterruptedException ex) { throw new MojoExecutionException( "Error executing process: " + StringUtils.join(processBuilder.command(), " "), ex); } }
From source file:com.netscape.cmstools.cli.HelpCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); String[] cmdArgs = cmd.getArgs(); String manPage = null;//from w ww. ja v a2s . co m if (cmdArgs.length == 0) { // no command specified, show the pki man page manPage = parent.getManPage(); } else { // find all modules handling the specified command List<CLI> modules = parent.findModules(cmdArgs[0]); // find the module that has a man page starting from the last one for (int i = modules.size() - 1; i >= 0; i--) { CLI module = modules.get(i); manPage = module.getManPage(); if (manPage != null) break; } // if no module has a man page, show the pki man page if (manPage == null) manPage = parent.getManPage(); } while (true) { // display man page for the command ProcessBuilder pb = new ProcessBuilder("/usr/bin/man", manPage); pb.inheritIO(); Process p = pb.start(); int rc = p.waitFor(); if (rc == 16) { // man page not found, find the parent command int i = manPage.lastIndexOf('-'); if (i >= 0) { // parent command exists, try again manPage = manPage.substring(0, i); continue; } else { // parent command not found, stop break; } } else { // man page found or there's a different error, stop break; } } }