Example usage for java.lang Process getOutputStream

List of usage examples for java.lang Process getOutputStream

Introduction

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

Prototype

public abstract OutputStream getOutputStream();

Source Link

Document

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

Usage

From source file:com.isecpartners.gizmo.FourthIdea.java

private void writeToProcess(Process proc, byte[] buf) {
    try {//w  w w .  ja  v  a  2s .  co m
        proc.getOutputStream().write(buf, 0, buf.length);
    } catch (IOException ex) {
        Logger.getLogger(FourthIdea.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Console.java

public StdIn(Process p, ConsoleTextArea cta) {
    setDaemon(true);// w w w .  java  2 s.c  om
    InputStreamReader ir = new InputStreamReader(cta.getIn());
    kb = new BufferedReader(ir);

    BufferedOutputStream os = new BufferedOutputStream(p.getOutputStream());
    op = new PrintWriter((new OutputStreamWriter(os)), true);
    processRunning = true;
}

From source file:hudson.slaves.CommandLauncher.java

@Override
public void launch(SlaveComputer computer, final TaskListener listener) {
    EnvVars _cookie = null;/* ww  w . j  a v a 2s.  c  o  m*/
    Process _proc = null;
    try {
        Slave node = computer.getNode();
        if (node == null) {
            throw new AbortException("Cannot launch commands on deleted nodes");
        }

        listener.getLogger().println(hudson.model.Messages.Slave_Launching(getTimestamp()));
        if (getCommand().trim().length() == 0) {
            listener.getLogger().println(Messages.CommandLauncher_NoLaunchCommand());
            return;
        }
        listener.getLogger().println("$ " + getCommand());

        ProcessBuilder pb = new ProcessBuilder(Util.tokenize(getCommand()));
        final EnvVars cookie = _cookie = EnvVars.createCookie();
        pb.environment().putAll(cookie);
        pb.environment().put("WORKSPACE",
                StringUtils.defaultString(computer.getAbsoluteRemoteFs(), node.getRemoteFS())); //path for local slave log

        {// system defined variables
            String rootUrl = Jenkins.getInstance().getRootUrl();
            if (rootUrl != null) {
                pb.environment().put("HUDSON_URL", rootUrl); // for backward compatibility
                pb.environment().put("JENKINS_URL", rootUrl);
                pb.environment().put("SLAVEJAR_URL", rootUrl + "/jnlpJars/slave.jar");
            }
        }

        if (env != null) {
            pb.environment().putAll(env);
        }

        final Process proc = _proc = pb.start();

        // capture error information from stderr. this will terminate itself
        // when the process is killed.
        new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(),
                proc.getErrorStream(), listener.getLogger()).start();

        computer.setChannel(proc.getInputStream(), proc.getOutputStream(), listener.getLogger(),
                new Channel.Listener() {
                    @Override
                    public void onClosed(Channel channel, IOException cause) {
                        reportProcessTerminated(proc, listener);

                        try {
                            ProcessTree.get().killAll(proc, cookie);
                        } catch (InterruptedException e) {
                            LOGGER.log(Level.INFO, "interrupted", e);
                        }
                    }
                });

        LOGGER.info("slave agent launched for " + computer.getDisplayName());
    } catch (InterruptedException e) {
        e.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch()));
    } catch (RuntimeException e) {
        e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError()));
    } catch (Error e) {
        e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError()));
    } catch (IOException e) {
        Util.displayIOException(e, listener);

        String msg = Util.getWin32ErrorMessage(e);
        if (msg == null) {
            msg = "";
        } else {
            msg = " : " + msg;
        }
        msg = hudson.model.Messages.Slave_UnableToLaunch(computer.getDisplayName(), msg);
        LOGGER.log(Level.SEVERE, msg, e);
        e.printStackTrace(listener.error(msg));

        if (_proc != null) {
            reportProcessTerminated(_proc, listener);
            try {
                ProcessTree.get().killAll(_proc, _cookie);
            } catch (InterruptedException x) {
                x.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch()));
            }
        }
    }
}

From source file:com.palantir.opensource.sysmon.linux.LinuxLoadAverageJMXWrapper.java

