List of usage examples for org.apache.commons.exec DefaultExecutor execute
public void execute(final CommandLine command, final ExecuteResultHandler handler) throws ExecuteException, IOException
From source file:org.onehippo.forge.gallerymagick.core.command.AbstractMagickCommand.java
/** * Execute the Magick command with the sub-command and arguments. * @param stdOut standard output stream//from ww w . j a v a 2 s . c o m * @throws MagickExecuteException if an execution exception occurs * @throws IOException if IO exception occurs */ public void execute(final OutputStream stdOut) throws IOException { CommandLine cmdLine = createCommandLine(); ByteArrayOutputStream errStream = null; int exitValue = 0; DefaultExecuteResultHandler resultHandler = null; try { errStream = new ByteArrayOutputStream(512); final DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler streamHandler; if (stdOut != null) { streamHandler = new PumpStreamHandler(stdOut, errStream); } else { streamHandler = new PumpStreamHandler(System.out, errStream); } executor.setStreamHandler(streamHandler); if (getWorkingDirectory() != null) { executor.setWorkingDirectory(getWorkingDirectory()); } long timeout = NumberUtils.toLong(System.getProperty(PROP_TIMEOUT), DEFAULT_COMMAND_TIMEOUT); if (timeout > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(DEFAULT_COMMAND_TIMEOUT); executor.setWatchdog(watchdog); resultHandler = new DefaultExecuteResultHandler(); executor.execute(cmdLine, resultHandler); log.debug("Executed with watchdog: {}", cmdLine); resultHandler.waitFor(); } else { exitValue = executor.execute(cmdLine); log.debug("Executed without watchdog: {}", cmdLine); } } catch (ExecuteException | InterruptedException e) { if (resultHandler != null) { exitValue = resultHandler.getExitValue(); } if (e.getCause() == null) { throw new MagickExecuteException(getExecutionErrorMessage(cmdLine, errStream, e), exitValue); } else { throw new MagickExecuteException(getExecutionErrorMessage(cmdLine, errStream, e), exitValue, e.getCause()); } } finally { IOUtils.closeQuietly(errStream); } }
From source file:org.opencron.agent.AgentProcessor.java
@Override public Response execute(final Request request) throws TException { if (!this.password.equalsIgnoreCase(request.getPassword())) { return errorPasswordResponse(request); }//ww w . java 2 s . co m String command = request.getParams().get("command") + EXITCODE_SCRIPT; String pid = request.getParams().get("pid"); //?? Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L); boolean timeoutFlag = timeout > 0; logger.info("[opencron]:execute:{},pid:{}", command, pid); File shellFile = CommandUtils.createShellFile(command, pid); Integer exitValue; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Response response = Response.response(request); final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE); final Timer timer = new Timer(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath()); final DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream); executor.setStreamHandler(stream); response.setStartTime(new Date().getTime()); //?0,shell executor.setExitValue(0); if (timeoutFlag) { //... executor.setWatchdog(watchdog); // timer.schedule(new TimerTask() { @Override public void run() { //,kill... if (watchdog.isWatching()) { /** * watchdogdestroyProcesskill... * watchdog.destroyProcess(); */ timer.cancel(); watchdog.stop(); //call kill... request.setAction(Action.KILL); try { kill(request); response.setExitCode(Opencron.StatusCode.TIME_OUT.getValue()); } catch (TException e) { e.printStackTrace(); } } } }, timeout * 60 * 1000); // resultHandler = new DefaultExecuteResultHandler() { @Override public void onProcessComplete(int exitValue) { super.onProcessComplete(exitValue); timer.cancel(); } @Override public void onProcessFailed(ExecuteException e) { super.onProcessFailed(e); timer.cancel(); } }; } executor.execute(commandLine, resultHandler); resultHandler.waitFor(); } catch (Exception e) { if (e instanceof ExecuteException) { exitValue = ((ExecuteException) e).getExitValue(); } else { exitValue = Opencron.StatusCode.ERROR_EXEC.getValue(); } if (Opencron.StatusCode.KILL.getValue().equals(exitValue)) { if (timeoutFlag) { timer.cancel(); watchdog.stop(); } logger.info("[opencron]:job has be killed!at pid :{}", request.getParams().get("pid")); } else { logger.info("[opencron]:job execute error:{}", e.getCause().getMessage()); } } finally { exitValue = resultHandler.getExitValue(); if (CommonUtils.notEmpty(outputStream.toByteArray())) { try { outputStream.flush(); String text = outputStream.toString(); if (notEmpty(text)) { try { text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), ""); response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY))); exitValue = Integer.parseInt(text .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim()); } catch (IndexOutOfBoundsException e) { response.setMessage(text); } } outputStream.close(); } catch (Exception e) { logger.error("[opencron]:error:{}", e); } } if (Opencron.StatusCode.TIME_OUT.getValue() == response.getExitCode()) { response.setSuccess(false).end(); } else { response.setExitCode(exitValue) .setSuccess(response.getExitCode() == Opencron.StatusCode.SUCCESS_EXIT.getValue()).end(); } if (shellFile != null) { shellFile.delete();// } } logger.info("[opencron]:execute result:{}", response.toString()); watchdog.stop(); return response; }
From source file:org.opennms.gizmo.k8s.portforward.KubeCtlPortForwardingStrategy.java
@Override public ForwardedPort portForward(String namespace, String pod, int remotePort) { CommandLine cmdLine = new CommandLine("kubectl"); cmdLine.addArgument("--namespace=${namespace}"); cmdLine.addArgument("port-forward"); cmdLine.addArgument("${pod}"); cmdLine.addArgument(":${remotePort}"); HashMap<String, String> map = new HashMap<>(); map.put("namespace", namespace); map.put("pod", pod); map.put("remotePort", Integer.toString(remotePort)); cmdLine.setSubstitutionMap(map);/* w w w. ja v a 2 s . c om*/ ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(out, err); DefaultExecutor executor = new DefaultExecutor(); final ExecuteWatchdog wd = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(wd); executor.setStreamHandler(psh); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { throw Throwables.propagate(e); } final int localPort = waitForLocalPort(wd, out, err); return new ForwardedPort() { @Override public InetSocketAddress getAddress() { return new InetSocketAddress(InetAddress.getLoopbackAddress(), localPort); } @Override public void close() throws IOException { wd.destroyProcess(); } @Override public String toString() { return String.format("ForwardedPort[localPort=%d]", localPort); } }; }
From source file:org.opennms.systemreport.SystemReportResourceLocator.java
@Override public String slurpOutput(final String commandString, final boolean ignoreExitCode) { final CommandLine command = CommandLine.parse(commandString); LOG.debug("running: {}", commandString); final Map<String, String> environment = new HashMap<String, String>(System.getenv()); environment.put("COLUMNS", "2000"); DataInputStream input = null; PipedInputStream pis = null;//from w w w . ja v a 2 s . c o m OutputSuckingParser parser = null; String outputText = null; final DefaultExecutor executor = new DefaultExecutor(); final PipedOutputStream output = new PipedOutputStream(); final PumpStreamHandler streamHandler = new PumpStreamHandler(output, output); executor.setWatchdog(new ExecuteWatchdog(m_maxProcessWait)); executor.setStreamHandler(streamHandler); if (ignoreExitCode) { executor.setExitValues(null); } try { LOG.trace("executing '{}'", commandString); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new OutputSuckingParser(input); parser.start(); final int exitValue = executor.execute(command, environment); IOUtils.closeQuietly(output); parser.join(m_maxProcessWait); if (!ignoreExitCode && exitValue != 0) { LOG.debug("error running '{}': exit value was {}", commandString, exitValue); } else { outputText = parser.getOutput(); } LOG.trace("finished '{}'", commandString); } catch (final Exception e) { LOG.debug("Failed to run '{}'", commandString, e); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); } return outputText; }
From source file:org.sonatype.sisu.bl.support.DefaultDropwizardBundle.java
@Override protected void startApplication() { File bundleDirectory = getBundleDirectory(); List<String> javaOptions = getConfiguration().getJavaOptions(); List<String> javaAgentOptions = getJavaAgentOptions(); CommandLine cmdLine = new CommandLine(new File(System.getProperty("java.home"), "/bin/java")); if (javaAgentOptions.size() > 0) { cmdLine.addArguments(javaAgentOptions.toArray(new String[javaAgentOptions.size()])); }/*from w w w. ja v a 2s.c o m*/ if (javaOptions.size() > 0) { cmdLine.addArguments(javaOptions.toArray(new String[javaOptions.size()])); } cmdLine.addArgument("-jar").addArgument(getJarName()).addArguments(getConfiguration().arguments()) .addArgument("config.yaml"); log.debug("Launching: {}", cmdLine.toString()); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(bundleDirectory); executor.setWatchdog(watchdog = new ExecuteWatchdog(Time.minutes(5).toMillis())); try { executor.setStreamHandler(streamHandler = new PumpStreamHandler( new FileOutputStream(new File(bundleDirectory, "output.log")))); executor.execute(cmdLine, new DefaultExecuteResultHandler()); } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:org.spiffyui.maven.plugins.GwtCompileMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { Properties p = project.getProperties(); if (skip || "pom".equals(project.getPackaging())) { getLog().debug("GWT compilation is skipped"); return;/*from w w w. j a v a 2 s . c om*/ } if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } else if (!force) { String name = gwtModuleName; if (name.endsWith(InitializeMojo.SPIFFY_TMP_SUFFIX)) { name = name.substring(0, name.length() - InitializeMojo.SPIFFY_TMP_SUFFIX.length()); } if (Math.max(getNewestModifiedTime(resources, -1), getNewestModifiedTime(new File(compileSourceRoots.get(0)), -1)) < getOldestModifiedTime( new File(outputDirectory, name), -1)) { /* Then the GWT build is up to date and we can skip it */ getLog().info("GWT files are up to date. Skipping GWT build."); return; } } CommandLine cmd = new CommandLine("java"); ClassBuilder cb = new ClassBuilder(project); cb.add(p.getProperty("spiffyui.generated-source")); cb.add(resources.getAbsolutePath()); for (String sourceRoot : compileSourceRoots) { cb.add(sourceRoot); } cmd.addArgument("-cp").addArgument(cb.toString()).addArgument(extraJvmArgs) .addArgument("com.google.gwt.dev.Compiler").addArgument("-gen").addArgument(gen.getAbsolutePath()) .addArgument("-logLevel").addArgument(logLevel).addArgument("-style").addArgument(style) .addArgument("-war").addArgument(outputDirectory.getAbsolutePath()).addArgument("-localWorkers") .addArgument(String.valueOf(getLocalWorkers())); // optional advanced arguments if (enableAssertions) { cmd.addArgument("-ea"); } if (draftCompile) { cmd.addArgument("-draftCompile"); } if (validateOnly) { cmd.addArgument("-validateOnly"); } if (treeLogger) { cmd.addArgument("-treeLogger"); } if (disableClassMetadata) { cmd.addArgument("-XdisableClassMetadata"); } if (disableCastChecking) { cmd.addArgument("-XdisableCastChecking"); } if (strict) { cmd.addArgument("-strict"); } if (soycDetailed) { cmd.addArgument("-XsoycDetailed"); } if (optimizationLevel >= 0) { cmd.addArgument("-optimize").addArgument(Integer.toString(optimizationLevel)); } if (extraParam || compileReport) { getLog().debug("create extra directory "); if (!extra.exists()) { extra.mkdirs(); } cmd.addArgument("-extra").addArgument(extra.getAbsolutePath()); } else { getLog().debug("NOT create extra directory "); } if (compileReport) { cmd.addArgument("-compileReport"); } if (workDir != null) { cmd.addArgument("-workDir").addArgument(String.valueOf(workDir)); } cmd.addArgument(gwtModuleName); try { DefaultExecutor executor = new DefaultExecutor(); getLog().debug("Exec: " + cmd.toString()); int ret = executor.execute(cmd, CommandLineUtils.getSystemEnvVars()); if (ret != 0) { throw new MojoExecutionException("Exec failed: " + Integer.toString(ret)); } } catch (IOException e) { throw new MojoExecutionException(e.getMessage()); } moveJSDir(); }
From source file:org.wisdom.maven.node.NPM.java
/** * Executes the current NPM.//from w w w . j a v a2s .com * NPM can have several executable attached to them, so the 'binary' argument specifies which * one has to be executed. Check the 'bin' entry of the package.json file to determine which * one you need. 'Binary' is the key associated with the executable to invoke. For example, in * <code> * <pre> * "bin": { * "coffee": "./bin/coffee", * "cake": "./bin/cake" * }, * </pre> * </code> * <p/> * we have two alternatives: 'coffee' and 'cake'. * * @param binary the key of the binary to invoke * @param args the arguments * @return the execution exit status * @throws MojoExecutionException if the execution failed */ public int execute(String binary, String... args) throws MojoExecutionException { File destination = getNPMDirectory(); if (!destination.isDirectory()) { throw new IllegalStateException("The npm module " + this.npmName + " is not installed"); } CommandLine cmdLine = new CommandLine(node.getNodeExecutable()); File npmExec = null; try { npmExec = findExecutable(binary); } catch (IOException | ParseException e) { //NOSONAR log.error(e); } if (npmExec == null) { throw new IllegalStateException( "Cannot execute NPM " + this.npmName + " - cannot find the JavaScript file " + "matching " + binary + " in the " + PACKAGE_JSON + " file"); } // NPM is launched using the main file. cmdLine.addArgument(npmExec.getAbsolutePath(), false); for (String arg : args) { cmdLine.addArgument(arg, this.handleQuoting); } DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); errorStreamFromLastExecution = new LoggedOutputStream(log, true, true); outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamFromLastExecution, errorStreamFromLastExecution); executor.setStreamHandler(streamHandler); executor.setWorkingDirectory(node.getWorkDir()); log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath()); try { return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node)); } catch (IOException e) { throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e); } }
From source file:org.wisdom.maven.node.NPM.java
/** * Executes the current NPM using the given binary file. * * @param binary the program to run/*w w w. j a v a 2 s. com*/ * @param args the arguments * @return the execution exit status * @throws MojoExecutionException if the execution failed */ public int execute(File binary, String... args) throws MojoExecutionException { File destination = getNPMDirectory(); if (!destination.isDirectory()) { throw new IllegalStateException("NPM " + this.npmName + " not installed"); } CommandLine cmdLine = new CommandLine(node.getNodeExecutable()); if (binary == null) { throw new IllegalStateException( "Cannot execute NPM " + this.npmName + " - the given binary is 'null'."); } if (!binary.isFile()) { throw new IllegalStateException("Cannot execute NPM " + this.npmName + " - the given binary does not " + "exist: " + binary.getAbsoluteFile() + "."); } // NPM is launched using the main file. cmdLine.addArgument(binary.getAbsolutePath(), false); for (String arg : args) { cmdLine.addArgument(arg, this.handleQuoting); } DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); errorStreamFromLastExecution = new LoggedOutputStream(log, true, true); outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamFromLastExecution, errorStreamFromLastExecution); executor.setStreamHandler(streamHandler); executor.setWorkingDirectory(node.getWorkDir()); log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath()); try { return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node)); } catch (IOException e) { throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e); } }
From source file:org.wso2.ppaas.configurator.tests.ConfiguratorTestManager.java
/** * Execute shell command//from w w w . j a va2s . co m * * @param commandText */ protected int executeCommand(final String commandText, Map<String, String> environment) { final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal(); int result; try { CommandLine commandline = CommandLine.parse(commandText); DefaultExecutor exec = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setWorkingDirectory(new File(ConfiguratorTestManager.class.getResource(PATH_SEP).getPath() + ".." + PATH_SEP + CONFIGURATOR_DIR_NAME)); exec.setStreamHandler(streamHandler); ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); exec.setWatchdog(watchdog); result = exec.execute(commandline, environment); } catch (Exception e) { log.error(outputStream.toString(), e); throw new RuntimeException(e); } return result; }
From source file:uk.org.sappho.applications.transcript.service.registry.vcs.CommandExecuter.java
public String execute(Command command, File directory) throws TranscriptException { try {// w w w . j ava2 s . c om if (logger.isLoggable(Level.INFO)) { logger.info(command.getSafeCommand()); } DefaultExecutor executor = new DefaultExecutor(); DefaultExecuteResultHandler commandResultsHandler = new DefaultExecuteResultHandler(); ByteArrayOutputStream commandOutputStream = new ByteArrayOutputStream(); ByteArrayOutputStream commandErrorStream = new ByteArrayOutputStream(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(commandOutputStream, commandErrorStream); executor.setWatchdog(new ExecuteWatchdog(60000)); executor.setStreamHandler(pumpStreamHandler); executor.setWorkingDirectory(directory); executor.execute(command.getCommandLine(), commandResultsHandler); commandResultsHandler.waitFor(); if (commandResultsHandler.getExitValue() != 0) { throw new TranscriptException(commandErrorStream.toString()); } return commandOutputStream.toString(); } catch (Throwable throwable) { if (logger.isLoggable(Level.WARNING)) { logger.warning(throwable.getMessage()); } throw new TranscriptException("Unable to execute system command: " + command.getSafeCommand(), throwable); } }