List of usage examples for org.apache.commons.exec DefaultExecutor setWorkingDirectory
public void setWorkingDirectory(final File dir)
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 va2s. co 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:edu.stolaf.cs.wmrserver.TransformProcessor.java
private File compile(SubnodeConfiguration languageConf, String transformTypeString, File srcTransformFile, File jobTransformDir) throws CompilationException, IOException { // Determine correct compiler, returning if none specified String compiler = languageConf.getString("compiler-" + transformTypeString, ""); if (compiler.isEmpty()) compiler = languageConf.getString("compiler", ""); if (compiler.isEmpty()) return srcTransformFile; // Determine destination filename File compiledTransformFile = new File(jobTransformDir, "compiled-job-" + transformTypeString); // Create map to replace ${wmr:...} variables. // NOTE: Commons Configuration's built-in interpolator does not work here // for some reason. File jobTempDir = getJobTempDir(); Hashtable<String, String> variableMap = new Hashtable<String, String>(); File libDir = getLibraryDirectory(languageConf); variableMap.put("wmr:lib.dir", (libDir != null) ? libDir.toString() : ""); variableMap.put("wmr:src.dir", relativizeFile(srcTransformFile.getParentFile(), jobTempDir).toString()); variableMap.put("wmr:src.file", relativizeFile(srcTransformFile, jobTempDir).toString()); variableMap.put("wmr:dest.dir", relativizeFile(jobTransformDir, jobTempDir).toString()); variableMap.put("wmr:dest.file", relativizeFile(compiledTransformFile, jobTempDir).toString()); // Replace variables in compiler string compiler = StrSubstitutor.replace(compiler, variableMap); // Run the compiler CommandLine compilerCommand = CommandLine.parse(compiler); DefaultExecutor exec = new DefaultExecutor(); ExecuteWatchdog dog = new ExecuteWatchdog(60000); // 1 minute ByteArrayOutputStream output = new ByteArrayOutputStream(); PumpStreamHandler pump = new PumpStreamHandler(output); exec.setWorkingDirectory(jobTempDir); exec.setWatchdog(dog);// w w w .j ava 2s . c o m exec.setStreamHandler(pump); exec.setExitValues(null); // Can't get the exit code if it throws exception int exitStatus = -1; try { exitStatus = exec.execute(compilerCommand); } catch (IOException ex) { // NOTE: Exit status is still -1 in this case, since exception was thrown throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus, new String(output.toByteArray())); } // Check for successful exit if (exitStatus != 0) throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus, new String(output.toByteArray())); // Check that output exists and is readable, and make it executable if (!compiledTransformFile.isFile()) throw new CompilationException( "Compiler did not output a " + transformTypeString + " executable (or it was not a regular file).", exitStatus, new String(output.toByteArray())); if (!compiledTransformFile.canRead()) throw new IOException(StringUtils.capitalize(transformTypeString) + " executable output from compiler was not readable: " + compiledTransformFile.toString()); if (!compiledTransformFile.canExecute()) compiledTransformFile.setExecutable(true, false); return compiledTransformFile; }
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); }/*from ww w. j a v a 2 s .c o m*/ 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:net.openbyte.gui.WorkFrame.java
private void menuItem1ActionPerformed(ActionEvent e) { if (this.api == ModificationAPI.BUKKIT) { showBukkitIncompatibleFeature(); return;//from www .j a va 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;/*from ww w . j a v a2 s . c o m*/ } 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:net.openbyte.gui.WorkFrame.java
private void menuItem3ActionPerformed(ActionEvent e) { if (this.api == ModificationAPI.BUKKIT) { showBukkitIncompatibleFeature(); return;/*from w ww . j a v a2s .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:modules.GeneralNativeCommandModule.java
protected KeyValueResult extractNative(String command, String options, Path path) throws NativeExecutionException { if (command == null || command.equals("")) { System.err.println("command null at GeneralNativeCommandModule.extractNative()"); return null; }/*from w w w.j av a 2 s. c o 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); } DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig(); executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout)); if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) { executor.setWorkingDirectory(getConfig().workingDirectory); } try { // System.out.println(commandLine); executor.execute(commandLine); } catch (ExecuteException xs) { NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.toString(); n.exitCode = xs.getExitValue(); throw n; } catch (IOException xs) { // System.out.println(commandLine); NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.toString(); throw n; } KeyValueResult t = new KeyValueResult("GeneralNativeCommandResults"); t.add("fullOutput", outputStream.toString().trim()); return t; }
From source file:modules.NativeProcessIterativeDaemonModule.java
protected String extractNative(String command, String options, Path path) throws NativeExecutionException { if (command == null || command.equals("")) { System.err.println("command null at GeneralNativeCommandModule.extractNative()"); return null; }/*from w w w. ja v a 2s . c om*/ 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); } DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig(); executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout)); if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) { executor.setWorkingDirectory(getConfig().workingDirectory); } try { // System.out.println("Now execute " + commandLine); executor.execute(commandLine); } catch (ExecuteException xs) { NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.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(); } n.executionResult = outputStream.toString(); throw n; } return outputStream.toString().trim(); }
From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java
/** * This calls a TIBCO binary.//from www .j a v a 2 s. co m * * @param binary, the TIBCO binary file to execute * @param tras, the TRA files associated with the TIBCO binary * @param arguments, command-line arguments * @param workingDir, working directory from where the binary is launched * @param errorMsg, error message to display in case of a failure * @param fork, if true the chiild process will be detached from the caller * * @throws IOException * @throws MojoExecutionException */ protected int launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir, String errorMsg, boolean fork, boolean synchronous) throws IOException, MojoExecutionException { Integer result = 0; if (tras == null) { // no value specified as Mojo parameter, we use the .tra in the same directory as the binary String traPathFileName = binary.getAbsolutePath(); traPathFileName = FilenameUtils.removeExtension(traPathFileName); traPathFileName += ".tra"; tras = new ArrayList<File>(); tras.add(new File(traPathFileName)); } HashMap<File, File> trasMap = new HashMap<File, File>(); for (File tra : tras) { // copy of ".tra" file in the working directory File tmpTRAFile = new File(directory, tra.getName()); trasMap.put(tra, tmpTRAFile); copyFile(tra, tmpTRAFile); } for (File tra : trasMap.keySet()) { if (trasMap.containsKey(tibcoDesignerTRAPath) && ((tibcoBuildEARUseDesignerTRA && tra == tibcoBuildEARTRAPath) || (tibcoBuildLibraryUseDesignerTRA && tra == tibcoBuildLibraryTRAPath))) { if (tras.size() > 1) { ReplaceRegExp replaceRegExp = new ReplaceRegExp(); replaceRegExp.setFile(trasMap.get(tra)); replaceRegExp.setMatch("tibco.include.tra (.*/designer.tra)"); replaceRegExp.setReplace( "tibco.include.tra " + trasMap.get(tibcoDesignerTRAPath).toString().replace('\\', '/')); replaceRegExp.setByLine(true); replaceRegExp.execute(); } } if (tra == tibcoBuildEARTRAPath || tra == tibcoDesignerTRAPath || tra == tibcoBWEngineTRAPath) { // FIXME: should check more properly // append user.home at the end to force the use of custom Designer5.prefs PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(trasMap.get(tra), true))); out.println(""); out.println("java.property.user.home=" + directory.getAbsolutePath().replace("\\", "/")); out.close(); } } CommandLine cmdLine = new CommandLine(binary); for (String argument : arguments) { cmdLine.addArgument(argument); } getLog().debug("launchTIBCOBinary command line : " + cmdLine.toString()); getLog().debug("working dir : " + workingDir); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workingDir); if (timeOut > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut * 1000); executor.setWatchdog(watchdog); } executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); ByteArrayOutputStream stdOutAndErr = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(stdOutAndErr)); if (fork) { CommandLauncher commandLauncher = CommandLauncherFactory.createVMLauncher(); commandLauncher.exec(cmdLine, null, workingDir); } else { try { if (synchronous) { result = executor.execute(cmdLine); } else { executor.execute(cmdLine, new DefaultExecuteResultHandler()); } } catch (ExecuteException e) { // TODO : grer erreurs des excutables (ventuellement parser les erreurs classiques) getLog().info(cmdLine.toString()); getLog().info(stdOutAndErr.toString()); getLog().info(result.toString()); throw new MojoExecutionException(errorMsg, e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } return result; }
From source file:net.sourceforge.seqware.pipeline.plugins.ITUtility.java
/** * Run an arbitrary command and check it against an expected return value * * @param line/* w ww .j a v a 2 s. co m*/ * @param expectedReturnValue * @param dir working directory, can be null if you don't want to change directories * @return * @throws IOException */ public static String runArbitraryCommand(String line, int expectedReturnValue, File dir) throws IOException { Log.info("Running " + line); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(line); DefaultExecutor exec = new DefaultExecutor(); if (dir != null) { exec.setWorkingDirectory(dir); } PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); exec.setExitValue(expectedReturnValue); try { int exitValue = exec.execute(commandline); Assert.assertTrue( "exit value for full jar with no params should be " + expectedReturnValue + " was " + exitValue, exitValue == expectedReturnValue); String output = outputStream.toString(); return output; } catch (ExecuteException e) { Log.error("Execution failed with:"); Log.error(outputStream.toString()); throw e; } }