Search in sources :

Example 56 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project my_curd by qinyou.

the class ToolNet method ping.

/**
 * ping ip并返回结果
 *
 * @param ip
 * @return 描述apache-common-exec 示例
 */
public static String ping(String ip) {
    String encode = "GBK";
    String os = System.getProperties().getProperty("os.name");
    if (os.toLowerCase().indexOf("windows") == -1) {
        encode = "UTF-8";
    }
    try {
        String command = "ping " + ip;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
        CommandLine commandline = CommandLine.parse(command);
        DefaultExecutor exec = new DefaultExecutor();
        exec.setExitValues(null);
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
        exec.setStreamHandler(streamHandler);
        exec.execute(commandline);
        String out = outputStream.toString(encode);
        String error = errorStream.toString(encode);
        return out + error;
    } catch (Exception e) {
        LOG.error("ping task failed.", e);
        return e.toString();
    }
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 57 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project elasticsearch-maven-plugin by alexcojocaru.

the class ProcessUtil method executeScript.

/**
 * Run the given command as a process within the supplied instance config context
 * and wait until it finalizes. An ElasticsearchSetupException is thrown if the exit code
 * is not 0.
 * @param config - the instance config
 * @param command - the command to execute
 * @param environment - a map of environment variables; can be null
 * @param processDestroyer - a destroyer handler for the spawned process; can be null
 * @param disableLogging - whether to disable the logging of the command or not
 * @return the output (not trimmed of whitespaces) of the given command, as separate lines
 */
public static List<String> executeScript(InstanceConfiguration config, CommandLine command, Map<String, String> environment, ProcessDestroyer processDestroyer, boolean disableLogging) {
    Log log = config.getClusterConfiguration().getLog();
    int instanceId = config.getId();
    File baseDir = new File(config.getBaseDir());
    Map<String, String> completeEnvironment = createEnvironment(environment);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(baseDir);
    // allows null
    executor.setProcessDestroyer(processDestroyer);
    // set up a tap on the output stream, to collect to output and return it from this method
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(disableLogging ? outputStream : new TeeOutputStream(System.out, outputStream), disableLogging ? errorStream : new TeeOutputStream(System.err, errorStream)));
    try {
        log.debug(String.format("Using environment: %s", completeEnvironment));
        String commandMessage = String.format("Elasticsearch[%d]: Executing command '%s' in directory '%s'", instanceId, command.toString(), baseDir);
        if (disableLogging) {
            log.debug(commandMessage);
        } else {
            log.info(commandMessage);
        }
        int exitCode = executor.execute(command, completeEnvironment);
        if (exitCode != 0) {
            throw new ElasticsearchSetupException(String.format("Elasticsearch [%d]: Command '%s' in directory '%s' finished with exit code %d; see above for details", instanceId, command, baseDir, exitCode));
        }
        String resultMessage = String.format("Elasticsearch[%d]: The process finished with exit code %d", instanceId, exitCode);
        if (disableLogging) {
            log.debug(resultMessage);
        } else {
            log.info(resultMessage);
        }
    } catch (IOException e) {
        List<String> output = readBuffer(outputStream);
        List<String> error = readBuffer(errorStream);
        String lineSeparator = System.getProperty("line.separator");
        StringBuilder message = new StringBuilder();
        message.append("Elasticsearch [");
        message.append(instanceId);
        message.append("]: Cannot execute command '");
        message.append(command);
        message.append("' in directory '");
        message.append(baseDir);
        message.append("'");
        message.append(lineSeparator);
        message.append("Output:");
        message.append(lineSeparator);
        message.append(StringUtils.join(output, lineSeparator));
        message.append(lineSeparator);
        message.append("Error:");
        message.append(lineSeparator);
        message.append(StringUtils.join(error, lineSeparator));
        throw new ElasticsearchSetupException(message.toString(), e);
    }
    return readBuffer(outputStream);
}
Also used : TeeOutputStream(org.apache.commons.io.output.TeeOutputStream) Log(org.apache.maven.plugin.logging.Log) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ElasticsearchSetupException(com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File)

Example 58 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project weblogic-kubernetes-operator by oracle.

the class TestUtils method checkKubernetes.

private static Boolean checkKubernetes() {
    PrintStream savedOut = System.out;
    System.setOut(new PrintStream(new ByteArrayOutputStream()));
    try {
        CommandLine cmdLine = CommandLine.parse("kubectl cluster-info");
        DefaultExecutor executor = new DefaultExecutor();
        executor.execute(cmdLine);
        return true;
    } catch (IOException e) {
        return false;
    } finally {
        System.setOut(savedOut);
    }
}
Also used : PrintStream(java.io.PrintStream) CommandLine(org.apache.commons.exec.CommandLine) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 59 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project assembly64fx by freabemania.

