Example usage for org.apache.commons.exec PumpStreamHandler PumpStreamHandler

List of usage examples for org.apache.commons.exec PumpStreamHandler PumpStreamHandler

Introduction

In this page you can find the example usage for org.apache.commons.exec PumpStreamHandler PumpStreamHandler.

Prototype

public PumpStreamHandler(final OutputStream out, final OutputStream err, final InputStream input) 

Source Link

Document

Construct a new PumpStreamHandler.

Usage

From source file:com.kotcrab.vis.editor.Main.java

public static void main(String[] args) throws Exception {
    App.init();/*from  ww w .j a  v  a2  s .c o m*/
    if (OsUtils.isMac())
        System.setProperty("java.awt.headless", "true");

    LaunchConfiguration launchConfig = new LaunchConfiguration();

    //TODO: needs some better parser
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.equals("--scale-ui")) {
            launchConfig.scaleUIEnabled = true;
            continue;
        }

        if (arg.equals("--project")) {
            if (i + 1 >= args.length) {
                throw new IllegalStateException("Not enough parameters for --project <project path>");
            }

            launchConfig.projectPath = args[i + 1];
            i++;
            continue;
        }

        if (arg.equals("--scene")) {
            if (i + 1 >= args.length) {
                throw new IllegalStateException("Not enough parameters for --scene <scene path>");
            }

            launchConfig.scenePath = args[i + 1];
            i++;
            continue;
        }

        Log.warn("Unrecognized command line argument: " + arg);
    }

    launchConfig.verify();

    editor = new Editor(launchConfig);

    Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration();
    config.setWindowedMode(1280, 720);
    config.setWindowSizeLimits(1, 1, 9999, 9999);
    config.useVsync(true);
    config.setIdleFPS(2);
    config.setWindowListener(new Lwjgl3WindowAdapter() {
        @Override
        public boolean closeRequested() {
            editor.requestExit();
            return false;
        }
    });

    try {
        new Lwjgl3Application(editor, config);
        Log.dispose();
    } catch (Exception e) {
        Log.exception(e);
        Log.fatal("Uncaught exception occurred, error report will be saved");
        Log.flush();

        if (App.eventBus != null)
            App.eventBus.post(new ExceptionEvent(e, true));

        try {
            File crashReport = new CrashReporter(Log.getLogFile().file()).processReport();
            if (new File(App.TOOL_CRASH_REPORTER_PATH).exists() == false) {
                Log.warn("Crash reporting tool not present, skipping crash report sending.");
            } else {
                CommandLine cmdLine = new CommandLine(PlatformUtils.getJavaBinPath());
                cmdLine.addArgument("-jar");
                cmdLine.addArgument(App.TOOL_CRASH_REPORTER_PATH);
                cmdLine.addArgument(ApplicationUtils.getRestartCommand().replace("\"", "%"));
                cmdLine.addArgument(crashReport.getAbsolutePath(), false);
                DefaultExecutor executor = new DefaultExecutor();
                executor.setStreamHandler(new PumpStreamHandler(null, null, null));
                executor.execute(cmdLine);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        Log.dispose();
        System.exit(-3);
    } catch (ExceptionInInitializerError err) {
        if (OsUtils.isMac() && err.getCause() instanceof IllegalStateException) {
            if (ExceptionUtils.getStackTrace(err).contains("XstartOnFirstThread")) {
                System.out.println(
                        "Application was not launched on first thread. Restarting with -XstartOnFirstThread, add VM argument -XstartOnFirstThread to avoid this.");
                ApplicationUtils.startNewInstance();
            }
        }

        throw err;
    }
}

From source file:com.tibco.tgdb.test.utils.ProcessCheck.java

/**
 * Check whether a process is running or not
 * @param pid pid of the process to monitor
 * @return true if process is running/*from   www  . j a  va  2  s .  c o  m*/
 * @throws IOException IO exception
 */
public static boolean isProcessRunning(int pid) throws IOException {
    String line;
    if (OS.isFamilyWindows()) {
        //tasklist exit code is always 0. Parse output
        //findstr exit code 0 if found pid, 1 if it doesn't
        line = "cmd /c \"tasklist /FI \"PID eq " + pid + "\" | findstr " + pid + "\"";
    } else {
        //ps exit code 0 if process exists, 1 if it doesn't
        line = "ps -p " + pid;
    }
    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(null, null, null));
    executor.setExitValues(new int[] { 0, 1 });
    int exitValue = executor.execute(cmdLine);
    if (exitValue == 0)
        return true;
    else if (exitValue == 1)
        return false;
    else // should never get to here in theory since execute would throw exception
        return true;
}

From source file:com.impetus.ankush.common.utils.CommandExecutor.java

/**
 * Exec./*  ww  w .  ja  va  2 s. com*/
 *
 * @param command the command
 * @param out the out
 * @param err the err
 * @return the int
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws InterruptedException the interrupted exception
 */
public static int exec(String command, OutputStream out, OutputStream err)
        throws IOException, InterruptedException {
    CommandLine cmdLine = CommandLine.parse(command);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(out, err, null));
    return executor.execute(cmdLine);
}

From source file:com.jivesoftware.os.jive.utils.shell.utils.Invoke.java

