List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor
public DefaultExecutor()
From source file:com.jaeksoft.searchlib.ocr.OcrManager.java
private final int run(CommandLine cmdLine, int secTimeOut, Integer expectedExitValue, StringBuilder returnedText) throws IOException, SearchLibException { DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {/* w w w.j a v a 2 s . co m*/ Logging.info("LOG OCR: " + cmdLine); PumpStreamHandler streamHandler = new PumpStreamHandler(baos); executor.setStreamHandler(streamHandler); if (expectedExitValue != null) executor.setExitValue(expectedExitValue); ExecuteWatchdog watchdog = new ExecuteWatchdog(secTimeOut * 1000); executor.setWatchdog(watchdog); int ev = executor.execute(cmdLine); if (expectedExitValue != null) if (ev != expectedExitValue) throw new SearchLibException("Bad exit value (" + ev + ") "); if (returnedText != null) returnedText.append(baos.toString("UTF-8")); return ev; } finally { if (baos != null) IOUtils.closeQuietly(baos); } }
From source file:gr.upatras.ece.nam.baker.impl.InstalledBunLifecycleMgmt.java
public int executeSystemCommand(String cmdStr) { logger.info(" ================> Execute :" + cmdStr); CommandLine cmdLine = CommandLine.parse(cmdStr); final Executor executor = new DefaultExecutor(); // create the executor and consider the exitValue '0' as success executor.setExitValue(0);//from www . j a v a 2 s . c o m ByteArrayOutputStream out = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(out); executor.setStreamHandler(streamHandler); int exitValue = -1; try { exitValue = executor.execute(cmdLine); logger.info(" ================> EXIT (" + exitValue + ") FROM :" + cmdStr); } catch (ExecuteException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } logger.info("out>" + out); return exitValue; }
From source file:cc.arduino.contributions.packages.ContributionInstaller.java
private void executeScripts(File folder, Collection<File> postInstallScripts, boolean trusted, boolean trustAll) throws IOException { File script = postInstallScripts.iterator().next(); if (!trusted && !trustAll) { System.err.println(/* ww w . j a va 2s .c om*/ I18n.format(tr("Warning: non trusted contribution, skipping script execution ({0})"), script)); return; } if (trustAll) { System.err.println(I18n.format(tr("Warning: forced untrusted script execution ({0})"), script)); } ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); Executor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(stdout, stderr)); executor.setWorkingDirectory(folder); executor.setExitValues(null); int exitValue = executor.execute(new CommandLine(script)); executor.setExitValues(new int[0]); System.out.write(stdout.toByteArray()); System.err.write(stderr.toByteArray()); if (executor.isFailure(exitValue)) { throw new IOException(); } }
From source file:com.mooregreatsoftware.gitprocess.lib.Pusher.java
private static ThePushResult doGitProgPush(GitLib gitLib, Branch localBranch, String remoteBranchName, boolean forcePush, String remoteName) { String cmd = String.format("git push --porcelain %s %s %s:%s", remoteName, forcePush ? "--force" : "", localBranch.shortName(), remoteBranchName); CommandLine commandLine = CommandLine.parse(cmd); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(gitLib.workingDirectory()); final StringWriter stdOutWriter = new StringWriter(); final StringWriter stdErrWriter = new StringWriter(); executor.setStreamHandler(// ww w .j a v a2 s .c o m new PumpStreamHandler(new WriterOutputStream(stdOutWriter), new WriterOutputStream(stdErrWriter))); final int exitCode = Try.of(() -> { try { return executor.execute(commandLine); } catch (ExecuteException e) { return e.getExitValue(); } catch (IOException e) { final String message = e.getMessage(); if (message != null && message.contains("No such file or directory")) { return 1; } e.printStackTrace(); return -1; } }).get(); return new ProcPushResult(stdOutWriter, stdErrWriter, exitCode); }
From source file:com.googlecode.mycontainer.maven.plugin.ExecMojo.java
/** * priority in the execute method will be to use System properties arguments * over the pom specification.//from ww w.j a va2 s . c o m * * @throws MojoExecutionException * if a failure happens */ public void execute() throws MojoExecutionException { try { if (isSkip()) { getLog().info("skipping execute as per configuraion"); return; } if (basedir == null) { throw new IllegalStateException("basedir is null. Should not be possible."); } String argsProp = getSystemProperty("exec.args"); List commandArguments = new ArrayList(); if (hasCommandlineArgs()) { String[] args = parseCommandlineArgs(); for (int i = 0; i < args.length; i++) { if (isLongClassPathArgument(args[i])) { // it is assumed that starting from -cp or -classpath // the arguments // are: -classpath/-cp %classpath mainClass // the arguments are replaced with: -jar // $TMP/maven-exec.jar // NOTE: the jar will contain the classpath and the main // class commandArguments.add("-jar"); File tmpFile = createJar(computeClasspath(null), args[i + 2]); commandArguments.add(tmpFile.getAbsolutePath()); i += 2; } else if (CLASSPATH_TOKEN.equals(args[i])) { commandArguments.add(computeClasspathString(null)); } else { commandArguments.add(args[i]); } } } else if (!isEmpty(argsProp)) { getLog().debug("got arguments from system properties: " + argsProp); try { String[] args = CommandLineUtils.translateCommandline(argsProp); commandArguments.addAll(Arrays.asList(args)); } catch (Exception e) { throw new MojoExecutionException("Couldn't parse systemproperty 'exec.args'"); } } else { if (arguments != null) { for (int i = 0; i < arguments.size(); i++) { Object argument = arguments.get(i); String arg; 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 if (argument instanceof String && isLongClassPathArgument((String) argument)) { // it is assumed that starting from -cp or // -classpath the arguments // are: -classpath/-cp %classpath mainClass // the arguments are replaced with: -jar // $TMP/maven-exec.jar // NOTE: the jar will contain the classpath and the // main class commandArguments.add("-jar"); File tmpFile = createJar(computeClasspath((Classpath) arguments.get(i + 1)), (String) arguments.get(i + 2)); commandArguments.add(tmpFile.getAbsolutePath()); i += 2; } else if (argument instanceof Classpath) { Classpath specifiedClasspath = (Classpath) argument; arg = computeClasspathString(specifiedClasspath); commandArguments.add(arg); } else { arg = argument.toString(); commandArguments.add(arg); } } } } Map enviro = new HashMap(); try { Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); enviro.putAll(systemEnvVars); } catch (IOException x) { getLog().error("Could not assign default system enviroment variables.", x); } if (environmentVariables != null) { Iterator iter = environmentVariables.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); String value = (String) environmentVariables.get(key); enviro.put(key, value); } } if (workingDirectory == null) { workingDirectory = basedir; } if (!workingDirectory.exists()) { getLog().debug("Making working directory '" + workingDirectory.getAbsolutePath() + "'."); if (!workingDirectory.mkdirs()) { throw new MojoExecutionException( "Could not make working directory: '" + workingDirectory.getAbsolutePath() + "'"); } } CommandLine commandLine = getExecutablePath(enviro, workingDirectory); Executor exec = new DefaultExecutor(); String[] args = new String[commandArguments.size()]; for (int i = 0; i < commandArguments.size(); i++) { args[i] = (String) commandArguments.get(i); } commandLine.addArguments(args, false); exec.setWorkingDirectory(workingDirectory); // this code ensures the output gets logged vai maven logging, but // at the same time prevents // partial line output, like input prompts. // final Log outputLog = getExecOutputLog(); // LogOutputStream stdout = new LogOutputStream() // { // protected void processLine( String line, int level ) // { // outputLog.info( line ); // } // }; // // LogOutputStream stderr = new LogOutputStream() // { // protected void processLine( String line, int level ) // { // outputLog.info( line ); // } // }; OutputStream stdout = System.out; OutputStream stderr = System.err; try { getLog().debug("Executing command line: " + commandLine); int resultCode = executeCommandLine(exec, commandLine, enviro, stdout, stderr); if (isResultCodeAFailure(resultCode)) { throw new MojoExecutionException( "Result of " + commandLine + " execution is: '" + resultCode + "'."); } } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } registerSourceRoots(); } catch (IOException e) { throw new MojoExecutionException("I/O Error", e); } }
From source file:net.openbyte.gui.WorkFrame.java
private void menuItem3ActionPerformed(ActionEvent e) { if (this.api == ModificationAPI.BUKKIT) { showBukkitIncompatibleFeature(); return;/*from ww w . j a v a2 s.c o m*/ } System.out.println("Building modification JAR."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild() .forTasks("build").run(); return null; } }; if (this.api == ModificationAPI.MCP) { // recompile and reobfuscate worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (System.getProperty("os.name").startsWith("Windows")) { Runtime.getRuntime().exec("cmd /c recompile.bat", null, workDirectory); Runtime.getRuntime().exec("cmd /c reobfuscate.bat", null, workDirectory); return null; } try { CommandLine recompile = CommandLine.parse("python " + new File(new File(workDirectory, "runtime"), "recompile.py").getAbsolutePath() + " $@"); CommandLine reobfuscate = CommandLine.parse("python " + new File(new File(workDirectory, "runtime"), "reobfuscate.py").getAbsolutePath() + " $@"); File recompilePy = new File(new File(workDirectory, "runtime"), "recompile.py"); File reobfuscatePy = new File(new File(workDirectory, "runtime"), "reobfuscate.py"); CommandLine authRecompile = CommandLine.parse("chmod 755 " + recompilePy.getAbsolutePath()); CommandLine authReobfuscate = CommandLine .parse("chmod 755 " + reobfuscatePy.getAbsolutePath()); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workDirectory); executor.execute(authRecompile); executor.execute(authReobfuscate); executor.execute(recompile); executor.execute(reobfuscate); System.out.println("Finished building modification JAR."); } catch (Exception e) { e.printStackTrace(); } return null; } }; } worker.execute(); }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java
protected boolean compileForEeprom(String executable, File sourceFile, File destinationFile) { try {/*from ww w . j av a 2s . com*/ 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:kr.motd.maven.exec.ExecMojo.java
/** * priority in the execute method will be to use System properties arguments over the pom specification. * * @throws MojoExecutionException if a failure happens *///from ww w .j av a 2 s . co m public void execute() throws MojoExecutionException { if (isSkip()) { getLog().info("skipping execute as per configuraion"); return; } if (basedir == null) { throw new IllegalStateException("basedir is null. Should not be possible."); } try { handleWorkingDirectory(); String argsProp = getSystemProperty("exec.args"); List<String> commandArguments = new ArrayList<String>(); if (hasCommandlineArgs()) { handleCommandLineArgs(commandArguments); } else if (!StringUtils.isEmpty(argsProp)) { handleSystemPropertyArguments(argsProp, commandArguments); } else { if (arguments != null) { handleArguments(commandArguments); } } Map<String, String> enviro = handleSystemEnvVariables(); CommandLine commandLine = getExecutablePath(enviro, workingDirectory); String[] args = commandArguments.toArray(new String[commandArguments.size()]); commandLine.addArguments(args, false); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(workingDirectory); fillSuccessCodes(exec); getLog().debug("Executing command line: " + commandLine); try { int resultCode; if (outputFile != null) { if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) { getLog().warn( "Could not create non existing parent directories for log file: " + outputFile); } FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(outputFile); resultCode = executeCommandLine(exec, commandLine, enviro, outputStream); } finally { IOUtil.close(outputStream); } } else { resultCode = executeCommandLine(exec, commandLine, enviro, System.out, System.err); } if (isResultCodeAFailure(resultCode)) { throw new MojoExecutionException( "Result of " + commandLine + " execution is: '" + resultCode + "'."); } } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } registerSourceRoots(); } catch (IOException e) { throw new MojoExecutionException("I/O Error", e); } }
From source file:io.selendroid.android.impl.AbstractDevice.java
private void startLogging() { logoutput = new ByteArrayOutputStream(); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(new PumpStreamHandler(logoutput)); CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S", "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S", "ActivityThread:S", "-v", "time"); log.info("starting logcat:"); log.fine(command.toString());/*from w ww . j a v a 2 s . com*/ try { exec.execute(command, new DefaultExecuteResultHandler()); logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); exec.setWatchdog(logcatWatchdog); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.alibaba.jstorm.yarn.utils.JStormUtils.java
/** * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler If it is frontend, ByteArrayOutputStream.toString get the result * <p/>//from w ww .j a v a 2 s. c o m * This function don't care whether the command is successfully or not * * @param command * @param environment * @param workDir * @param resultHandler * @return * @throws IOException */ @Deprecated public static ByteArrayOutputStream launchProcess(String command, final Map environment, final String workDir, ExecuteResultHandler resultHandler) throws IOException { String[] cmdlist = command.split(" "); CommandLine cmd = new CommandLine(cmdlist[0]); for (String cmdItem : cmdlist) { if (StringUtils.isBlank(cmdItem) == false) { cmd.addArgument(cmdItem); } } DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); if (StringUtils.isBlank(workDir) == false) { executor.setWorkingDirectory(new File(workDir)); } ByteArrayOutputStream out = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(out, out); if (streamHandler != null) { executor.setStreamHandler(streamHandler); } try { if (resultHandler == null) { executor.execute(cmd, environment); } else { executor.execute(cmd, environment, resultHandler); } } catch (ExecuteException e) { // @@@@ // failed to run command } return out; }