Example usage for java.lang Process getInputStream

List of usage examples for java.lang Process getInputStream

Introduction

In this page you can find the example usage for java.lang Process getInputStream.

Prototype

public abstract InputStream getInputStream();

Source Link

Document

Returns the input stream connected to the normal output of the process.

Usage

From source file:ape.KillNodeCommand.java

public boolean runImpl(String[] args) throws ParseException, IOException {
    if (Main.VERBOSE) {
        System.out.println("NodeType: " + args[0]);
    }//from ww w.j av a 2 s .  co  m

    String nodeType = args[0];

    if (nodeType.toLowerCase().equals("datanode") || nodeType.toLowerCase().equals("tasktracker")
            || nodeType.toLowerCase().equals("jobtracker") || nodeType.toLowerCase().equals("namenode")) {
        System.out.println("Kill is about to execute the following command:");

        /**
         * The line of code below sends a very ugly bash command to kill the corresponding process.
         * It gets a list of running processes, then greps it for the node type, then 
         * removes the result generated by running grep, then it gets the process ID of that line 
         * 
         */
        String cmd = "echo \"kill -9 \\$(ps -ef | grep -i " + nodeType
                + " | grep -v grep | grep -v ape | awk -F ' '  '{print \\$2}')\" > /tmp/kill-node.sh && chmod +x /tmp/kill-node.sh && /tmp/./kill-node.sh && rm /tmp/kill-node.sh";

        System.out.println(cmd);

        ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
        pb.redirectErrorStream(true);
        Process sh = pb.start();
        InputStream shIn = sh.getInputStream();
        try {
            if (sh.waitFor() != 0) {
                System.out.println("Executing Kill Command failed");
                return false;
            }
        } catch (InterruptedException e) {
            System.out.println(
                    "The kill command was killed before it could kill its target process.  Kind of ironic really...");
            e.printStackTrace();
            throw new RuntimeException();
        }
        int c;
        while ((c = shIn.read()) != -1) {
            System.out.write(c);
        }
        try {
            shIn.close();
        } catch (IOException e) {
            System.out.println("Could not close InputStream from the kill process.");
            e.printStackTrace();
            return false;
        }
    }

    else {
        System.out.println("Invalid node type: " + nodeType);
        System.out.println("Should be one of the following: DataNode, TaskTracker, NameNode, JobTracker.");
        return false;
    }
    return true;
}

From source file:com.playonlinux.wine.WineInstallationTest.java

@Test
public void testRun_RunWineVersion_ProcessRunsAndReturnsVersion() throws IOException {
    Process wineProcess = this.wineInstallationToTest.run(new File("/tmp"), "--version", null);

    InputStream inputStream = wineProcess.getInputStream();
    String processOutput = IOUtils.toString(inputStream);

    assertEquals("wine-1.7.26\n", processOutput);
}

From source file:fi.jumi.launcher.remote.ProcessStartingDaemonSummoner.java

@Override
public void connectToDaemon(SuiteConfiguration suite, DaemonConfiguration daemon,
        ActorRef<DaemonListener> listener) {
    // XXX: should we handle multiple connections properly, even though we are expecting only one?
    int port = daemonConnector.listenOnAnyPort(new OneTimeDaemonListenerFactory(
            withInitialMessageTimeout(listener.tell(), daemon.getStartupTimeout())));
    daemon = daemon.melt().setDaemonDir(steward.createDaemonDir(daemon.getJumiHome())).setLauncherPort(port)
            .freeze();// w ww  .  j  a va2 s . co m

    try {
        JvmArgs jvmArgs = new JvmArgsBuilder().setExecutableJar(steward.getDaemonJar(daemon.getJumiHome()))
                .setWorkingDir(Paths.get(suite.getWorkingDirectory())).setJvmOptions(suite.getJvmOptions())
                .setSystemProperties(daemon.toSystemProperties()).setProgramArgs(daemon.toProgramArgs())
                .freeze();
        Process process = processStarter.startJavaProcess(jvmArgs);
        copyInBackground(process.getInputStream(), outputListener); // TODO: write the output to a log file using OS pipes, read it from there with AppRunner
    } catch (Exception e) {
        throw Boilerplate.rethrow(e);
    }
}

From source file:com.thoughtworks.go.util.ProcessWrapper.java

