Example usage for java.lang ProcessBuilder inheritIO

List of usage examples for java.lang ProcessBuilder inheritIO

Introduction

In this page you can find the example usage for java.lang ProcessBuilder inheritIO.

Prototype

public ProcessBuilder inheritIO() 

Source Link

Document

Sets the source and destination for subprocess standard I/O to be the same as those of the current Java process.

Usage

From source file:Main.java

public static void main(String[] args) {

    // create a new list of arguments for our process
    String[] list = { "notepad.exe", "test.txt" };

    // create the process builder
    ProcessBuilder pb = new ProcessBuilder(list);
    try {/*from   w  w  w  .j a v  a  2 s.c  o  m*/
        // start the subprocess
        System.out.println("Starting the process..");
        pb = pb.inheritIO();
        pb.start();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.apache.nutch.util.TestProcessUtil.java

public static void main(String[] args) throws Exception {
    int res = 0;/*w  ww  . java 2  s  .  c  o  m*/

    JSONArray data = new JSONArray(Arrays.asList(args));

    System.out.println("It's crowdsourcing mode, forward the command to NutchServer...");

    ProcessBuilder builder = new ProcessBuilder("curl", "-v", "-H", "'Content-Type: application/json'", "-X",
            "PUT", "--data", data.toString(), "http://127.0.0.1:8182/exec/fetch");
    System.out.println("Execute command : " + StringUtils.join(builder.command(), " "));
    builder.inheritIO();
    Process process = builder.start();

    res = process.waitFor();

    System.exit(res);
}

From source file:net.sfr.tv.mom.mgt.HornetqConsole.java

/**
 * @param args the command line arguments
 *//*from   w w w.java 2  s .co  m*/
public static void main(String[] args) {

    try {

        String jmxHost = "127.0.0.1";
        String jmxPort = "6001";

        // Process command line arguments
        String arg;
        for (int i = 0; i < args.length; i++) {
            arg = args[i];
            switch (arg) {
            case "-h":
                jmxHost = args[++i];
                break;
            case "-p":
                jmxPort = args[++i];
                break;
            default:
                break;
            }
        }

        // Check for arguments consistency
        if (StringUtils.isEmpty(jmxHost) || !NumberUtils.isNumber(jmxPort)) {
            LOGGER.info("Usage : ");
            LOGGER.info("hq-console.jar <-h host(127.0.0.1)> <-p port(6001)>\n");
            System.exit(1);
        }

        System.out.println(
                SystemUtils.LINE_SEPARATOR.concat(Ansi.format("HornetQ Console ".concat(VERSION), Color.CYAN)));

        final StringBuilder _url = new StringBuilder("service:jmx:rmi://").append(jmxHost).append(':')
                .append(jmxPort).append("/jndi/rmi://").append(jmxHost).append(':').append(jmxPort)
                .append("/jmxrmi");

        final String jmxServiceUrl = _url.toString();
        JMXConnector jmxc = null;

        final CommandRouter router = new CommandRouter();

        try {
            jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxServiceUrl), null);
            assert jmxc != null; // jmxc must be not null
        } catch (final MalformedURLException e) {
            System.out.println(SystemUtils.LINE_SEPARATOR
                    .concat(Ansi.format(jmxServiceUrl + " :" + e.getMessage(), Color.RED)));
        } catch (Throwable t) {
            System.out.println(SystemUtils.LINE_SEPARATOR.concat(
                    Ansi.format("Unable to connect to JMX service URL : ".concat(jmxServiceUrl), Color.RED)));
            System.out.print(SystemUtils.LINE_SEPARATOR.concat(
                    Ansi.format("Did you add jmx-staticport-agent.jar to your classpath ?", Color.MAGENTA)));
            System.out.println(SystemUtils.LINE_SEPARATOR.concat(Ansi.format(
                    "Or did you set the com.sun.management.jmxremote.port option in the hornetq server startup script ?",
                    Color.MAGENTA)));
            System.exit(-1);
        }

        System.out.println("\n".concat(Ansi
                .format("Successfully connected to JMX service URL : ".concat(jmxServiceUrl), Color.YELLOW)));

        final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        // PRINT SERVER STATUS REPORT
        System.out.print((String) router.get(Command.STATUS, Option.VM).execute(mbsc, null));
        System.out.print((String) router.get(Command.STATUS, Option.SERVER).execute(mbsc, null));
        System.out.print((String) router.get(Command.STATUS, Option.CLUSTER).execute(mbsc, null));

        printHelp(router);

        // START COMMAND LINE
        Scanner scanner = new Scanner(System.in);
        System.out.print("> ");
        String input;
        while (!(input = scanner.nextLine().concat(" ")).equals("exit ")) {

            String[] cliArgs = input.split("\\ ");
            CommandHandler handler;

            if (cliArgs.length < 1) {
                System.out.print("> ");
                continue;
            }

            Command cmd = Command.fromString(cliArgs[0]);
            if (cmd == null) {
                System.out.print(Ansi.format("Syntax error !", Color.RED).concat("\n"));
                cmd = Command.HELP;
            }

            switch (cmd) {
            case STATUS:
            case LIST:
            case DROP:

                Set<Option> options = router.get(cmd);

                for (Option opt : options) {

                    if (cliArgs[1].equals(opt.toString())) {
                        handler = router.get(cmd, opt);

                        String[] cmdOpts = null;
                        if (cliArgs.length > 2) {
                            cmdOpts = new String[cliArgs.length - 2];
                            for (int i = 0; i < cmdOpts.length; i++) {
                                cmdOpts[i] = cliArgs[2 + i];
                            }
                        }

                        Object result = handler.execute(mbsc, cmdOpts);
                        if (result != null && String.class.isAssignableFrom(result.getClass())) {
                            System.out.print((String) result);
                        }
                        System.out.print("> ");
                    }
                }

                break;

            case FORK:
                // EXECUTE SYSTEM COMMAND
                ProcessBuilder pb = new ProcessBuilder(Arrays.copyOfRange(cliArgs, 1, cliArgs.length));
                pb.inheritIO();
                pb.start();
                break;

            case HELP:
                printHelp(router);
                break;
            }
        }
    } catch (MalformedURLException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }

    echo(SystemUtils.LINE_SEPARATOR.concat(Ansi.format("Bye!", Color.CYAN)));

}