the class Autoupgrade method doUpgrade.

public void doUpgrade() {
    PlatformInfoService platformService = PlatformInfoService.getInstance();
    String upgradeFile = platformService.getPlatformDBSetting("dist");
    String script = platformService.getPlatformDBSetting("script");
    try {
        CancelableTask cancelTask = CancelableTask.of();
        ProgressDBController controller = GuiUtils.showDialogOwnerNoWait("progressBarDbUpdate.fxml", "Progress", true, NullWindowOwner.of(), new Object[] { 4, cancelTask, "", "Will not really happen" });
        controller.hideAllButtons();
        ReturningTask<Void> upgradeTask = () -> {
            GlobalRepoService.getInstance().put("upgrading", "true");
            controller.increaseProgress();
            controller.setProgressLabel("Downloading new files " + upgradeFile);
            File downloaded = FTPService.getInstance().getFile("/artifacts", upgradeFile, new File(PathService.getInstance().getTmpFolderAsString() + upgradeFile), false);
            controller.increaseProgress();
            File currfolder = new File("..");
            LOGGER.info("Unpack");
            controller.setProgressLabel("Unpacking");
            unzipService.extractZip(downloaded, new File(currfolder.getAbsolutePath() + "/tmp"));
            controller.increaseProgress();
            try {
                FileUtils.copyFile(new File(currfolder.getAbsolutePath() + "/tmp/assembly64/update/update.bat"), new File(currfolder.getAbsolutePath() + "/update/update.bat"));
            } catch (Exception e) {
            }
            LOGGER.info("Done! Restarting, please wait");
            controller.increaseProgress();
            controller.setProgressLabel("Restarting");
            Thread.sleep(2000);
            ReturningTask<Void> installTask = () -> {
                String cmd = "\"" + currfolder.getAbsolutePath() + "/update/" + script + "\" \"" + currfolder.getAbsolutePath() + "/tmp/assembly64\" \"" + currfolder.getAbsolutePath() + "\" \"" + currfolder.getAbsolutePath() + "/assembly64.exe\"";
                cmd = cmd.replace("/", "\\");
                LOGGER.info("Launching external script " + cmd);
                CommandLine commandLine = CommandLine.parse(cmd);
                DefaultExecutor executor = new DefaultExecutor();
                executor.setExitValue(0);
                executor.execute(commandLine);
                return null;
            };
            ExecutorUtil.executeAsyncWithRetry(installTask);
            Thread.sleep(2000);
            System.exit(0);
            return null;
        };
        ExecutorUtil.executeAsyncWithRetry(upgradeTask);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : ProgressDBController(se.light.assembly64.fx.ProgressDBController) CommandLine(org.apache.commons.exec.CommandLine) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ReturningTask(se.light.assembly64.model.ReturningTask) File(java.io.File) PlatformInfoService(se.light.assembly64.service.PlatformInfoService) CancelableTask(se.light.assembly64.model.CancelableTask)

Example 60 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project alliance by codice.

the class MpegTsUdpClient method executeFFmpeg.

private static DefaultExecuteResultHandler executeFFmpeg(final CommandLine command, final int timeoutSeconds, final PumpStreamHandler streamHandler) throws IOException {
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutSeconds * 1000);
    final Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(command, resultHandler);
    return resultHandler;
}
Also used : Executor(org.apache.commons.exec.Executor) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) DefaultExecuteResultHandler(org.apache.commons.exec.DefaultExecuteResultHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog)

Aggregations

DefaultExecutor (org.apache.commons.exec.DefaultExecutor)81 CommandLine (org.apache.commons.exec.CommandLine)62 PumpStreamHandler (org.apache.commons.exec.PumpStreamHandler)47 IOException (java.io.IOException)36 ExecuteWatchdog (org.apache.commons.exec.ExecuteWatchdog)33 ExecuteException (org.apache.commons.exec.ExecuteException)27 ByteArrayOutputStream (java.io.ByteArrayOutputStream)26 File (java.io.File)24 Executor (org.apache.commons.exec.Executor)11 DefaultExecuteResultHandler (org.apache.commons.exec.DefaultExecuteResultHandler)9 ShutdownHookProcessDestroyer (org.apache.commons.exec.ShutdownHookProcessDestroyer)9 HashMap (java.util.HashMap)5 Test (org.junit.Test)5 URL (java.net.URL)4 Properties (java.util.Properties)4 LogOutputStream (org.apache.commons.exec.LogOutputStream)4 InputStream (java.io.InputStream)3 PipedInputStream (java.io.PipedInputStream)3 PipedOutputStream (java.io.PipedOutputStream)3 HashSet (java.util.HashSet)3