List of usage examples for org.apache.commons.exec DefaultExecutor setWorkingDirectory
public void setWorkingDirectory(final File dir)
From source file:com.blackducksoftware.tools.scmconnector.core.CommandLineExecutor.java
@Override public int executeCommand(Logger log, CommandLine command, File targetDir, String promptResponse) throws Exception { DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0);/*from www . java 2 s .c om*/ PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHangler(log, Level.INFO)); executor.setStreamHandler(psh); providePromptResponse(psh, promptResponse); executor.setWorkingDirectory(targetDir); // This log msg would reveal password // log.info("Command: " + command.toString() + " executed in: " // + targetDir.toString()); int exitStatus = 1; try { exitStatus = executor.execute(command, EnvironmentUtils.getProcEnvironment()); } catch (Exception e) { log.error("Failure executing Command: " + e.getMessage()); } return exitStatus; }
From source file:io.takari.maven.testing.executor.ForkedLauncher.java
public int run(String[] cliArgs, Map<String, String> envVars, File multiModuleProjectDirectory, File workingDirectory, File logFile) throws IOException, LauncherException { String javaHome;//from ww w. j a v a 2 s .c o m if (envVars == null || envVars.get("JAVA_HOME") == null) { javaHome = System.getProperty("java.home"); } else { javaHome = envVars.get("JAVA_HOME"); } File executable = new File(javaHome, Os.isFamily(Os.FAMILY_WINDOWS) ? "bin/javaw.exe" : "bin/java"); CommandLine cli = new CommandLine(executable); cli.addArgument("-classpath").addArgument(classworldsJar.getAbsolutePath()); cli.addArgument("-Dclassworlds.conf=" + new File(mavenHome, "bin/m2.conf").getAbsolutePath()); cli.addArgument("-Dmaven.home=" + mavenHome.getAbsolutePath()); cli.addArgument("-Dmaven.multiModuleProjectDirectory=" + multiModuleProjectDirectory.getAbsolutePath()); cli.addArgument("org.codehaus.plexus.classworlds.launcher.Launcher"); cli.addArguments(args.toArray(new String[args.size()])); if (extensions != null && !extensions.isEmpty()) { cli.addArgument("-Dmaven.ext.class.path=" + toPath(extensions)); } cli.addArguments(cliArgs); Map<String, String> env = new HashMap<>(); if (mavenHome != null) { env.put("M2_HOME", mavenHome.getAbsolutePath()); } if (envVars != null) { env.putAll(envVars); } if (envVars == null || envVars.get("JAVA_HOME") == null) { env.put("JAVA_HOME", System.getProperty("java.home")); } DefaultExecutor executor = new DefaultExecutor(); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); executor.setWorkingDirectory(workingDirectory.getAbsoluteFile()); try (OutputStream log = new FileOutputStream(logFile)) { PrintStream out = new PrintStream(log); out.format("Maven Executor implementation: %s\n", getClass().getName()); out.format("Maven home: %s\n", mavenHome); out.format("Build work directory: %s\n", workingDirectory); out.format("Environment: %s\n", env); out.format("Command line: %s\n\n", cli.toString()); out.flush(); PumpStreamHandler streamHandler = new PumpStreamHandler(log); executor.setStreamHandler(streamHandler); return executor.execute(cli, env); // this throws ExecuteException if process return code != 0 } catch (ExecuteException e) { throw new LauncherException("Failed to run Maven: " + e.getMessage() + "\n" + cli, e); } }
From source file:com.blackducksoftware.tools.scmconnector.core.CommandLineExecutor.java
@Override public CommandResults executeCommandForOutput(Logger log, CommandLine command, File targetDir) throws Exception { DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0);/*from www . ja v a 2s . c o m*/ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(outputStream); executor.setStreamHandler(psh); int exitStatus = 1; executor.setWorkingDirectory(targetDir); exitStatus = executor.execute(command); String outputString = outputStream.toString(); // This log msg would reveal password // log.info("Command: " + command.toString() + " executed in: " // + targetDir.toString() + "; output: " + outputString); return new CommandResults(exitStatus, outputString); }
From source file:com.walmart.gatling.commons.ReportExecutor.java
private void runJob(Master.GenerateReport job) { TaskEvent taskEvent = job.reportJob.taskEvent; CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand()); Map<String, Object> map = new HashMap<>(); map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName()))); cmdLine.addArgument("${path}"); //parameters come from the task event for (Pair<String, String> pair : taskEvent.getParameters()) { cmdLine.addArgument(pair.getValue()); }/*from w w w . j a v a 2s.c o m*/ String dir = agentConfig.getJob().getLogDirectory() + "reports/" + job.reportJob.trackingId + "/"; cmdLine.addArgument(dir); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(agentConfig.getJob().getExitValues()); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); executor.setWorkingDirectory(new File(agentConfig.getJob().getPath())); FileOutputStream outFile = null; FileOutputStream errorFile = null; try { List<String> resultFiles = new ArrayList<>(job.results.size()); //download all files adn /*int i=0; for (Worker.Result result : job.results) { String destFile = dir + i++ + ".log"; resultFiles.add(destFile); DownloadFile.downloadFile(result.metrics,destFile); }*/ AtomicInteger index = new AtomicInteger(); job.results.parallelStream().forEach(result -> { String destFile = dir + index.incrementAndGet() + ".log"; resultFiles.add(destFile); DownloadFile.downloadFile(result.metrics, destFile); }); String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.reportJob.trackingId); String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.reportJob.trackingId); //create the std and err files outFile = FileUtils.openOutputStream(new File(outPath)); errorFile = FileUtils.openOutputStream(new File(errPath)); PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile), new ExecLogHandler(errorFile)); executor.setStreamHandler(psh); System.out.println(cmdLine); int exitResult = executor.execute(cmdLine); ReportResult result; if (executor.isFailure(exitResult)) { result = new ReportResult(dir, job.reportJob, false); log.info("Report Executor Failed, result: " + job.toString()); } else { result = new ReportResult(job.reportJob.getHtml(), job.reportJob, true); log.info("Report Executor Completed, result: " + result.toString()); } for (String resultFile : resultFiles) { FileUtils.deleteQuietly(new File(resultFile)); } getSender().tell(result, getSelf()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { IOUtils.closeQuietly(outFile); IOUtils.closeQuietly(errorFile); } }
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;//from w w w. j a va2 s .com 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:de.akquinet.innovation.play.maven.Play2PackageMojo.java
private void packageApplication() throws MojoExecutionException { String line = getPlay2().getAbsolutePath(); CommandLine cmdLine = CommandLine.parse(line); cmdLine.addArgument("package"); DefaultExecutor executor = new DefaultExecutor(); if (timeout > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog);//w w w. j av a 2 s. co m } executor.setWorkingDirectory(project.getBasedir()); executor.setExitValue(0); try { executor.execute(cmdLine, getEnvironment()); } catch (IOException e) { throw new MojoExecutionException("Error during packaging", e); } }
From source file:de.akquinet.innovation.play.maven.Play2PackageMojo.java
private void packageDistribution() throws MojoExecutionException { String line = getPlay2().getAbsolutePath(); CommandLine cmdLine = CommandLine.parse(line); cmdLine.addArgument("dist"); DefaultExecutor executor = new DefaultExecutor(); if (timeout > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog);//from ww w . j a v a 2s . com } executor.setWorkingDirectory(project.getBasedir()); executor.setExitValue(0); try { executor.execute(cmdLine, getEnvironment()); } catch (IOException e) { throw new MojoExecutionException("Error during distribution creation", e); } }
From source file:net.openbyte.gui.CreateProjectFrame.java
public void doOperations() { createProjectFolder();/* ww w. java 2 s .c o m*/ monitor.setProgress(20); monitor.setNote("Creating solution for project..."); createSolutionFile(); monitor.setNote("Creating library solution for project..."); createLibrarySolution(); monitor.setProgress(60); monitor.setNote("Cloning API..."); cloneAPI(); monitor.setProgress(90); monitor.setNote("Decompiling Minecraft..."); if (this.api == ModificationAPI.MCP) { if (System.getProperty("os.name").startsWith("Windows")) { try { Runtime.getRuntime().exec("cmd /c decompile.bat", null, projectFolder); } catch (IOException e) { e.printStackTrace(); } } else { try { CommandLine commandLine = CommandLine.parse("python " + new File(new File(projectFolder, "runtime"), "decompile.py").getAbsolutePath() + " $@"); File runtimePythonDirectory = new File(projectFolder, "runtime"); File decompilePython = new File(runtimePythonDirectory, "decompile.py"); CommandLine authPy = CommandLine.parse("chmod 755 " + decompilePython.getAbsolutePath()); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(projectFolder); executor.execute(authPy); executor.execute(commandLine); } catch (Exception e) { e.printStackTrace(); } } } if (this.api == ModificationAPI.MINECRAFT_FORGE) { GradleConnector.newConnector().forProjectDirectory(projectFolder).connect().newBuild() .setJvmArguments("-XX:-UseGCOverheadLimit").forTasks("setupDecompWorkspace").run(); } monitor.close(); WelcomeFrame welcomeFrame = new WelcomeFrame(); welcomeFrame.setVisible(true); }
From source file:com.alibaba.jstorm.utils.JStormUtils.java
/** * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler If it is frontend, ByteArrayOutputStream.toString get the result * <p/>/* w w w . j a v a2 s . co m*/ * This function don't care whether the command is successfully or not * * @param command * @param environment * @param workDir * @param resultHandler * @return * @throws IOException */ 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; }
From source file:com.walmart.gatling.commons.ScriptExecutor.java
private Object runJob(Object message) { Master.Job job = (Master.Job) message; TaskEvent taskEvent = (TaskEvent) job.taskEvent; CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand()); log.info("Verified Script worker received task: {}", message); Map<String, Object> map = new HashMap<>(); if (StringUtils.isNotEmpty(agentConfig.getJob().getMainClass())) cmdLine.addArgument(agentConfig.getJob().getCpOrJar()); map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName()))); cmdLine.addArgument("${path}"); if (!StringUtils.isEmpty(agentConfig.getJob().getMainClass())) { cmdLine.addArgument(agentConfig.getJob().getMainClass()); }/*from w ww.j a va2s .c om*/ //parameters come from the task event for (Pair<String, String> pair : taskEvent.getParameters()) { cmdLine.addArgument(pair.getValue()); } cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId, job.jobId)); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(agentConfig.getJob().getExitValues()); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); executor.setWorkingDirectory(new File(agentConfig.getJob().getPath())); FileOutputStream outFile = null; FileOutputStream errorFile = null; String outPath = "", errPath = ""; try { outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.jobId); errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.jobId); //create the std and err files outFile = FileUtils.openOutputStream(new File(outPath)); errorFile = FileUtils.openOutputStream(new File(errPath)); PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile), new ExecLogHandler(errorFile)); executor.setStreamHandler(psh); log.info("command: {}", cmdLine); int exitResult = executor.execute(cmdLine); //executor.getWatchdog().destroyProcess(). Worker.Result result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), null, job); log.info("Exit code: {}", exitResult); if (executor.isFailure(exitResult) || exitResult == 1) { log.info("Script Executor Failed, job: " + job.jobId); //getSender().tell(new Worker.WorkFailed(result), getSelf()); return new Worker.WorkFailed(result); } else { result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), agentConfig.getUrl(getMetricsPath(job)), job); log.info("Script Executor Completed, job: " + result); //getSender().tell(new Worker.WorkComplete(result), getSelf()); return new Worker.WorkComplete(result); } } catch (IOException e) { log.error(e.toString()); Worker.Result result = new Worker.Result(-1, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), null, job); log.info("Executor Encountered run time exception, result: " + result.toString()); //getSender().tell(new Worker.WorkFailed(result), getSelf()); return new Worker.WorkFailed(result); } finally { IOUtils.closeQuietly(outFile); IOUtils.closeQuietly(errorFile); } }