From source file:net.dv8tion.discord.Yui.java

private static void relaunchInUTF8() throws InterruptedException, UnsupportedEncodingException {
    System.out.println("BotLauncher: We are not running in UTF-8 mode! This is a problem!");
    System.out.println("BotLauncher: Relaunching in UTF-8 mode using -Dfile.encoding=UTF-8");

    String[] command = new String[] { "java", "-Dfile.encoding=UTF-8", "-jar",
            Yui.getThisJarFile().getAbsolutePath() };

    //Relaunches the bot using UTF-8 mode.
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.inheritIO(); //Tells the new process to use the same command line as this one.
    try {/*from  ww w  . j a  v a  2  s .  c o  m*/
        Process process = processBuilder.start();
        process.waitFor(); //We wait here until the actual bot stops. We do this so that we can keep using the same command line.
        System.exit(process.exitValue());
    } catch (IOException e) {
        if (e.getMessage().contains("\"java\"")) {
            System.out.println(
                    "BotLauncher: There was an error relaunching the bot. We couldn't find Java to launch with.");
            System.out.println("BotLauncher: Attempted to relaunch using the command:\n   "
                    + StringUtils.join(command, " ", 0, command.length));
            System.out.println(
                    "BotLauncher: Make sure that you have Java properly set in your Operating System's PATH variable.");
            System.out.println("BotLauncher: Stopping here.");
        } else {
            e.printStackTrace();
        }
    }
}

From source file:org.apache.hyracks.control.nc.service.NCService.java

/**
 * Attempts to launch the "real" NCDriver, based on the configuration
 * information gathered so far./*from w w  w .  j  av a2 s  . c om*/
 * @return true if the process was successfully launched and has now
 * exited with a 0 (normal) exit code. false if some configuration error
 * prevented the process from being launched or the process returned
 * a non-0 (abnormal) exit code.
 */
private static boolean launchNCProcess() {
    try {
        ProcessBuilder pb = new ProcessBuilder(buildCommand());
        configEnvironment(pb.environment());
        // QQQ inheriting probably isn't right
        pb.inheritIO();

        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("Launching NCDriver process");
        }

        // Logfile
        if (!"-".equals(config.logdir)) {
            pb.redirectErrorStream(true);
            File log = new File(config.logdir);
            if (!log.mkdirs()) {
                if (!log.isDirectory()) {
                    throw new IOException(config.logdir + ": cannot create");
                }
                // If the directory IS there, all is well
            }
            File logfile = new File(config.logdir, "nc-" + ncId + ".log");
            // Don't care if this succeeds or fails:
            logfile.delete();
            pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logfile));
            if (LOGGER.isLoggable(Level.INFO)) {
                LOGGER.info("Logging to " + logfile.getCanonicalPath());
            }
        }
        proc = pb.start();

        boolean waiting = true;
        int retval = 0;
        while (waiting) {
            try {
                retval = proc.waitFor();
                waiting = false;
            } catch (InterruptedException ignored) {
            }
        }
        LOGGER.info("NCDriver exited with return value " + retval);
        if (retval == 99) {
            LOGGER.info("Terminating NCService based on return value from NCDriver");
            exit(0);
        }
        return retval == 0;
    } catch (Exception e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "Configuration from CC broken", e);
        }
        return false;
    }
}