void readData() throws LinuxMonitoringException {
    Process process = null;
    BufferedReader stdout = null;
    InputStream stderr = null;//from   w  ww  .ja  v a  2  s. c  o  m
    OutputStream stdin = null;

    try {
        // start process
        process = Runtime.getRuntime().exec(uptimeCmd); // (authorized)
        // initialize stream
        stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
        stderr = process.getErrorStream();
        stdin = process.getOutputStream();

        // pull what should be the header line
        String line = stdout.readLine();
        if (line == null) {
            throw new LinuxMonitoringException("No data read from uptime process!");
        }

        processUptimeLine(line);
    } catch (IOException e) {
        throw new LinuxMonitoringException("Error while reading data from uptime process", e);
    } finally {
        IOUtils.closeQuietly(stdout);
        IOUtils.closeQuietly(stderr);
        IOUtils.closeQuietly(stdin);
        if (process != null) {
            process.destroy();
        }
    }

}

From source file:net.ostis.scpdev.builder.ScRepositoryBuilder.java

/**
 * Create META-file in binary folder.// w ww.  j  a  v  a2 s.  co  m
 */
private void createMetaFile(IFolder binary) throws CoreException {
    IFile meta = binary.getFile("META");

    if (log.isDebugEnabled())
        log.debug("Create META for " + binary);

    String scs2tgf = ScCoreModule.getSCsCompilerPath();

    try {
        Process ps = Runtime.getRuntime()
                .exec(String.format("\"%s\" -nc - \"%s\"", scs2tgf, meta.getLocation().toOSString()));

        BufferedWriter outStream2 = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()));
        outStream2.write("\"/info/dirent\" = {META={}");

        // TODO: remove bad solution with filesystem raw working
        File binaryFolder = binary.getRawLocation().toFile();
        for (String n : binaryFolder.list()) {
            outStream2.write(",\"" + n + "\"={}");
        }

        outStream2.write("};");
        outStream2.close();

        if (ps.waitFor() != 0) {
            System.err.println(IOUtils.toString(ps.getErrorStream()));
        }
    } catch (Exception e) {
        String msg = "Error while creating META-file for binary folder " + binary;
        log.error(msg, e);
        throw new CoreException(new Status(IStatus.ERROR, ScpdevPlugin.PLUGIN_ID, msg, e));
    }
}

From source file:org.cryptomator.frontend.webdav.mount.command.CommandResult.java

/**
 * Constructs a CommandResult from a terminated process and closes all its streams.
 * //from   w w w  . j a v  a 2 s .  c  om
 * @param process An <strong>already finished</strong> process.
 */
CommandResult(Process process) {
    String out = null;
    String err = null;
    CommandFailedException ex = null;
    try {
        out = IOUtils.toString(process.getInputStream());
        err = IOUtils.toString(process.getErrorStream());
    } catch (IOException e) {
        ex = new CommandFailedException(e);
    } finally {
        this.process = process;
        this.stdout = out;
        this.stderr = err;
        this.exception = ex;
        IOUtils.closeQuietly(process.getInputStream());
        IOUtils.closeQuietly(process.getOutputStream());
        IOUtils.closeQuietly(process.getErrorStream());
        logDebugInfo();
    }
}

From source file:org.ballerinalang.test.context.ServerInstance.java

/**
 * Write client options to process./*w  ww . j a v  a2 s . c  o m*/
 *
 * @param options client options
 * @param process process executed
 * @throws IOException
 */
private void writeClientOptionsToProcess(String[] options, Process process) throws IOException {
    OutputStream stdin = process.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));

    for (String arguments : options) {
        writer.write(arguments);
    }
    writer.flush();
    writer.close();
}

From source file:com.thoughtworks.cruise.util.command.CommandLine.java

private Process startProcess(EnvironmentVariableContext environmentVariableContext,
        ConsoleOutputStreamConsumer consumer) throws IOException {
    Process process = createProcess(environmentVariableContext, consumer);
    process.getOutputStream().close();
    return process;
}

From source file:net.sf.mavenjython.JythonMojo.java

public void runJythonScriptOnInstall(File outputDirectory, List<String> args) throws MojoExecutionException {
    getLog().info("running " + args + " in " + outputDirectory);
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(outputDirectory);/*from ww  w .ja va  2 s .c  o m*/
    final Process p;
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException("Executing jython failed. tried to run: " + pb.command(), e);
    }
    copyIO(p.getInputStream(), System.out);
    copyIO(p.getErrorStream(), System.err);
    copyIO(System.in, p.getOutputStream());
    try {
        if (p.waitFor() != 0) {
            throw new MojoExecutionException("Jython failed with return code: " + p.exitValue());
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }

}

From source file:Util.PacketGenerator.java

