List of usage examples for org.apache.commons.exec DefaultExecutor setProcessDestroyer
public void setProcessDestroyer(final ProcessDestroyer processDestroyer)
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 w w w.j a v a2s. c om 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.sonar.it.jenkins.orchestrator.container.JenkinsWrapper.java
@VisibleForTesting DefaultExecutor createExecutor(ExecuteWatchdog watchDog) { DefaultExecutor newExecutor = new DefaultExecutor(); newExecutor.setWatchdog(watchDog);//ww w. ja va2 s . c om newExecutor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); return newExecutor; }
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"; }/*from w w w .j av a 2 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:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java
/** * This calls a TIBCO binary.//from w ww . j a v a 2s . 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:org.apache.camel.component.exec.impl.DefaultExecCommandExecutor.java
protected DefaultExecutor prepareDefaultExecutor(ExecCommand execCommand) { DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(null);//from ww w . j ava2s .c om if (execCommand.getWorkingDir() != null) { executor.setWorkingDirectory(new File(execCommand.getWorkingDir()).getAbsoluteFile()); } if (execCommand.getTimeout() != ExecEndpoint.NO_TIMEOUT) { executor.setWatchdog(new ExecuteWatchdog(execCommand.getTimeout())); } executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); return executor; }
From source file:org.eclipse.sisu.equinox.launching.internal.DefaultEquinoxLauncher.java
@Override public int execute(LaunchConfiguration configuration, int forkedProcessTimeoutInSeconds) throws EquinoxLaunchingException { String executable = configuration.getJvmExecutable(); if (executable == null || "".equals(executable)) { // use the same JVM as the one used to run Maven (the "java.home" one) executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; if (File.separatorChar == '\\') { executable = executable + ".exe"; }//ww w . j a v a 2s . co m } CommandLine cli = new CommandLine(executable); final boolean handleQuotes = false; cli.addArguments(configuration.getVMArguments(), handleQuotes); cli.addArguments(new String[] { "-jar", getCanonicalPath(configuration.getLauncherJar()) }, handleQuotes); cli.addArguments(configuration.getProgramArguments(), handleQuotes); log.info("Command line:\n\t" + cli.toString()); 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(configuration.getWorkingDirectory()); try { return executor.execute(cli, getMergedEnvironment(configuration)); } catch (ExecuteException e) { if (watchdog != null && watchdog.killedProcess()) { log.error("Timeout " + forkedProcessTimeoutInSeconds + " s exceeded. Process was killed."); } return e.getExitValue(); } catch (IOException e) { throw new EquinoxLaunchingException(e); } }
From source file:org.jberet.support.io.OsCommandBatchlet.java
/** * {@inheritDoc}//from ww w .j av a 2 s . co m * <p> * This method runs the OS command. * If the command completes successfully, its process exit code is returned. * If there is exception while running the OS command, which may be * caused by timeout, the command being stopped, or other errors, the process * exit code is set as the step exit status, and the exception is thrown. * * @return the OS command process exit code * * @throws Exception upon errors */ @Override public String process() throws Exception { final DefaultExecutor executor = new DefaultExecutor(); final CommandLine commandLineObj; if (commandLine != null) { commandLineObj = CommandLine.parse(commandLine); } else { if (commandArray == null) { throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, null, "commandArray"); } else if (commandArray.isEmpty()) { throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, commandArray.toString(), "commandArray"); } commandLineObj = new CommandLine(commandArray.get(0)); final int len = commandArray.size(); if (len > 1) { for (int i = 1; i < len; i++) { commandLineObj.addArgument(commandArray.get(i)); } } } if (workingDir != null) { executor.setWorkingDirectory(workingDir); } if (streamHandler != null) { executor.setStreamHandler((ExecuteStreamHandler) streamHandler.newInstance()); } SupportLogger.LOGGER.runCommand(commandLineObj.getExecutable(), Arrays.toString(commandLineObj.getArguments()), executor.getWorkingDirectory().getAbsolutePath()); if (commandOkExitValues != null) { executor.setExitValues(commandOkExitValues); } watchdog = new ExecuteWatchdog( timeoutSeconds > 0 ? timeoutSeconds * 1000 : ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); executor.execute(commandLineObj, environment, resultHandler); resultHandler.waitFor(); final ExecuteException exception = resultHandler.getException(); if (exception != null) { stepContext.setExitStatus(String.valueOf(resultHandler.getExitValue())); if (!isStopped) { throw exception; } else { SupportLogger.LOGGER.warn("", exception); } } return String.valueOf(resultHandler.getExitValue()); }
From source file:org.stem.ExternalNode.java
private DefaultExecuteResultHandler startStemProcess(CommandLine commandLine, Map env) throws MojoExecutionException { try {/*from ww w. java 2s .co m*/ DefaultExecutor exec = new DefaultExecutor(); DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler(); exec.setWorkingDirectory(nodeDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(log); LogOutputStream stderr = new MavenLogOutputStream(log); log.debug("Executing command line: " + commandLine); PumpStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr); streamHandler.start(); exec.setStreamHandler(streamHandler); exec.execute(commandLine, env, execHandler); // try // { // execHandler.waitFor(); // } // catch (InterruptedException e) // { // e.printStackTrace(); // } return execHandler; } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } }
From source file:org.wisdom.maven.utils.WisdomExecutor.java
/** * Launches the Wisdom server. This method blocks until the wisdom server shuts down. * It uses the {@literal Java} executable directly. * * @param mojo the mojo/*from w w w. j a v a2s. co m*/ * @param interactive enables the shell prompt * @param debug the debug port (0 to disable it) * @param jvmArgs JVM arguments to add to the `java` command (before the -jar argument). * @param destroyer a process destroyer that can be used to destroy the process, if {@code null} * a {@link org.apache.commons.exec.ShutdownHookProcessDestroyer} is used. * @throws MojoExecutionException if the Wisdom instance cannot be started or has thrown an unexpected status * while being stopped. */ public void execute(AbstractWisdomMojo mojo, boolean interactive, int debug, String jvmArgs, ProcessDestroyer destroyer) throws MojoExecutionException { // Get java File java = ExecUtils.find("java", new File(mojo.javaHome, "bin")); if (java == null) { throw new MojoExecutionException("Cannot find the java executable"); } CommandLine cmdLine = new CommandLine(java); if (debug != 0) { cmdLine.addArgument("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=" + debug, false); } if (!Strings.isNullOrEmpty(jvmArgs)) { cmdLine.addArguments(jvmArgs, false); } cmdLine.addArgument("-jar"); cmdLine.addArgument("bin/chameleon-core-" + CHAMELEON_VERSION + ".jar"); if (interactive) { cmdLine.addArgument("--interactive"); } appendSystemPropertiesToCommandLine(mojo, cmdLine); DefaultExecutor executor = new DefaultExecutor(); if (destroyer != null) { executor.setProcessDestroyer(destroyer); } else { executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); } executor.setWorkingDirectory(mojo.getWisdomRootDirectory()); if (interactive) { executor.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in)); //NOSONAR // Using the interactive mode the framework should be stopped using the 'exit' command, // and produce a '0' status. executor.setExitValue(0); } else { executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); // NOSONAR // As the execution is intended to be interrupted using CTRL+C, the status code returned is expected to be 1 // 137 or 143 is used when stopped by the destroyer. executor.setExitValues(new int[] { 1, 137, 143 }); } try { mojo.getLog().info("Launching Wisdom Server"); mojo.getLog().debug("Command Line: " + cmdLine.toString()); // The message is different whether or not we are in the interactive mode. if (interactive) { mojo.getLog().info("You are in interactive mode"); mojo.getLog().info("Hit 'exit' to shutdown"); } else { mojo.getLog().info("Hit CTRL+C to exit"); } if (debug != 0) { mojo.getLog().info("Wisdom launched with remote debugger interface enabled on port " + debug); } // Block execution until ctrl+c executor.execute(cmdLine); } catch (IOException e) { throw new MojoExecutionException("Cannot execute Wisdom", e); } }
From source file:org.zanata.client.commands.ConfigurableCommand.java
/** * @throws Exception/* w w w .ja v a 2 s . c om*/ * if any of the commands fail. */ private void runSystemCommands(List<String> commands) throws Exception { for (String command : commands) { log.info("[Running command]$ " + command); try { DefaultExecutor executor = new DefaultExecutor(); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); CommandLine cmdLine = CommandLine.parse(command); int exitValue = executor.execute(cmdLine); if (exitValue != 0) { throw new Exception("Command returned non-zero exit value: " + exitValue); } log.info(" Completed with exit value: " + exitValue); } catch (java.io.IOException e) { throw new Exception("Failed to run command. " + e.getMessage(), e); } catch (InterruptedException e) { throw new Exception("Interrupted while running command. " + e.getMessage(), e); } } }