From source file:org.exist.launcher.ServiceManager.java

static void run(List<String> args, BiConsumer<Integer, String> consumer) {
    final ProcessBuilder pb = new ProcessBuilder(args);
    final Optional<Path> home = ConfigurationHelper.getExistHome();

    pb.directory(home.orElse(Paths.get(".")).toFile());
    pb.redirectErrorStream(true);/*  ww  w. j  a  v a  2  s . c  om*/
    if (consumer == null) {
        pb.inheritIO();
    }
    try {
        final Process process = pb.start();
        if (consumer != null) {
            final StringBuilder output = new StringBuilder();
            try (final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "UTF-8"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append('\n').append(line);
                }
            }
            final int exitValue = process.waitFor();
            consumer.accept(exitValue, output.toString());
        }
    } catch (IOException | InterruptedException e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Error Running Process", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.samsung.sjs.Compiler.java

public static Process exec(boolean should_inherit_io, String... args) throws IOException {
    System.err.println("Executing: " + Arrays.toString(args));
    Path tmp = Files.createTempDirectory("testing");
    tmp.toFile().deleteOnExit();/*www .j  ava2 s  .c o m*/
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(tmp.toFile());
    if (should_inherit_io) {
        pb.inheritIO();
    }
    return pb.start();
}

From source file:com.yfiton.oauth.receiver.GraphicalReceiver.java

@Override
public AuthorizationData requestAuthorizationData(String authorizationUrl,
        String authorizationCodeParameterName, String... requestParameterNames) throws NotificationException {
    try {//  w w w  . j  a  v  a 2s  .  c  o m
        File tmpFile = File.createTempFile("yfiton", ".auth");

        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.inheritIO();
        processBuilder.command("java",
                //"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005",
                "-classpath", getClasspath(), WebBrowser.class.getName(),
                "--authorization-code-parameter-name=" + authorizationCodeParameterName,
                "--authorization-file=" + tmpFile.getAbsolutePath(), "--authorization-url=" + authorizationUrl,
                "--debug=" + (debug ? "true" : "false"),
                "--webengine-listener-class=" + webEngineListenerClazz.getName());

        Process process = processBuilder.start();

        int returnCode = process.waitFor();

        switch (returnCode) {
        case 0:
            return OAuthUtils.readAuthorizationInfo(tmpFile.toPath());
        case 255:
            throw new NotificationException("Authorization process aborted");
        default:
            throw new NotificationException(
                    "Error occurred while waiting for process: return code " + returnCode);
        }
    } catch (ClassNotFoundException | ConfigurationException | IOException | InterruptedException e) {
        throw new NotificationException(e.getMessage());
    }
}

From source file:edu.illinois.cs.cogcomp.CompileMojo.java

public void execute() throws MojoExecutionException {
    dFlag = FileUtils.getPlatformIndependentFilePath(dFlag);
    gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag);
    sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag);

    classpath.add(dFlag);//w w  w.ja  va  2  s . c  o m
    classpath.add(gspFlag);

    String newpath = StringUtils.join(classpath, File.pathSeparator);

    // If these directories don't exist, make them.
    new File(dFlag).mkdirs();
    new File(gspFlag).mkdirs();

    for (String lbjInputFile : lbjavaInputFileList) {
        if (StringUtils.isEmpty(lbjInputFile)) {
            // making the optional-compile-parameter happy.
            continue;
        }

        getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main...");

        lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile);

        try {
            String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-d",
                    dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile };

            ProcessBuilder pr = new ProcessBuilder(args);
            pr.inheritIO();
            Process p = pr.start();
            p.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Yeah, an error.");
        }
    }

}

From source file:edu.illinois.cs.cogcomp.GenerateMojo.java

public void execute() throws MojoExecutionException {
    dFlag = FileUtils.getPlatformIndependentFilePath(dFlag);
    gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag);
    sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag);

    classpath.add(dFlag);//from  ww w .  j  av  a  2 s  . co m
    classpath.add(gspFlag);

    String newpath = StringUtils.join(classpath, File.pathSeparator);

    // If these directories don't exist, make them.
    new File(dFlag).mkdirs();
    new File(gspFlag).mkdirs();

    for (String lbjInputFile : lbjavaInputFileList) {
        if (StringUtils.isEmpty(lbjInputFile)) {
            // making the optional-compile-step parameter happy.
            continue;
        }

        getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main...");

        lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile);

        try {
            String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-c",
                    "-d", dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile };

            ProcessBuilder pr = new ProcessBuilder(args);
            pr.inheritIO();
            Process p = pr.start();
            p.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Yeah, an error.");
        }
    }

}