public void GenerateGraphGnuplot() {
    try {//from   www .  j a  v  a 2 s. c o  m
        for (int j = 6; j <= 6; j++) {
            File real = new File("D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology"
                    + j + "\\Real.csv");
            for (int k = 1; k <= 4; k++) {
                File simu = new File(
                        "D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology" + j
                                + "\\SimulacaoInstancia" + k + ".csv");
                File dat = new File(
                        "D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology" + j
                                + "\\SimulacaoInstancia" + k + ".txt");

                FileInputStream simuFIS = new FileInputStream(simu);
                DataInputStream simuDIS = new DataInputStream(simuFIS);
                BufferedReader simuBR = new BufferedReader(new InputStreamReader(simuDIS));

                FileInputStream realFIS = new FileInputStream(real);
                DataInputStream realDIS = new DataInputStream(realFIS);
                BufferedReader realBR = new BufferedReader(new InputStreamReader(realDIS));

                PrintWriter datPW = new PrintWriter(dat);

                String lineSimu = simuBR.readLine();
                String lineReal = realBR.readLine();

                double maxX = 0.0;
                double maxY = 0.0;

                HashMap<Double, Double> map = new HashMap<>();

                while (lineSimu != null && lineReal != null) {

                    lineSimu = lineSimu.replaceAll(",", ".");
                    String[] simuMatriz = lineSimu.split(";");
                    String[] realMatriz = lineReal.split(";");

                    for (int i = 0; i < simuMatriz.length; i++) {
                        try {
                            Integer valorReal = Integer.parseInt(realMatriz[i]);
                            Double valorSimu = Double.parseDouble(simuMatriz[i]);
                            if (map.containsKey(valorReal) && map.containsValue(valorSimu)) {
                                continue;
                            }
                            map.put(valorReal.doubleValue(), valorSimu);
                            datPW.write(valorReal.doubleValue() + "\t");
                            datPW.write(valorReal.doubleValue() + "\t");
                            datPW.write(valorSimu.doubleValue() + "\t");
                            datPW.write(valorReal.doubleValue() * 1.2 + "\t");
                            datPW.write(valorReal.doubleValue() * 0.8 + "\n");
                            if (valorReal > maxX) {
                                maxX = valorReal;
                            }
                            if (valorSimu > maxY) {
                                maxY = valorSimu;
                            }
                        } catch (NumberFormatException ex) {

                        }
                    }
                    lineSimu = simuBR.readLine();
                    lineReal = realBR.readLine();
                }

                simuFIS.close();
                simuDIS.close();
                simuBR.close();

                realFIS.close();
                realDIS.close();
                realBR.close();

                datPW.close();

                Double max = Math.max(maxX, maxY);
                max *= 1.05;

                Process p = Runtime.getRuntime().exec("cmd");
                new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
                new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
                PrintWriter stdin = new PrintWriter(p.getOutputStream());
                stdin.println("gnuplot");
                stdin.println("cd 'D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology"
                        + j + "'");
                stdin.println("set terminal postscript eps enhanced \"Times\" 20");
                stdin.println("set output \"SimulacaoInstancia" + k + ".eps\"");
                stdin.println("unset title");
                stdin.println("unset style line");
                stdin.println("set style line 1 pt 7 lc 7 lw 1");
                stdin.println("set style line 2 lt 1 lc 7 lw 1");
                stdin.println("set style line 3 lt 4 lc 7 lw 1");
                stdin.println("set style line 4 lt 4 lc 7 lw 1");
                stdin.println("set style line 5 lt 5 lc 5 lw 3");
                stdin.println("set style line 6 lt 6 lc 6 lw 3");
                stdin.println("set style line 7 pt 7 lc 7 lw 3");
                if (k == 4) {
                    stdin.println("set ylabel \"CMO-MT\"");
                    stdin.println("set xlabel \"Real\"");
                } else {
                    stdin.println("set ylabel \"Zhao\"");
                    stdin.println("set xlabel \"CMO-MT\"");
                }
                stdin.println("set key top left");
                stdin.println("set xrange [0:" + max.intValue() + "]");
                stdin.println("set yrange [0:" + max.intValue() + "]");
                stdin.println("set grid ytics lc rgb \"#bbbbbb\" lw 1 lt 0");
                stdin.println("set grid xtics lc rgb \"#bbbbbb\" lw 1 lt 0");
                stdin.println("plot " + "x title \"Referencia\"      ls 2," + "\"SimulacaoInstancia" + k
                        + ".txt\" using 1:3 title \"Matriz\"          ls 7,"
                        + "1.2*x title \"Superior 20%\"    ls 4," + "0.8*x title \"Inferior 20%\"    ls 4");

                stdin.println("exit");
                stdin.println("exit");
                // write any other commands you want here
                stdin.close();
                int returnCode = p.waitFor();
                System.out.println("Return code = " + returnCode);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}