List of usage examples for org.apache.commons.exec CommandLine CommandLine
public CommandLine(final CommandLine other)
From source file:de.torstenwalter.maven.plugins.SQLPlusMojo.java
private void runScriptWithSqlPlus(File file, Map environment) throws MojoExecutionException, MojoFailureException { checkFileIsReadable(file);/*from ww w . j a v a 2 s. c om*/ CommandLine commandLine = new CommandLine(sqlplus); // logon only once, without this sql*plus would prompt for // credentials if given ones are not correct commandLine.addArgument("-L"); StringTokenizer stringTokenizer = new StringTokenizer(getConnectionIdentifier()); while (stringTokenizer.hasMoreTokens()) { commandLine.addArgument(stringTokenizer.nextToken()); } commandLine.addArgument("@" + file.getName()); if (arguments != null) { for (Object argument : arguments) { if (argument == null) { throw new MojoExecutionException("Misconfigured argument, value is null. " + "Set the argument to an empty value if this is the required behaviour."); } else { commandLine.addArgument(argument.toString()); } } } getLog().info("Executing command line: " + obfuscateCredentials(commandLine.toString(), getCredentials())); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(file.getParentFile()); exec.setStreamHandler(new PumpStreamHandler(System.out, System.err)); try { exec.execute(commandLine, environment); } catch (ExecuteException e) { throw new MojoExecutionException("program exited with exitCode: " + e.getExitValue()); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } }
From source file:com.thinkbiganalytics.spark.shell.MultiUserProcessManager.java
/** * Calls kinit to request a new Kerberos ticket if the previous one is about to expire. *//*w w w . ja va2 s. com*/ private void refreshKerberosTicket() { // Determine if a new ticket is needed if (kerberos == null || kerberos.getInitInterval() <= 0 || kerberosNextInit > DateTimeUtils.currentTimeMillis()) { return; } // Build executor final Executor executor = new DefaultExecutor(); final ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer(); executor.setProcessDestroyer(processDestroyer); final Logger outputLogger = LoggerFactory.getLogger(getClass().getName() + ".kinit"); final LoggerOutputStream outputStream = new LoggerOutputStream(outputLogger); final PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); final ExecuteWatchdog watchdog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(kerberos.getInitTimeout())); executor.setWatchdog(watchdog); // Run kinit to acquire a new ticket final CommandLine command = new CommandLine("kinit").addArgument("-kt") .addArgument(kerberos.getKeytabLocation()).addArgument(kerberos.getKerberosPrincipal()); log.debug("Acquiring a new Kerberos ticket with command: {}", command); int exitCode; try { exitCode = executor.execute(command); } catch (final IOException e) { log.error("Failed to execute kinit", e); exitCode = -1; } // Record next time to acquire ticket if (!executor.isFailure(exitCode)) { kerberosNextInit = DateTimeUtils.currentTimeMillis() + TimeUnit.SECONDS.toMillis(kerberos.getInitInterval()); } else { if (watchdog.killedProcess()) { log.error("Failed to acquire a Kerberos ticket within the allotted time: {}", kerberos.getInitTimeout()); } else { log.error("Kinit exited with non-zero status: {}", exitCode); } kerberosNextInit = DateTimeUtils.currentTimeMillis() + TimeUnit.SECONDS.toMillis(kerberos.getRetryInterval()); throw new IllegalStateException("Failed to acquire a Kerberos ticket"); } }
From source file:de.yaio.services.webshot.server.controller.WebshotProvider.java
protected WebShotResultHandler runCommand(final String command, final String[] params, final long jobTimeout) throws IOException { int exitValue; boolean inBackground = false; ExecuteWatchdog watchdog = null;/*from ww w. j a v a 2 s . co m*/ WebShotResultHandler resultHandler; // build up the command line to using a 'java.io.File' final CommandLine commandLine = new CommandLine(command); commandLine.addArguments(params); if (LOGGER.isDebugEnabled()) { LOGGER.debug("start command " + command + " with params" + new ReflectionToStringBuilder(params, ToStringStyle.SHORT_PREFIX_STYLE).toString()); } // create the executor and consider the exitValue '1' as success final Executor executor = new DefaultExecutor(); executor.setExitValue(0); // create a watchdog if requested if (jobTimeout > 0) { watchdog = new ExecuteWatchdog(jobTimeout); executor.setWatchdog(watchdog); } if (inBackground) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[WebShot] Executing non-blocking WebShot job ..."); } resultHandler = new WebShotResultHandler(watchdog); executor.execute(commandLine, resultHandler); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[WebShot] Executing blocking WebShot job ..."); } exitValue = executor.execute(commandLine); resultHandler = new WebShotResultHandler(exitValue); } return resultHandler; }
From source file:modules.NativeProcessMonitoringDaemonModule.java
protected void startNativeMonitor(String command, String options, Path path) throws NativeExecutionException { if (command == null || command.equals("")) { System.err.println("command null at GeneralNativeCommandModule.extractNative()"); return;//from w w w .j a va 2 s. co m } CommandLine commandLine = new CommandLine(command); if (options != null && !options.equals("")) { String[] args = options.split(" "); commandLine.addArguments(args); } if (path != null) { commandLine.addArgument(path.toAbsolutePath().toString(), false); } executor = new DefaultExecutor(); esh = new MyExecuteStreamHandler(); executor.setStreamHandler(esh); // GeneralExecutableModuleConfig generalExecutableModuleConfig = // getConfig(); executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT)); if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) { executor.setWorkingDirectory(getConfig().workingDirectory); } try { // System.out.println("Now execute: " + commandLine); executor.execute(commandLine, this); } catch (ExecuteException xs) { NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.exitCode = xs.getExitValue(); throw n; } catch (IOException xs) { NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } throw n; } return; }
From source file:com.github.zeroxff.executor.ExtendedExecutor.java
public ExecuteResult execute() throws ExtendedExecuteException { this.clearOut(); if (this.commandLine == null) { throw new ExtendedExecuteException("CommandLine cannot be null", Executor.INVALID_EXITVALUE); }//w w w .j a va 2 s .c om if (this.commandLine.length == 0) { throw new ExtendedExecuteException("CommandLine cannot be empty", Executor.INVALID_EXITVALUE); } if (this.maxExecutiontime != ExecuteWatchdog.INFINITE_TIMEOUT && this.maxExecutiontime < 1) { throw new ExtendedExecuteException("Max execution time must not be less than 1", Executor.INVALID_EXITVALUE); } try { // load the command line as an array of strings CommandLine cmdLine = new CommandLine(this.commandLine[0]); for (int counter = 1; counter < commandLine.length; counter++) { cmdLine.addArgument(this.commandLine[counter], quoteCommandlineArgs); } // load the substitution map, if defined if (this.substitutionMap != null) { cmdLine.setSubstitutionMap(this.substitutionMap); } // load the watchdog timer, it can be set to infinite time ExecuteWatchdog watchdog = new ExecuteWatchdog(this.maxExecutiontime); ExtendedResultHandler resultHandler = new ExtendedResultHandler(watchdog); // inizialize outputstream processors. OutStreamProcessor outLinee = null; OutStreamProcessor errLinee = null; PumpStreamHandler streamHandler = null; if (outputFilter != null && outputFilter.size() > 0) { outLinee = new OutStreamProcessor(outputFilter); } else { outLinee = new OutStreamProcessor(); } if (this.enableAllLinesOut) { outLinee.enableAllLines(); } if (mergeOutStreams) { // Using Std out for the output/error stream streamHandler = new PumpStreamHandler(outLinee); } else { if (errorFilter != null && errorFilter.size() > 0) { errLinee = new OutStreamProcessor(errorFilter); } else { errLinee = new OutStreamProcessor(); } if (enableAllLinesErr) { errLinee.enableAllLines(); } // Using Std out for the output/error stream streamHandler = new PumpStreamHandler(outLinee, errLinee); } DefaultExecutor executor = new DefaultExecutor(); // set the working directory... // if the working directory doesn't exists, it can crash the // executor. if (workingDirecory != null) { executor.setWorkingDirectory(workingDirecory); } // set the accepted exit values for the command line // default is '0'. if (okExitValues != null && okExitValues.length > 0) { executor.setExitValues(okExitValues); } executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); try { executor.execute(cmdLine, resultHandler); resultHandler.waitFor(); returnCode = resultHandler.getExitValue(); exitMode = resultHandler.getExitMode(); switch (exitMode) { case ERROR_IN_EXECUTION: this.message = resultHandler.getException().getMessage(); break; default: break; } } catch (ExecuteException e) { exitMode = ExecuteResult.EXCEPTION; exception = e; this.message = e.getMessage(); } catch (IOException e) { exitMode = ExecuteResult.EXCEPTION; exception = e; this.message = e.getMessage(); } catch (InterruptedException e) { exitMode = ExecuteResult.EXCEPTION; exception = e; this.message = e.getMessage(); } // if (outLinee != null) { outputLines = outLinee.getLines(); allOutputLines = outLinee.getAllLines(); } if (errLinee != null) { errorLines = errLinee.getLines(); allErrorLines = errLinee.getAllLines(); } this.closeStreams(outLinee, errLinee); } catch (Exception e) { throw new ExtendedExecuteException(e.getMessage(), Executor.INVALID_EXITVALUE, e); } return exitMode; }
From source file:com.walmart.gatling.commons.ScriptExecutor.java
private void runCancelJob(Master.Job message) { if (getAbortStatus(message.abortUrl, message.trackingId)) { CommandLine cmdLine = new CommandLine("/bin/bash"); cmdLine.addArgument(agentConfig.getJob().getJobArtifact("cancel")); cmdLine.addArgument(message.jobId); DefaultExecutor killExecutor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); killExecutor.setWatchdog(watchdog); try {// w w w . j a v a2s. c o m log.info("Cancel command: {}", cmdLine); killExecutor.execute(cmdLine); } catch (IOException e) { log.error(e, "Error cancelling job"); } } }
From source file:com.netflix.genie.core.services.impl.LocalJobKillServiceImpl.java
private void killJobOnUnix(final int pid) throws GenieException { try {/*from w ww.j av a 2 s. c o m*/ // Ensure this process check can't be timed out final Calendar tomorrow = Calendar.getInstance(JobConstants.UTC); tomorrow.add(Calendar.DAY_OF_YEAR, 1); final ProcessChecker processChecker = new UnixProcessChecker(pid, this.executor, tomorrow.getTime()); processChecker.checkProcess(); } catch (final ExecuteException ee) { // This means the job was done already log.debug("Process with pid {} is already done", pid); return; } catch (final IOException ioe) { throw new GenieServerException("Unable to check process status for pid " + pid, ioe); } // TODO: Do we need retries? // This means the job client process is still running try { final CommandLine killCommand; if (this.runAsUser) { killCommand = new CommandLine("sudo"); killCommand.addArgument("kill"); } else { killCommand = new CommandLine("kill"); } killCommand.addArguments(Integer.toString(pid)); this.executor.execute(killCommand); } catch (final IOException ioe) { throw new GenieServerException("Unable to kill process " + pid, ioe); } }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java
protected boolean compileForRam(String executable, File sourceFile, File destinationFile) { try {/* w w w. j a v a2 s. c om*/ List<CLib> libs = new ArrayList<>(); libs.add(cLibs.get("simpletools")); libs.add(cLibs.get("simpletext")); libs.add(cLibs.get("simplei2c")); File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib"); Map map = new HashMap(); map.put("sourceFile", sourceFile); map.put("destinationFile", destinationFile); CommandLine cmdLine = new CommandLine(executable); for (CLib lib : libs) { cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}"); cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}"); // cmdLine.addArgument("-l" + lib.getName()); map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir())); map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm"))); } cmdLine.addArgument("-Os"); cmdLine.addArgument("-mcmm"); cmdLine.addArgument("-m32bit-doubles"); cmdLine.addArgument("-std=c99"); cmdLine.addArgument("-o").addArgument("${destinationFile}"); cmdLine.addArgument("${sourceFile}"); cmdLine.addArgument("-lm"); for (CLib lib : libs) { cmdLine.addArgument("-l" + lib.getName()); } cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); // executor.setExitValues(new int[]{402, 101}); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); try { exitValue = executor.execute(cmdLine); } catch (ExecuteException ee) { exitValue = ee.getExitValue(); logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue); success = false; return false; } finally { output = outputStream.toString(); } // System.out.println("output: " + output); /* Scanner scanner = new Scanner(output); Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?"); Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$"); while (scanner.hasNextLine()) { String portLine = scanner.nextLine(); if (chipFoundPattern.matcher(portLine).matches()) { Matcher portMatch = pattern.matcher(portLine); if (portMatch.find()) { // String port = portMatch.group("comport"); } } } */ // System.out.println("output: " + output); // System.out.println("exitValue: " + exitValue); success = true; return true; } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); success = false; return false; } }
From source file:com.tupilabs.pbs.PBS.java
/** * PBS qstat command./*from ww w. j av a 2 s . co m*/ * <p> * Equivalent to qstat -f [param] * * @param name job name * @return list of jobs */ public static List<Job> qstat(String name) { final CommandLine cmdLine = new CommandLine(COMMAND_QSTAT); cmdLine.addArgument(PARAMETER_FULL_STATUS); if (StringUtils.isNotBlank(name)) { cmdLine.addArgument(name); } final OutputStream out = new ByteArrayOutputStream(); final OutputStream err = new ByteArrayOutputStream(); DefaultExecuteResultHandler resultHandler; try { resultHandler = execute(cmdLine, null, out, err); resultHandler.waitFor(DEFAULT_TIMEOUT); } catch (ExecuteException e) { throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e); } catch (IOException e) { throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e); } catch (InterruptedException e) { throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e); } final int exitValue = resultHandler.getExitValue(); LOGGER.info("qstat exit value: " + exitValue); final List<Job> jobs; try { jobs = QSTAT_JOBS_PARSER.parse(out.toString()); } catch (ParseException pe) { throw new PBSException("Failed to parse qstat jobs output: " + pe.getMessage(), pe); } return (jobs == null ? new ArrayList<Job>(0) : jobs); }
From source file:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java
protected TestJobResult.TransformResult runTransform(long id, File executable, File workingDir, InputStream input) throws IOException { // Create the result object TestJobResult.TransformResult result = new TestJobResult.TransformResult(); CountingOutputStream output = null;/*ww w.ja va 2 s.co m*/ CountingOutputStream error = null; try { // Create and open temporary file for standard output File outputFile = File.createTempFile("job-" + Long.toString(_id), "-output", _tempDir); output = new CountingOutputStream(new FileOutputStream(outputFile)); // Create and open temporary file for standard error File errorFile = File.createTempFile("job-" + Long.toString(_id), "-error", _tempDir); error = new CountingOutputStream(new FileOutputStream(errorFile)); // If executable is relative, try to resolve in working directory // (This emulates the behavior of Streaming) if (!executable.isAbsolute()) { File resolvedExecutable = new File(workingDir, executable.toString()); if (resolvedExecutable.isFile()) { resolvedExecutable.setExecutable(true); executable = resolvedExecutable.getAbsoluteFile(); } } // Run the transform CommandLine command; if (_switchUserCommand == null) command = new CommandLine(executable); else { command = CommandLine.parse(_switchUserCommand); HashMap<String, String> substitutionMap = new HashMap<String, String>(); substitutionMap.put("cmd", executable.toString()); command.setSubstitutionMap(substitutionMap); } DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT); PumpStreamHandler pump = new PumpStreamHandler(output, error, input); executor.setWorkingDirectory(workingDir); executor.setWatchdog(dog); executor.setStreamHandler(pump); executor.setExitValues(null); int exitCode = executor.execute(command); result.setExitCode(exitCode); // Check whether it produced any output if (output.getByteCount() == 0) { output.close(); outputFile.delete(); } else result.setOutputFile(outputFile); // Check whether it produced any error output if (error.getByteCount() == 0) { error.close(); errorFile.delete(); } else result.setErrorFile(errorFile); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(error); } return result; }