List of usage examples for java.lang ProcessBuilder inheritIO
public ProcessBuilder inheritIO()
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 w w . j av a 2s.c om*/ 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; }
From source file:com.orange.clara.cloud.servicedbdumper.integrations.AbstractIntegrationTest.java
protected Process runCommandLineWithStdoutShowed(String[] commandLine) throws IOException, InterruptedException { logger.info("Running command line: " + String.join(" ", commandLine)); ProcessBuilder pb = new ProcessBuilder(commandLine); pb.inheritIO(); Process process = pb.start(); return process; }
From source file:org.raspinloop.fmi.VMRunner.java
@Override public void run() { String separator = System.getProperty("file.separator"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; ProcessBuilder processBuilder; try {/*w ww . j ava 2s .c om*/ processBuilder = new ProcessBuilder(path, VMRunnerUtils.getRunnerAgentArgument(".", jSonConfigName, false), VMRunnerUtils.getWeaverAgentArgument(".", false), vMArguments, "-cp", classPath.stream().collect(Collectors.joining(":")), className, programArguments); } catch (Exception e) { logger.error("Cannot configure process: " + e.getMessage()); throw new VMRunnerUncheckedException(e); } if (System.getProperty("mock") == null || !System.getProperty("mock").equalsIgnoreCase("true")) { try { logger.debug( "==> starting JVM " + processBuilder.command().stream().collect(Collectors.joining(" "))); process = processBuilder.inheritIO().start(); } catch (Exception e) { logger.error("Cannot start process: " + e.getMessage()); throw new VMRunnerUncheckedException(e); } CompletableFuture.supplyAsync(() -> { try { return process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e); } }).thenAccept(i -> logger.info("<== JVM Stopped code(" + i + ")")); } else { logger.info("PLEASE RUN " + processBuilder.command().stream().collect(Collectors.joining(" "))); while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { logger.info("PLEASE STOP "); return; } } } }
From source file:ca.weblite.jdeploy.JDeploy.java
private void publish() throws IOException { try {/*from ww w . ja va 2s . c o m*/ ProcessBuilder pb = new ProcessBuilder(); pb.inheritIO(); pb.command(npm, "publish"); Process p = pb.start(); int result = p.waitFor(); if (result != 0) { System.exit(result); } } catch (InterruptedException ex) { Logger.getLogger(JDeploy.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException(ex); } }
From source file:ca.weblite.jdeploy.JDeploy.java
private void install() throws IOException { _package();/* w w w . ja v a 2 s . c o m*/ try { ProcessBuilder pb = new ProcessBuilder(); pb.inheritIO(); pb.command(npm, "link"); Process p = pb.start(); int result = p.waitFor(); if (result != 0) { System.exit(result); } } catch (InterruptedException ex) { Logger.getLogger(JDeploy.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException(ex); } }
From source file:org.pshdl.model.simulation.codegenerator.GoCodeGenerator.java
public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) { try {/*from w ww . j a va 2s.c o m*/ IHDLInterpreterFactory<NativeRunner> _xblockexpression = null; { final CharSequence dartCode = this.generateMainCode(); final File dutFile = new File(tempDir, "TestUnit.go"); Files.createParentDirs(dutFile); Files.write(dartCode, dutFile, StandardCharsets.UTF_8); final File testRunner = new File(tempDir, "runner.go"); final InputStream runnerStream = CCodeGenerator.class .getResourceAsStream("/org/pshdl/model/simulation/includes/runner.go"); final FileOutputStream fos = new FileOutputStream(testRunner); try { ByteStreams.copy(runnerStream, fos); } finally { fos.close(); } String _absolutePath = testRunner.getAbsolutePath(); String _absolutePath_1 = dutFile.getAbsolutePath(); ProcessBuilder _processBuilder = new ProcessBuilder("/usr/local/go/bin/go", "build", _absolutePath, _absolutePath_1); ProcessBuilder _directory = _processBuilder.directory(tempDir); ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true); final ProcessBuilder goBuilder = _redirectErrorStream.inheritIO(); final Process goCompiler = goBuilder.start(); int _waitFor = goCompiler.waitFor(); boolean _notEquals = (_waitFor != 0); if (_notEquals) { throw new RuntimeException("Compilation of Go Program failed"); } _xblockexpression = new IHDLInterpreterFactory<NativeRunner>() { public NativeRunner newInstance() { try { final File runnerExecutable = new File(tempDir, "runner"); String _absolutePath = runnerExecutable.getAbsolutePath(); ProcessBuilder _processBuilder = new ProcessBuilder(_absolutePath); ProcessBuilder _directory = _processBuilder.directory(tempDir); final ProcessBuilder goBuilder = _directory.redirectErrorStream(true); final Process goRunner = goBuilder.start(); InputStream _inputStream = goRunner.getInputStream(); OutputStream _outputStream = goRunner.getOutputStream(); String _absolutePath_1 = runnerExecutable.getAbsolutePath(); return new NativeRunner(_inputStream, _outputStream, GoCodeGenerator.this.em, goRunner, 5, _absolutePath_1); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } }; } return _xblockexpression; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
From source file:ca.weblite.jdeploy.JDeploy.java
private void init_old(String commandName) throws IOException { try {/*from www . j a v a 2 s . co m*/ File packageJson = new File(directory, "package.json"); if (!packageJson.exists()) { ProcessBuilder pb = new ProcessBuilder(); pb.command(npm, "init"); pb.inheritIO(); final Process p = pb.start(); Timer t = new Timer(); TimerTask tt = new TimerTask() { @Override public void run() { if (packageJson.exists()) { p.destroy(); cancel(); } } }; t.schedule(tt, new Date(System.currentTimeMillis() + 1000), 1000); int code = p.waitFor(); if (!packageJson.exists() && code != 0) { System.err.println("Stopped init because npm init failed"); System.exit(code); } } String pkgJsonStr = FileUtils.readFileToString(packageJson, "UTF-8"); if (!pkgJsonStr.contains("shelljs")) { System.out.println("Installing shelljs"); ProcessBuilder pb = new ProcessBuilder(); pb.inheritIO(); pb.command(npm, "install", "shelljs", "--save"); Process p = pb.start(); int result = p.waitFor(); if (result != 0) { System.err.println("Failed to install shelljs"); System.exit(result); } } // For some reason it never sticks in the package.json file the first time pkgJsonStr = FileUtils.readFileToString(packageJson, "UTF-8"); if (!pkgJsonStr.contains("shelljs")) { System.out.println("Installing shelljs"); ProcessBuilder pb = new ProcessBuilder(); pb.inheritIO(); pb.command(npm, "install", "shelljs", "--save"); Process p = pb.start(); int result = p.waitFor(); if (result != 0) { System.err.println("Failed to install shelljs"); System.exit(result); } } JSONParser parser = new JSONParser(); Map contents = parser.parseJSON(new StringReader(pkgJsonStr)); if (commandName == null) { commandName = (String) contents.get("name"); } if (!contents.containsKey("bin")) { contents.put("bin", new HashMap()); } Map bins = (Map) contents.get("bin"); if (!bins.values().contains(getBinDir() + "/jdeploy.js")) { contents.put("preferGlobal", true); bins.put(commandName, getBinDir() + "/jdeploy.js"); Result res = Result.fromContent(contents); FileUtils.writeStringToFile(packageJson, res.toString(), "UTF-8"); } if (!contents.containsKey("files")) { contents.put("files", new ArrayList()); } List files = (List) contents.get("files"); if (!files.contains(getBinDir())) { files.add(getBinDir()); Result res = Result.fromContent(contents); FileUtils.writeStringToFile(packageJson, res.toString(), "UTF-8"); } } catch (InterruptedException ex) { throw new RuntimeException(ex); } }
From source file:org.apache.htrace.impl.HTracedProcess.java
private HTracedProcess(Builder builder) throws Exception { this.htracedPath = Paths.get("target", "..", "go", "build", "htraced").toFile(); if (!this.htracedPath.exists()) { throw new RuntimeException("No htraced binary exists at " + this.htracedPath); }// w w w. ja v a 2 s. c o m this.dataDir = new DataDir(); // Create a notifier socket bound to a random port. ServerSocket listener = new ServerSocket(0); boolean success = false; Process process = null; HttpClient http = null; try { // Use a random port for the web address. No 'scheme' yet. String random = builder.host + ":0"; String logPath = new File(dataDir.get(), "log.txt").getAbsolutePath(); // Pass cmdline args to htraced to it uses our test dir for data. ProcessBuilder pb = new ProcessBuilder(htracedPath.getAbsolutePath(), "-Dlog.level=TRACE", "-Dlog.path=" + logPath, "-Dweb.address=" + random, "-Dhrpc.address=" + random, "-Ddata.store.clear=true", "-Dstartup.notification.address=localhost:" + listener.getLocalPort(), "-Ddata.store.directories=" + dataDir.get().getAbsolutePath()); // Set HTRACED_CONF_DIR to the temporary directory we just created, to // ensure that it doesn't pull in any other configuration file that might // be on this test machine. Map<String, String> env = pb.environment(); env.put("HTRACED_CONF_DIR", dataDir.get().getAbsolutePath()); // Remove any HTRACED_WEB_DIR variable that might be set, to ensure that // we use the default value (which finds the local web files by relative // path). env.remove("HTRACED_WEB_DIR"); pb.redirectErrorStream(true); // Inherit STDERR/STDOUT i/o; dumps on console for now. Can add logs later. pb.inheritIO(); pb.directory(dataDir.get()); //assert pb.redirectInput() == Redirect.PIPE; //assert pb.redirectOutput().file() == dataDir; process = pb.start(); assert process.getInputStream().read() == -1; StartupNotificationData data = readStartupNotification(listener); httpAddr = data.httpAddr; hrpcAddr = data.hrpcAddr; LOG.info("Started htraced process " + data.processId + " with http " + "address " + data.httpAddr + ", logging to " + logPath); http = RestBufferManager.createHttpClient(60000L, 60000L); http.start(); success = true; } finally { if (!success) { // Clean up after failure if (process != null) { process.destroy(); process = null; } if (http != null) { http.stop(); } } delegate = process; listener.close(); httpClient = http; } }
From source file:org.pshdl.model.simulation.codegenerator.CCodeGenerator.java
public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) { try {//w ww. jav a 2s . c o m final File testCFile = new File(tempDir, "test.c"); String _generateMainCode = this.generateMainCode(); Files.write(_generateMainCode, testCFile, StandardCharsets.UTF_8); final File testRunner = new File(tempDir, "runner.c"); final InputStream runnerStream = CCodeGenerator.class .getResourceAsStream("/org/pshdl/model/simulation/includes/runner.c"); final FileOutputStream fos = new FileOutputStream(testRunner); try { ByteStreams.copy(runnerStream, fos); } finally { runnerStream.close(); fos.close(); } final File executable = new File(tempDir, "testExec"); this.writeAuxiliaryContents(tempDir); String _absolutePath = tempDir.getAbsolutePath(); String _absolutePath_1 = testCFile.getAbsolutePath(); String _absolutePath_2 = testRunner.getAbsolutePath(); String _absolutePath_3 = executable.getAbsolutePath(); final ProcessBuilder builder = new ProcessBuilder(CCodeGenerator.COMPILER, "-I", _absolutePath, "-O3", _absolutePath_1, _absolutePath_2, "-o", _absolutePath_3); ProcessBuilder _directory = builder.directory(tempDir); ProcessBuilder _inheritIO = _directory.inheritIO(); final Process process = _inheritIO.start(); process.waitFor(); int _exitValue = process.exitValue(); boolean _notEquals = (_exitValue != 0); if (_notEquals) { throw new RuntimeException("Process did not terminate with 0"); } return new IHDLInterpreterFactory<NativeRunner>() { public NativeRunner newInstance() { try { String _absolutePath = executable.getAbsolutePath(); final ProcessBuilder execBuilder = new ProcessBuilder(_absolutePath); ProcessBuilder _directory = execBuilder.directory(tempDir); ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true); final Process testExec = _redirectErrorStream.start(); InputStream _inputStream = testExec.getInputStream(); OutputStream _outputStream = testExec.getOutputStream(); String _absolutePath_1 = executable.getAbsolutePath(); return new NativeRunner(_inputStream, _outputStream, CCodeGenerator.this.em, testExec, 5, _absolutePath_1); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } }; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
From source file:com.netflix.genie.agent.execution.services.impl.LaunchJobServiceImpl.java
/** * {@inheritDoc}//from w w w . j av a2s . c om */ @Override public void launchProcess(final File jobDirectory, final Map<String, String> environmentVariablesMap, final List<String> commandLine, final boolean interactive) throws JobLaunchException { if (!launched.compareAndSet(false, true)) { throw new IllegalStateException("Job already launched"); } final ProcessBuilder processBuilder = new ProcessBuilder(); // Validate job running directory if (jobDirectory == null) { throw new JobLaunchException("Job directory is null"); } else if (!jobDirectory.exists()) { throw new JobLaunchException("Job directory does not exist: " + jobDirectory); } else if (!jobDirectory.isDirectory()) { throw new JobLaunchException("Job directory is not a directory: " + jobDirectory); } else if (!jobDirectory.canWrite()) { throw new JobLaunchException("Job directory is not writable: " + jobDirectory); } final Map<String, String> currentEnvironmentVariables = processBuilder.environment(); if (environmentVariablesMap == null) { throw new JobLaunchException("Job environment variables map is null"); } // Merge job environment variables into process inherited environment environmentVariablesMap.forEach((key, value) -> { final String replacedValue = currentEnvironmentVariables.put(key, value); if (StringUtils.isBlank(replacedValue)) { log.debug("Added job environment variable: {}={}", key, value); } else if (!replacedValue.equals(value)) { log.debug("Set job environment variable: {}={} (previous value: {})", key, value, replacedValue); } }); // Validate arguments if (commandLine == null) { throw new JobLaunchException("Job command-line arguments is null"); } else if (commandLine.isEmpty()) { throw new JobLaunchException("Job command-line arguments are empty"); } // Configure arguments log.info("Job command-line: {}", Arrays.toString(commandLine.toArray())); final List<String> expandedCommandLine; try { expandedCommandLine = expandCommandLineVariables(commandLine, Collections.unmodifiableMap(currentEnvironmentVariables)); } catch (final EnvUtils.VariableSubstitutionException e) { throw new JobLaunchException("Job command-line arguments variables could not be expanded"); } if (!commandLine.equals(expandedCommandLine)) { log.info("Job command-line with variables expanded: {}", Arrays.toString(expandedCommandLine.toArray())); } processBuilder.command(expandedCommandLine); if (interactive) { processBuilder.inheritIO(); } else { processBuilder.redirectError(PathUtils.jobStdErrPath(jobDirectory).toFile()); processBuilder.redirectOutput(PathUtils.jobStdOutPath(jobDirectory).toFile()); } if (killed.get()) { log.info("Job aborted, skipping launch"); } else { log.info("Launching job"); try { processReference.set(processBuilder.start()); } catch (final IOException | SecurityException e) { throw new JobLaunchException("Failed to launch job: ", e); } log.info("Process launched (pid: {})", getPid(processReference.get())); } }