public static int invoke(File home, String[] command, final InputStream writeToProcess,
        final ConcurrentLinkedQueue<String> response) throws Exception {
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);//from   ww  w  .  j  a v a 2  s.  co m
    if (home != null) {
        executor.setWorkingDirectory(home);
    }

    //give all the processes 120s to return that they started successfully
    ExecuteWatchdog watchdog = new ExecuteWatchdog(120000);
    executor.setWatchdog(watchdog);

    LogOutputStream outputStream = new LogOutputStream(20000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    LogOutputStream errorStream = new LogOutputStream(40000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, errorStream, writeToProcess);
    executor.setStreamHandler(pumpStreamHandler);
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine commandLine = new CommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i]);
    }
    try {
        //executor.execute(commandLine, handler);
        return executor.execute(commandLine);
        //handler.waitFor(20000);
    } catch (Exception x) {
        x.printStackTrace();
        return 1;
    }
}

From source file:com.codeshare.codeexecutor.executor.MyPumpStreamHandler.java

/**
 * The constructor for <code>MyPumpStreamHandler</code> having following
 * parameters/*from w  w w .ja  v  a  2s . c o  m*/
 */
public MyPumpStreamHandler(final String stdin, final ExecuteWatchdog watchdog,
        final int outputStreamMaxCharSize) {

    out = new MyOutputStream(outputStreamMaxCharSize, watchdog, this);

    final byte[] stdinBytes;

    if (stdin != null) {
        stdinBytes = stdin.getBytes();
    } else {
        stdinBytes = "".getBytes();
    }
    pumpStreamHandler = new PumpStreamHandler(out, out, new ByteArrayInputStream(stdinBytes));
}

From source file:com.kotcrab.vis.editor.util.ApplicationUtils.java

public static void startNewInstance() {
    try {// ww  w. j a  va2 s .  c o  m
        CommandLine cmdLine = CommandLine.parse(getRestartCommand());
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(null, null, null));
        executor.execute(cmdLine, new DefaultExecuteResultHandler());
    } catch (Exception e) {
        Log.exception(e);
    }
}

From source file:com.codeabovelab.dm.common.utils.ProcessUtils.java

public static int executeCommand(String command, ExecuteWatchdog watchdog, OutputStream outputStream,
        OutputStream errorStream, InputStream inputStream, Map<String, String> env) {
    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    if (outputStream == null) {
        outputStream = new LogOutputStream() {
            @Override//  w  w w. j a v  a  2  s  .  c o m
            protected void processLine(String s, int i) {
                log.error(s);
            }
        };
    }
    if (errorStream == null) {
        errorStream = new LogOutputStream() {
            @Override
            protected void processLine(String s, int i) {
                log.error(s);
            }
        };
    }
    executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream, inputStream));
    executor.setExitValues(new int[] { 0, 1 });
    if (watchdog != null) {
        executor.setWatchdog(watchdog);
    }
    int exitValue;
    try {
        exitValue = executor.execute(cmdLine, env);
    } catch (IOException e) {
        exitValue = 1;
        LOGGER.error("error executing command", e);
    }
    return exitValue;
}

From source file:name.martingeisse.webide.nodejs.AbstractNodejsServer.java

/**
 * Starts this server.//from  ww w.  ja v  a 2 s  . co m
 */
public void start() {

    // determine the path of the associated script
    URL url = getScriptUrl();
    if (!url.getProtocol().equals("file")) {
        throw new RuntimeException("unsupported protocol for associated script URL: " + url);
    }
    File scriptFile = new File(url.getPath());

    // build the command line
    CommandLine commandLine = new CommandLine(Configuration.getBashPath());
    commandLine.addArgument("--login");
    commandLine.addArgument("-c");
    commandLine.addArgument("node " + scriptFile.getName(), false);

    // build I/O streams
    ByteArrayInputStream inputStream = null;
    OutputStream outputStream = System.err;
    OutputStream errorStream = System.err;
    ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream, inputStream);

    // build an environment map that contains the path to the node_modules
    Map<String, String> environment = new HashMap<String, String>();
    environment.put("NODE_PATH", new File("lib/node_modules").getAbsolutePath());

    // run Node.js
    Executor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setStreamHandler(streamHandler);
    try {
        executor.setWorkingDirectory(scriptFile.getParentFile());
        executor.execute(commandLine, environment, new ExecuteResultHandler() {

            @Override
            public void onProcessFailed(ExecuteException e) {
            }

            @Override
            public void onProcessComplete(int exitValue) {
            }

        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:name.martingeisse.webide.process.NodejsCompanionProcess.java

@Override
protected void configureExecutor(Executor executor) {
    super.configureExecutor(executor);
    ByteArrayInputStream inputStream = null;
    OutputStream outputStream = System.err;
    OutputStream errorStream = System.err;
    executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream, inputStream));
    executor.setWorkingDirectory(mainFile.getParentFile());
}

From source file:com.k42b3.aletheia.filter.request.Process.java

public void exec(Request request) {
    String cmd = getConfig().getProperty("cmd");

    try {//from  www  . ja v a2s. com
        logger.info("Execute: " + cmd);

        CommandLine commandLine = CommandLine.parse(cmd);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        DefaultExecutor executor = new DefaultExecutor();

        this.baos = new ByteArrayOutputStream();
        this.baosErr = new ByteArrayOutputStream();
        this.bais = new ByteArrayInputStream(request.getContent().getBytes());

        executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr, this.bais));
        executor.setWatchdog(watchdog);
        executor.execute(commandLine);

        logger.info("Output: " + this.baos.toString());

        request.setContent(this.baos.toString());
    } catch (Exception e) {
        logger.warning(e.getMessage());
    }
}