private void close(Process p) {
    try {/*from  w  ww .ja  v a 2 s.com*/
        IOUtils.closeQuietly(p.getInputStream());
        IOUtils.closeQuietly(p.getOutputStream());
        IOUtils.closeQuietly(p.getErrorStream());
    } finally {
        if (p != null) {
            p.destroy();
        }
    }
}

From source file:com.web.searchlocal.flashpaper.thread.Covnert2SwfTask.java

/** 
 * /*from  ww  w  . jav a2s.  c om*/
 */
public void excute() {
    String tmpOutFile = outFile.getPath().concat(File.separator)
            .concat(inFile.getName().replaceAll("[.]{1}.*$", ".swf"));
    List<String> commandArray = new ArrayList<String>();
    commandArray.add(defaultCommand);
    commandArray.add(inFile.getPath());
    commandArray.add("-o");
    commandArray.add(tmpOutFile);
    ProcessBuilder pbObj = new ProcessBuilder();
    pbObj.command(commandArray);
    pbObj.directory(outFile);
    pbObj.redirectErrorStream(true);
    try {
        Process proObj = pbObj.start();
        final InputStream ins = proObj.getInputStream();
        final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Thread th = new Thread() {
            public void run() {
                ReadableByteChannel rbcObj = Channels.newChannel(ins);
                try {
                    while (rbcObj.read(byteBuffer) != -1) {
                        byteBuffer.flip();
                        logger.info(java.nio.charset.Charset.defaultCharset().decode(byteBuffer));
                        byteBuffer.clear();
                    }
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        };
        th.setDaemon(true);
        th.start();
        try {
            proObj.waitFor();
            logger.error("??." + tmpOutFile);
        } catch (InterruptedException e) {
            logger.error(e);
        }
    } catch (IOException e) {
        logger.error(e);
    }
}

From source file:net.landora.video.playerbackends.GenericPlayerBackend.java

@Override
public void playFile(File file) {
    try {/*w  w  w . j  av a2 s .c  om*/
        List<String> args = new ArrayList<String>();
        args.add(ProgramsAddon.getInstance().getConfiguredPath(program));
        args.addAll(Arrays.asList(extraArgs));
        args.add(file.getAbsolutePath());

        ProcessBuilder process = new ProcessBuilder(args);
        process.redirectErrorStream(true);
        Process p = process.start();

        StringWriter buffer = new StringWriter();
        IOUtils.copy(p.getInputStream(), buffer);
        p.waitFor();

    } catch (Exception e) {
        log.error("Error playing file with " + program.getName() + ": " + file, e);
    }
}

From source file:com.haulmont.yarg.formatters.impl.doc.connector.LinuxProcessManager.java

protected List<String> execute(String... args) throws IOException {
    Process process = new ProcessBuilder(args).start();
    @SuppressWarnings("unchecked")
    List<String> lines = IOUtils.readLines(process.getInputStream());
    return lines;
}

From source file:FreeMemoryViewer.java

public double exec(String command) {
    StringBuffer buffer = new StringBuffer("");
    try {//ww  w  .  j  a  va 2  s.c  o m
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Double.parseDouble(buffer.toString());
}

From source file:ca.canucksoftware.systoolsmgr.CommandLine.java

public boolean doCmd() {
    try {//  www  . ja  v a 2 s  . c  om
        response = null;
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(false);
        Process p = pb.start();
        String stdout = getTextFromStream(p.getInputStream());
        String stderr = getTextFromStream(p.getErrorStream());
        if (p.waitFor() != 0) {
            returnCode = p.exitValue();
        } else {
            returnCode = 0;
        }
        if (returnCode == 0) {
            response = stdout;
        } else {
            response = stderr;
        }
    } catch (Exception e) {
        response = e.getMessage();
        returnCode = -1;
    }
    return (returnCode == 0);
}

From source file:alluxio.cli.validation.ClusterConfConsistencyValidationTask.java

private Properties getNodeConf(String node) {
    try {//from  w  ww . j a  va 2s  . c  om
        String homeDir = Configuration.get(PropertyKey.HOME);
        String remoteCommand = String.format("%s/bin/alluxio getConf", homeDir);
        String localCommand = String.format(
                "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand);
        String[] command = { "bash", "-c", localCommand };
        Properties properties = new Properties();
        Process process = Runtime.getRuntime().exec(command);
        properties.load(process.getInputStream());
        return properties;
    } catch (IOException e) {
        System.err.format("Unable to retrieve configuration for %s: %s.", node, e.getMessage());
        return null;
    }
}