List of usage examples for org.apache.commons.exec DefaultExecutor execute
public int execute(final CommandLine command) throws ExecuteException, IOException
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 .j a v a 2 s . c o 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; }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java
protected boolean compileForEeprom(String executable, File sourceFile, File destinationFile) { try {// w w w.j a va 2 s .c o m 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:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java
protected boolean compileForRam(String executable, File sourceFile, File destinationFile) { try {//from ww w . j av a2s . c o m 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:io.takari.maven.plugins.compile.javac.CompilerJavacLauncher.java
private void compile(File options, File output, final Map<File, Resource<File>> sources) throws IOException { new CompilerConfiguration(getSourceEncoding(), getCompilerOptions(), sources.keySet()).write(options); // use the same JVM as the one used to run Maven (the "java.home" one) String executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; if (File.separatorChar == '\\') { executable = executable + ".exe"; }// w ww .j a v a2 s .c o m CommandLine cli = new CommandLine(executable); // jvm options cli.addArguments(new String[] { "-cp", jar.getAbsolutePath() }); if (meminitial != null) { cli.addArgument("-Xms" + meminitial); } if (maxmem != null) { cli.addArgument("-Xmx" + maxmem); } // main class and program arguments cli.addArgument(CompilerJavacForked.class.getName()); cli.addArgument(options.getAbsolutePath(), false); cli.addArgument(output.getAbsolutePath(), false); DefaultExecutor executor = new DefaultExecutor(); // ExecuteWatchdog watchdog = null; // if (forkedProcessTimeoutInSeconds > 0) { // watchdog = new ExecuteWatchdog(forkedProcessTimeoutInSeconds * 1000L); // executor.setWatchdog(watchdog); // } // best effort to avoid orphaned child process executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); executor.setWorkingDirectory(basedir); log.debug("External java process command line:\n {}", cli); try { executor.execute(cli); // this throws ExecuteException if process return code != 0 } catch (ExecuteException e) { if (!log.isDebugEnabled()) { log.info("External java process command line:\n {}", cli); } throw e; } final Map<File, Output<File>> outputs = new HashMap<File, Output<File>>(); CompilerOutput.process(output, new CompilerOutputProcessor() { @Override public void processOutput(File inputFile, File outputFile) { outputs.put(outputFile, context.processOutput(outputFile)); } @Override public void addMessage(String path, int line, int column, String message, MessageSeverity kind) { if (".".equals(path)) { context.addPomMessage(message, kind, null); } else { File file = new File(path); Resource<File> resource = sources.get(file); if (resource == null) { resource = outputs.get(file); } if (resource != null) { if (isShowWarnings() || kind != MessageSeverity.WARNING) { resource.addMessage(line, column, message, kind, null); } } else { log.warn("Unexpected java resource {}", file); } } } @Override public void addLogMessage(String message) { log.warn(message); } }); }
From source file:net.openbyte.gui.WorkFrame.java
private void menuItem1ActionPerformed(ActionEvent e) { if (this.api == ModificationAPI.BUKKIT) { showBukkitIncompatibleFeature(); return;//w ww . j a v a 2s. c o m } System.out.println("Starting client..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild() .forTasks("runClient").run(); return null; } }; if (this.api == ModificationAPI.MCP) { worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (System.getProperty("os.name").startsWith("Windows")) { Runtime.getRuntime().exec("cmd /c startclient.bat", null, workDirectory); return null; } try { CommandLine startClient = CommandLine.parse("python " + new File(new File(workDirectory, "runtime"), "startclient.py").getAbsolutePath() + " $@"); CommandLine authClient = CommandLine.parse("chmod 755 " + new File(new File(workDirectory, "runtime"), "startclient.py").getAbsolutePath()); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workDirectory); executor.execute(authClient); executor.execute(startClient); } catch (Exception e) { e.printStackTrace(); } return null; } }; } worker.execute(); }
From source file:net.openbyte.gui.WorkFrame.java
private void menuItem2ActionPerformed(ActionEvent e) { if (this.api == ModificationAPI.BUKKIT) { showBukkitIncompatibleFeature(); return;//www . java 2s . c om } System.out.println("Starting server..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild() .forTasks("runServer").run(); return null; } }; if (this.api == ModificationAPI.MCP) { worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (System.getProperty("os.name").startsWith("Windows")) { Runtime.getRuntime().exec("cmd /c startserver.bat", null, workDirectory); return null; } try { CommandLine startServer = CommandLine.parse("python " + new File(new File(workDirectory, "runtime"), "startserver.py").getAbsolutePath() + " $@"); CommandLine authServer = CommandLine.parse("chmod 755 " + new File(new File(workDirectory, "runtime"), "startserver.py").getAbsolutePath()); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workDirectory); executor.execute(authServer); executor.execute(startServer); } catch (Exception e) { e.printStackTrace(); } return null; } }; } worker.execute(); }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java
/** * * * @param executable/*w w w. j ava 2 s. co m*/ * @param sourceFile * @return */ protected boolean compile(String executable, File sourceFile) { try { List<CLib> libs = new ArrayList<>(); libs.add(cLibs.get("simpletools")); libs.add(cLibs.get("simpletext")); libs.add(cLibs.get("simplei2c")); File temporaryDestinationFile = File.createTempFile("blocklyapp", ".elf"); File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib"); Map map = new HashMap(); map.put("sourceFile", sourceFile); map.put("destinationFile", temporaryDestinationFile); 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("-fno-exceptions"); 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[] { 0, 1 }); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); try { System.out.println(cmdLine); exitValue = executor.execute(cmdLine); } catch (ExecuteException ee) { exitValue = ee.getExitValue(); logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue); success = false; return false; } finally { temporaryDestinationFile.delete(); 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:net.openbyte.gui.WorkFrame.java
private void menuItem3ActionPerformed(ActionEvent e) { if (this.api == ModificationAPI.BUKKIT) { showBukkitIncompatibleFeature(); return;//from w ww .ja v a 2 s . com } 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:com.nts.alphamale.shell.AdbShellExecutor.java
/** * @param cmd adb /*from www . ja v a2s . co m*/ * @param synch ? ? true: synchronous, false: asynchronous * @param (ms) * @return Executor Standard Output? Map */ public Map<String, Object> execute(CommandLine cmd, boolean synch, long timeoutMilliseconds) { Map<String, Object> executorMap = new HashMap<String, Object>(); DefaultExecutor executor = new DefaultExecutor(); PipedOutputStream pos = new PipedOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(pos, System.err); streamHandler.setStopTimeout(timeoutMilliseconds); DataInputStream dis = null; try { dis = new DataInputStream(new PipedInputStream(pos)); } catch (IOException e) { //log.error(e.getCause() + " : " + e.getMessage()); } executor.setStreamHandler(streamHandler); ExecuteWatchdog watchDog = new ExecuteWatchdog(timeoutMilliseconds); executor.setWatchdog(watchDog); try { if (synch) executor.execute(cmd); else executor.execute(cmd, new DefaultExecuteResultHandler()); log.debug(cmd.toString()); LineIterator li = IOUtils.lineIterator(dis, "UTF-8"); if (li != null) { executorMap.put("executor", executor); executorMap.put("stdOut", li); } } catch (Exception e) { log.error(e.getCause() + ":" + e.getMessage() + "[" + cmd + "]"); } return executorMap; }
From source file:com.virtualparadigm.packman.processor.JPackageManagerOld.java
public static boolean autorun(File autorunDir) { logger.info("PackageManager::autorun()"); boolean status = true; if (autorunDir != null && autorunDir.isDirectory()) { File[] autorunFiles = autorunDir.listFiles(); Arrays.sort(autorunFiles); String fileExtension = null; DefaultExecutor cmdExecutor = new DefaultExecutor(); // String sqlScriptFilePath = null; // Reader sqlScriptReader = null; // Properties sqlScriptProperties = null; for (File autorunFile : autorunFiles) { if (!autorunFile.isDirectory()) { try { fileExtension = FilenameUtils.getExtension(autorunFile.getAbsolutePath()); if (fileExtension != null) { if (fileExtension.equalsIgnoreCase("bat") || fileExtension.equalsIgnoreCase("sh")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath())); } else if (fileExtension.equalsIgnoreCase("sql") || fileExtension.equalsIgnoreCase("ddl")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); // look for properties file named same as script file for connection properties // sqlScriptFilePath = autorunFile.getAbsolutePath(); // sqlScriptProperties = PropertyLoader.loadProperties(sqlScriptFilePath.substring(0, sqlScriptFilePath.length()-3) + "properties"); // sqlScriptReader = new FileReader(autorunFile.getAbsolutePath()); } else if (fileExtension.equalsIgnoreCase("jar")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); }/*from w w w .j a va 2 s . c o m*/ } } catch (Exception e) { logger.error("", e); e.printStackTrace(); } } } } return status; }