List of usage examples for java.lang Process exitValue
public abstract int exitValue();
From source file:org.scribble.cli.ExecUtil.java
/** * Runs a process, up to a certain timeout, * //from w w w .j av a2s.c om * @throws IOException * @throws TimeoutException * @throws ExecutionException * @throws InterruptedException */ public static ProcessSummary execUntil(Map<String, String> env, long timeout, String... command) throws IOException, InterruptedException, ExecutionException { ProcessBuilder builder = new ProcessBuilder(command); builder.environment().putAll(env); Process process = builder.start(); ExecutorService executorService = Executors.newFixedThreadPool(3); CyclicBarrier onStart = new CyclicBarrier(3); Future<String> stderr = executorService.submit(toString(process.getErrorStream(), onStart)); Future<String> stdout = executorService.submit(toString(process.getInputStream(), onStart)); Future<Integer> waitFor = executorService.submit(waitFor(process, onStart)); ProcessSummary result = null; try { waitFor.get(timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { // timeouts are ok } finally { process.destroy(); waitFor.get(); result = new ProcessSummary(stdout.get(), stderr.get(), process.exitValue()); executorService.shutdown(); } return result; }
From source file:edu.ucsd.sbrg.escher.EscherConverter.java
/** * Extracts CoBRA from {@link SBMLDocument} if it is FBC compliant. cobrapy must be present for * this./*from w w w . j ava2 s . com*/ * * @param file Input file. * @return Result of extraction. * @throws IOException Thrown if there are problems in reading the {@code input} file(s). * @throws XMLStreamException Thrown if there are problems in parsing XML file(s). */ public static boolean extractCobraModel(File file) throws IOException, XMLStreamException { if (false) { logger.warning(format(bundle.getString("SBMLFBCNotAvailable"), file.getName())); return false; } else { logger.info(format(bundle.getString("SBMLFBCInit"), file.getName())); // Execute: py3 -c "from cobra import io; // io.save_json_model(model=io.read_sbml_model('FILENAME'), file_name='FILENAME')" String[] command; command = new String[] { "python3", "-c", "\"print('yo');from cobra import io;" + "io.save_json_model(model=io.read_sbml_model('" + file.getAbsolutePath() + "'), file_name='" + file.getAbsolutePath() + ".json" + "');print('yo')\"", "> /temp/log" }; // command = new String[] {"/usr/local/bin/python3", "-c", "\"print('yo')\""}; command = new String[] { "python3" }; Process p; try { // p = new ProcessBuilder(command).redirectErrorStream(true).start(); p = Runtime.getRuntime().exec(command); p.waitFor(); if (p.exitValue() == 0) { logger.info(format(bundle.getString("SBMLFBCExtractionSuccessful"), file.getAbsolutePath(), file.getAbsolutePath())); InputStream is = p.getErrorStream(); is = p.getInputStream(); OutputStream os = p.getOutputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String cobrapy_output = ""; cobrapy_output = reader.readLine(); while (cobrapy_output != null) { logger.warning(cobrapy_output); cobrapy_output = reader.readLine(); } return true; } else { logger.info(format(bundle.getString("SBMLFBCExtractionFailed"))); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String cobrapy_output = ""; cobrapy_output = reader.readLine(); while (cobrapy_output != null) { logger.warning(cobrapy_output); cobrapy_output = reader.readLine(); } return false; } } catch (InterruptedException e) { e.printStackTrace(); return false; } } }
From source file:org.polymap.p4.data.importer.raster.ExternalProgram.java
/** * Executes the given command.//ww w. jav a 2 s . c o m * * @param command Command to execute and arguments. * @throws IOException If the command could not be executed. The message of the * exception contains the error output of the command. * @throws RuntimeException If canceled by monitor. */ public static <R, E extends Exception> R execute(String[] command, IProgressMonitor monitor, ResultHandler<R, E> handler) throws IOException { Process process = new ProcessBuilder(command).start(); InputStream in = new BufferedInputStream(process.getInputStream()); StringBuilder output = new StringBuilder(4096); InputStream err = new BufferedInputStream(process.getErrorStream()); StringBuilder error = new StringBuilder(4096); do { if (monitor.isCanceled()) { throw new RuntimeException("Canceled"); } if (read(err, error) > 0) { //checkError( error ); } if (read(in, output) > 0) { monitor.worked(1); } try { Thread.sleep(100); } catch (InterruptedException e) { // continue } } while (isRunning(process)); try { return handler.handle(process.exitValue(), output.toString(), error.toString()); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, IOException.class); throw Throwables.propagate(e); } }
From source file:org.kududb.client.BaseKuduTest.java
/** * Starts a process using the provided command and configures it to be daemon, * redirects the stderr to stdout, and starts a thread that will read from the process' input * stream and redirect that to LOG.//from w ww. ja va 2 s.c o m * @param command Process and options * @return The started process * @throws Exception Exception if an error prevents us from starting the process, * or if we were able to start the process but noticed that it was then killed (in which case * we'll log the exit value). */ static Process configureAndStartProcess(String[] command) throws Exception { LOG.info("Starting process: {}", Joiner.on(" ").join(command)); ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); Process proc = processBuilder.start(); ProcessInputStreamLogPrinterRunnable printer = new ProcessInputStreamLogPrinterRunnable( proc.getInputStream()); Thread thread = new Thread(printer); thread.setDaemon(true); thread.setName(command[0]); PROCESS_INPUT_PRINTERS.add(thread); thread.start(); Thread.sleep(300); try { int ev = proc.exitValue(); throw new Exception( "We tried starting a process (" + command[0] + ") but it exited with " + "value=" + ev); } catch (IllegalThreadStateException ex) { // This means the process is still alive, it's like reverse psychology. } return proc; }
From source file:org.zilverline.util.SysUtils.java
/** * Picks a random number between 0 and (below) the givenNumber. * //from www . ja va 2s. co m * @param number the givenNumber * * @return a number n: 0 <= n < givenNumber */ public static boolean canExecute(final String cmd) { Process proc = null; log.debug("Can we Execute cmd: " + cmd); try { proc = Runtime.getRuntime().exec(cmd); // any error message? StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // any output? StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // kick them off errorGobbler.start(); outputGobbler.start(); proc.waitFor(); log.debug("Exit value: " + proc.exitValue()); log.error("Exit value: " + SysUtils.getErrorTextById(proc.exitValue())); return proc.exitValue() == 0; } catch (Exception e) { log.error("Can't execute: " + cmd, e); if (proc != null) { log.error(" --> Can't execute: '" + cmd + "'. Exit value: " + proc.exitValue()); log.error(" --> Can't execute: '" + cmd + "'. " + SysUtils.getErrorTextById(proc.exitValue())); } } return false; }
From source file:com.ikon.util.ExecutionUtils.java
/** * Execute command line: implementation//w ww. ja va2 s . c om */ private static ExecutionResult runCmdImpl(final String cmd[], final long timeout) throws SecurityException, InterruptedException, IOException { log.debug("runCmdImpl({}, {})", Arrays.toString(cmd), timeout); ExecutionResult ret = new ExecutionResult(); long start = System.currentTimeMillis(); final ProcessBuilder pb = new ProcessBuilder(cmd); final Process process = pb.start(); Timer t = new Timer("Process Execution Timeout"); t.schedule(new TimerTask() { @Override public void run() { process.destroy(); log.warn("Process killed due to timeout."); log.warn("CommandLine: {}", Arrays.toString(cmd)); } }, timeout); try { ret.setStdout(IOUtils.toString(process.getInputStream())); ret.setStderr(IOUtils.toString(process.getErrorStream())); } catch (IOException e) { // Ignore } process.waitFor(); t.cancel(); ret.setExitValue(process.exitValue()); // Check return code if (ret.getExitValue() != 0) { log.warn("Abnormal program termination: {}", ret.getExitValue()); log.warn("CommandLine: {}", Arrays.toString(cmd)); log.warn("STDERR: {}", ret.getStderr()); } else { log.debug("Normal program termination"); } process.destroy(); log.debug("Elapse time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start)); return ret; }
From source file:com.noshufou.android.su.util.Util.java
public static final Boolean isSuid(Context context, String filename) { try {/*from w w w. jav a 2 s. c o m*/ Process p = Runtime.getRuntime().exec(context.getFilesDir() + "/test -u " + filename); p.waitFor(); if (p.exitValue() == 0) { Log.d(TAG, filename + " is set-user-ID"); return true; } } catch (Exception e) { e.printStackTrace(); } Log.d(TAG, filename + " is not set-user-ID"); return false; }
From source file:org.silverpeas.core.util.exec.ExternalExecution.java
/** * Execute the given external command into the context defined by the given {@link * ExternalExecution.Config}./*from w w w . j ava 2s . c o m*/ * @param commandLine the external command to execute. * @param config the configuration that permits to perform the execution of the command with * some flexibility. * @return a {@link List} of console lines written by the external command. */ public static List<String> exec(final CommandLine commandLine, final Config config) throws ExternalExecutionException { final List<String> result = new LinkedList<>(); final List<String> errors = new LinkedList<>(); CollectingLogOutputStream logErrors = new CollectingLogOutputStream(errors); final Process process; Thread errEater = null, outEater = null; try { process = Runtime.getRuntime().exec(commandLine.toStrings()); errEater = new Thread(() -> { try { errors.addAll(IOUtils.readLines(process.getErrorStream())); } catch (final IOException e) { throw new ExternalExecutionException(e); } }); errEater.start(); outEater = new Thread(() -> { try { result.addAll(IOUtils.readLines(process.getInputStream())); } catch (final IOException e) { throw new ExternalExecutionException(e); } }); outEater.start(); process.waitFor(); int exitStatus = process.exitValue(); if (exitStatus != config.getSuccessfulExitStatusValue()) { try { errEater.join(); } catch (InterruptedException e) { } throw new RuntimeException("Exit error status : " + exitStatus + " " + logErrors.getMessage()); } } catch (final IOException | InterruptedException | RuntimeException e) { performExternalExecutionException(config, e); } finally { IOUtils.closeQuietly(logErrors); } try { outEater.join(); } catch (InterruptedException e) { } return result; }
From source file:org.openqa.selenium.server.browserlaunchers.AsyncExecute.java
/** Waits the specified timeout for the process to die */ public static int waitForProcessDeath(Process p, long timeout) { ProcessWaiter pw = new ProcessWaiter(p); Thread waiter = new Thread(pw); waiter.start();/*from w w w .j a v a 2s .com*/ try { waiter.join(timeout); } catch (InterruptedException e) { throw new RuntimeException("Bug? Main interrupted while waiting for process", e); } if (waiter.isAlive()) { waiter.interrupt(); } try { waiter.join(); } catch (InterruptedException e) { throw new RuntimeException("Bug? Main interrupted while waiting for dead process waiter", e); } InterruptedException ie = pw.getException(); if (ie != null) { throw new ProcessStillAliveException("Timeout waiting for process to die", ie); } return p.exitValue(); }
From source file:fxts.stations.util.BrowserLauncher.java
/** * Attempts to open the default web browser to the given URL. * * @param url The URL to open//w w w . j ava 2s. co m * * @throws IOException If the web browser could not be located or does not run */ public static void openURL(String url) throws IOException { if (!loadedWithoutErrors) { throw new IOException("Exception in finding browser: " + errorMessage); } Object browser = locateBrowser(); if (browser == null) { throw new IOException("Unable to locate browser: " + errorMessage); } switch (jvm) { case MRJ_2_0: Object aeDesc = null; try { aeDesc = aeDescConstructor.newInstance(new Object[] { url }); putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc }); sendNoReply.invoke(browser, new Object[] {}); } catch (InvocationTargetException ite) { throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage()); } catch (IllegalAccessException iae) { throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage()); } catch (InstantiationException ie) { throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage()); } finally { aeDesc = null; // Encourage it to get disposed if it was created browser = null; // Ditto } break; case MRJ_2_1: Runtime.getRuntime().exec(new String[] { (String) browser, url }); break; case MRJ_3_0: int[] instance = new int[1]; int result = ICStart(instance, 0); if (result == 0) { int[] selectionStart = new int[] { 0 }; byte[] urlBytes = url.getBytes(); int[] selectionEnd = new int[] { urlBytes.length }; result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes, urlBytes.length, selectionStart, selectionEnd); if (result == 0) { // Ignore the return value; the URL was launched successfully // regardless of what happens here. ICStop(instance); } else { throw new IOException("Unable to launch URL: " + result); } } else { throw new IOException("Unable to create an Internet Config instance: " + result); } break; case MRJ_3_1: try { openURL.invoke(null, new Object[] { url }); } catch (InvocationTargetException ite) { throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage()); } catch (IllegalAccessException iae) { throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage()); } break; case WINDOWS_NT: case WINDOWS_9x: // cmd = 'rundll32 url.dll,FileProtocolHandler http://...' Process process = Runtime.getRuntime().exec(WIN_PATH + " " + WIN_FLAG + " " + url); // This avoids a memory leak on some versions of Java on Windows. // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>. try { process.waitFor(); process.exitValue(); } catch (InterruptedException ie) { throw new IOException("InterruptedException while launching browser: " + ie.getMessage()); } break; case OTHER: // Assume that we're on Unix and that Netscape is installed // First, attempt to open the URL in a currently running session of Netscape process = Runtime.getRuntime().exec(new String[] { (String) browser, NETSCAPE_REMOTE_PARAMETER, NETSCAPE_OPEN_PARAMETER_START + url + NETSCAPE_OPEN_PARAMETER_END }); try { int exitCode = process.waitFor(); if (exitCode != 0) { // if Netscape was not open Runtime.getRuntime().exec(new String[] { (String) browser, url }); } } catch (InterruptedException ie) { throw new IOException("InterruptedException while launching browser: " + ie.getMessage()); } break; default: // This should never occur, but if it does, we'll try the simplest thing possible Runtime.getRuntime().exec(new String[] { (String) browser, url }); break; } }