List of usage examples for org.apache.commons.exec DefaultExecutor setExitValues
public void setExitValues(final int[] values)
From source file:com.jredrain.base.utils.CommandUtils.java
public static String executeShell(File shellFile, String... args) { String info = null;//from w w w . ja va 2 s . c o m ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { String params = " "; if (CommonUtils.notEmpty(args)) { for (String p : args) { params += p + " "; } } CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath() + params); DefaultExecutor exec = new DefaultExecutor(); exec.setExitValues(null); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputStream); exec.setStreamHandler(streamHandler); exec.execute(commandLine); info = outputStream.toString().trim(); } catch (Exception e) { e.printStackTrace(); } finally { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } return info; } }
From source file:com.tibco.tgdb.test.utils.ProcessCheck.java
/** * Check whether a process is running or not * @param pid pid of the process to monitor * @return true if process is running//from w ww. j a v a2 s. com * @throws IOException IO exception */ public static boolean isProcessRunning(int pid) throws IOException { String line; if (OS.isFamilyWindows()) { //tasklist exit code is always 0. Parse output //findstr exit code 0 if found pid, 1 if it doesn't line = "cmd /c \"tasklist /FI \"PID eq " + pid + "\" | findstr " + pid + "\""; } else { //ps exit code 0 if process exists, 1 if it doesn't line = "ps -p " + pid; } CommandLine cmdLine = CommandLine.parse(line); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(null, null, null)); executor.setExitValues(new int[] { 0, 1 }); int exitValue = executor.execute(cmdLine); if (exitValue == 0) return true; else if (exitValue == 1) return false; else // should never get to here in theory since execute would throw exception return true; }
From source file:at.medevit.elexis.gdt.handler.GDTOutputHandler.java
public static void handleOutput(GDTSatzNachricht gdtSatzNachricht, IGDTCommunicationPartner cp) { int connectionType = cp.getConnectionType(); switch (connectionType) { case SystemConstants.FILE_COMMUNICATION: boolean success = GDTFileHelper.writeGDTSatzNachricht(gdtSatzNachricht, cp); if (success) { GDTProtokoll.addEntry(GDTProtokoll.MESSAGE_DIRECTION_OUT, cp, gdtSatzNachricht); } else {// w ww.j a v a 2s . co m String message = "Fehler beim Schreiben der GDT Satznachricht " + gdtSatzNachricht.getValue(GDTConstants.FELDKENNUNG_SATZIDENTIFIKATION) + " auf " + cp.getLabel(); Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, message); StatusManager.getManager().handle(status, StatusManager.SHOW); logger.log(message, Log.WARNINGS); } // Update the protokoll view final IViewPart protokoll = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .findView(GDTProtokollView.ID); Display display = PlatformUI.getWorkbench().getDisplay(); display.asyncExec(new Runnable() { @Override public void run() { if (protokoll != null) protokoll.setFocus(); } }); // Call the external program to care for the output (if applicable) String handlerProgram = cp.getExternalHandlerProgram(); if (handlerProgram != null) { CommandLine cmdLine = CommandLine.parse(handlerProgram); try { DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(null); // Ignore the exit value int exitValue = executor.execute(cmdLine); logger.log("Return value of " + cmdLine + ": " + exitValue, Log.DEBUGMSG); } catch (ExecuteException e) { String message = "Fehler beim Ausfhren von " + cmdLine; Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, message, e); StatusManager.getManager().handle(status, StatusManager.SHOW); logger.log(e, message, Log.ERRORS); } catch (IOException e) { String message = "Fehler beim Ausfhren von " + cmdLine; Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, message, e); StatusManager.getManager().handle(status, StatusManager.SHOW); logger.log(e, message, Log.ERRORS); } } break; case SystemConstants.SERIAL_COMMUNICATION: // TODO Serial output implementation break; default: break; } }
From source file:com.ghgande.j2mod.modbus.utils.TestUtils.java
/** * Runs a command line task and returns the screen output or throws and * error if something bad happened//from www .ja v a 2s . c o m * * @param command Command to run * * @return Screen output * * @throws Exception */ public static String execToString(String command) throws Exception { // Prepare the command line CommandLine commandline = CommandLine.parse(command); // Prepare the output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); // Prepare the executor DefaultExecutor exec = new DefaultExecutor(); exec.setExitValues(null); exec.setStreamHandler(streamHandler); exec.setWatchdog(new ExecuteWatchdog(5000)); // Execute the command try { exec.execute(commandline); return (outputStream.toString()); } catch (Exception e) { throw new Exception(String.format("%s - %s", outputStream.toString(), e.getMessage())); } }
From source file:eu.learnpad.verification.plugin.pn.modelcheckers.LOLA.java
public static String sync_getVerificationOutput(String lolaBinPath, String modelToVerify, String propertyToVerify, boolean useCoverabilitySearch, final int timeoutInSeconds) throws Exception { int cores = Runtime.getRuntime().availableProcessors(); String filePath = System.getProperty("java.io.tmpdir") + "/" + java.util.UUID.randomUUID() + ".lola"; IOUtils.writeFile(modelToVerify.getBytes(), filePath, false); //IOUtils.writeFile(propertyToVerify.getBytes(), filePath+".ctl", false); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine cmdLine = new CommandLine(lolaBinPath); cmdLine.addArgument("--nolog"); //cmdLine.addArgument("--formula="+filePath+".ctl", false); cmdLine.addArgument("--formula=" + propertyToVerify, false); cmdLine.addArgument("--threads=" + cores); if (useCoverabilitySearch) cmdLine.addArgument("--search=cover"); cmdLine.addArgument("-p"); //cmdLine.addArgument("--path=\""+filePath+".out\"", false); //cmdLine.addArgument("--state=\""+filePath+".out\"", false); cmdLine.addArgument(filePath, false); DefaultExecutor exec = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); ExecuteWatchdog watchdog = new ExecuteWatchdog(1000 * timeoutInSeconds); exec.setWatchdog(watchdog);/*w w w. j a va 2 s . c o m*/ exec.setStreamHandler(streamHandler); exec.setExitValues(new int[] { 0, 1, 2, 139, 35584 }); int exitVal = exec.execute(cmdLine); String output = outputStream.toString(); if (watchdog.killedProcess()) throw new Exception("ERROR: Timeout occurred. LOLA has reached the execution time limit of " + timeoutInSeconds + " seconds, so it has been aborted.\nPartial Output:\n" + output); if (exitVal != 0 || output.equals("") || output.contains("aborting [#")) throw new Exception("ERROR: LOLA internal error\nExit code:" + exitVal + "\nExec: " + cmdLine.toString() + "\nOutput:\n" + output); new File(filePath).delete(); return output; }
From source file:fr.gouv.culture.vitam.utils.Executor.java
/** * Execute an external command//from w w w .j ava 2 s . c om * @param cmd * @param tempDelay * @param correctValues * @param showOutput * @param realCommand * @return correctValues if ok, < 0 if an execution error occurs, or other error values */ public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput, String realCommand) { // Create command with parameters CommandLine commandLine = new CommandLine(cmd.get(0)); for (int i = 1; i < cmd.size(); i++) { commandLine.addArgument(cmd.get(i)); } DefaultExecutor defaultExecutor = new DefaultExecutor(); ByteArrayOutputStream outputStream; outputStream = new ByteArrayOutputStream(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream); defaultExecutor.setStreamHandler(pumpStreamHandler); defaultExecutor.setExitValues(correctValues); AtomicBoolean isFinished = new AtomicBoolean(false); ExecuteWatchdog watchdog = null; Timer timer = null; if (tempDelay > 0) { // If delay (max time), then setup Watchdog timer = new Timer(true); watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); defaultExecutor.setWatchdog(watchdog); CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand); timer.schedule(endOfExecute, tempDelay); } int status = -1; try { // Execute the command status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(100); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { pumpStreamHandler.stop(); System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString()); status = -2; try { outputStream.close(); } catch (IOException e2) { } return status; } catch (IOException e1) { pumpStreamHandler.stop(); System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString()); status = -2; try { outputStream.close(); } catch (IOException e2) { } return status; } } else { pumpStreamHandler.stop(); System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString()); status = -2; try { outputStream.close(); } catch (IOException e2) { } return status; } } catch (IOException e) { pumpStreamHandler.stop(); System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString()); status = -2; try { outputStream.close(); } catch (IOException e2) { } return status; } finally { isFinished.set(true); if (timer != null) { timer.cancel(); } try { Thread.sleep(200); } catch (InterruptedException e1) { } } pumpStreamHandler.stop(); if (defaultExecutor.isFailure(status) && watchdog != null) { if (watchdog.killedProcess()) { // kill by the watchdoc (time out) if (showOutput) { System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out"); } } status = -3; try { outputStream.close(); } catch (IOException e2) { } } else { if (showOutput) { System.out.println("Exec: " + outputStream.toString()); } try { outputStream.close(); } catch (IOException e2) { } } return status; }
From source file:com.codeabovelab.dm.common.utils.ProcessUtils.java
public static int executeCommand(String command, ExecuteWatchdog watchdog, OutputStream outputStream, OutputStream errorStream, InputStream inputStream, Map<String, String> env) { CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); if (outputStream == null) { outputStream = new LogOutputStream() { @Override/*w w w . j a va2 s . co m*/ protected void processLine(String s, int i) { log.error(s); } }; } if (errorStream == null) { errorStream = new LogOutputStream() { @Override protected void processLine(String s, int i) { log.error(s); } }; } executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream, inputStream)); executor.setExitValues(new int[] { 0, 1 }); if (watchdog != null) { executor.setWatchdog(watchdog); } int exitValue; try { exitValue = executor.execute(cmdLine, env); } catch (IOException e) { exitValue = 1; LOGGER.error("error executing command", e); } return exitValue; }
From source file:com.comcast.tvx.haproxy.HAProxyServiceController.java
@Override public int reload() { if (!new File("/etc/init.d/haproxy").exists()) { logger.info("HaProxy is not installed"); throw new IllegalArgumentException("HaProxy is not installed"); }/*ww w . ja v a2 s .co m*/ CommandLine cmdLine = new CommandLine("sudo"); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); cmdLine.addArgument("service"); cmdLine.addArgument("haproxy"); cmdLine.addArgument("reload"); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(new int[] { 0, 1 }); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); executor.setStreamHandler(psh); int exitValue; try { exitValue = executor.execute(cmdLine); } catch (ExecuteException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } logger.info("output from running process: " + stdout.toString()); logger.info("Exit value was: " + exitValue); return exitValue; }
From source file:com.sonar.scanner.api.it.tools.CommandExecutor.java
public int execute(String[] args, Map<String, String> env, @Nullable Path workingDir) throws IOException { if (!Files.isExecutable(file)) { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, perms); }//from ww w . java 2 s . c om watchdog = new ExecuteWatchdog(TIMEOUT); CommandLine cmd = new CommandLine(file.toFile()); cmd.addArguments(args, false); DefaultExecutor exec = new DefaultExecutor(); exec.setWatchdog(watchdog); exec.setStreamHandler(createStreamHandler()); exec.setExitValues(null); if (workingDir != null) { exec.setWorkingDirectory(workingDir.toFile()); } in.close(); LOG.info("Executing: {}", cmd.toString()); return exec.execute(cmd, env); }
From source file:it.sonarlint.cli.tools.CommandExecutor.java
public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException { if (!Files.isExecutable(file)) { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, perms); }/*www . j a v a 2 s . c o m*/ ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); CommandLine cmd = new CommandLine(file.toFile()); cmd.addArguments(args); DefaultExecutor exec = new DefaultExecutor(); exec.setWatchdog(watchdog); exec.setStreamHandler(createStreamHandler()); exec.setExitValues(null); if (workingDir != null) { exec.setWorkingDirectory(workingDir.toFile()); } in.close(); LOG.info("Executing: {}", cmd.toString()); Map<String, String> env = new HashMap<>(System.getenv()); env.putAll(addEnv); return exec.execute(cmd, env); }