Example usage for java.lang Process getErrorStream

List of usage examples for java.lang Process getErrorStream

Introduction

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

Prototype

public abstract InputStream getErrorStream();

Source Link

Document

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

Usage

From source file:com.opensmile.maven.bashClassifier.java

@Override
public JSONObject classify(String audioFile) {
    String line = "";
    String fullLine = "";
    int idx = run_command.lastIndexOf("/");
    String full_path = paths.SMILExtractDir + run_command.substring(0, idx);
    String str = "bash " + paths.SMILExtractDir + run_command + " " + audioFile;
    try {/*from www.j  a  v  a 2s.  c o  m*/
        logger_instance.write(1, "full_path=" + full_path);
        logger_instance.write(1, "bash command: " + str);
        for (int trial = 0; trial < 3; trial++) {
            fullLine = "";
            Process p = Runtime.getRuntime().exec(str, null, new File(full_path));
            p.waitFor();
            logger_instance.write(1, "bash command performed");
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = in.readLine()) != null)
                fullLine = fullLine + line;
            in = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((line = in.readLine()) != null)
                fullLine = fullLine + line;
            if (fullLine.length() > 0)
                break;
        }
        logger_instance.write(1, "bash output:" + fullLine);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    JSONObject jo = null;
    try {
        jo = new JSONObject(fullLine.substring(fullLine.indexOf("{")));
    } catch (JSONException e) {
        System.out.println(fullLine);
        e.printStackTrace();
    } catch (StringIndexOutOfBoundsException e) {
        System.out.println(fullLine);
        e.printStackTrace();
    }

    JSONObject jop = new JSONObject();
    switch ((String) jo.get("TYPE")) {
    case "regression":
        double out = jo.getDouble("VALUE");
        jop = createJsonEntry(entry, out);
        break;
    case "classification":
        jop = createJsonEntry(entry, jo.getJSONArray("PROB"));
        break;
    }
    return jop;
}

From source file:hudson.slaves.CommandLauncher.java

@Override
public void launch(SlaveComputer computer, final TaskListener listener) {
    EnvVars _cookie = null;/*from w  w w .j a  va  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:Exec.java

/**
 * Description of the Method/*ww  w  .j  a  v  a2s  .  c o m*/
 * 
 * @param command
 *            Description of the Parameter
 * @param input
 *            Description of the Parameter
 * @param successCode
 *            Description of the Parameter
 * @param timeout
 *            Description of the Parameter
 * @param lazy
 *            Description of the Parameter
 * @return Description of the Return Value
 */
public static ExecResults execOptions(String command, String input, int successCode, int timeout,
        boolean lazy) {
    Process child = null;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ByteArrayOutputStream errors = new ByteArrayOutputStream();
    ExecResults results = new ExecResults(command, input, successCode, timeout);
    BitSet interrupted = new BitSet(1);
    boolean lazyQuit = false;
    ThreadWatcher watcher;

    try {
        // start the command
        child = Runtime.getRuntime().exec(command);

        // get the streams in and out of the command
        InputStream processIn = child.getInputStream();
        InputStream processError = child.getErrorStream();
        OutputStream processOut = child.getOutputStream();

        // start the clock running
        if (timeout > 0) {
            watcher = new ThreadWatcher(child, interrupted, timeout);
            new Thread(watcher).start();
        }

        // Write to the child process' input stream
        if ((input != null) && !input.equals("")) {
            try {
                processOut.write(input.getBytes());
                processOut.flush();
                processOut.close();
            } catch (IOException e1) {
                results.setThrowable(e1);
            }
        }

        // Read from the child process' output stream
        // The process may get killed by the watcher at any time
        int c = 0;

        try {
            while (true) {
                if (interrupted.get(0) || lazyQuit) {
                    break;
                }

                // interrupted
                c = processIn.read();

                if (c == -1) {
                    break;
                }

                // end of stream
                output.write(c);

                if (lazy && (processIn.available() < 1)) {
                    lazyQuit = true;
                }

                // if lazy and nothing then quit (after at least one read)
            }

            processIn.close();
        } catch (IOException e2) {
            results.setThrowable(e2);
        } finally {
            if (interrupted.get(0)) {
                results.setInterrupted();
            }

            results.setOutput(output.toString());
        }

        // Read from the child process' error stream
        // The process may get killed by the watcher at any time
        try {
            while (true) {
                if (interrupted.get(0) || lazyQuit) {
                    break;
                }

                // interrupted
                c = processError.read();

                if (c == -1) {
                    break;
                }

                // end of stream
                output.write(c);

                if (lazy && (processError.available() < 1)) {
                    lazyQuit = true;
                }

                // if lazy and nothing then quit (after at least one read)
            }

            processError.close();
        } catch (IOException e3) {
            results.setThrowable(e3);
        } finally {
            if (interrupted.get(0)) {
                results.setInterrupted();
            }

            results.setErrors(errors.toString());
        }

        // wait for the return value of the child process.
        if (!interrupted.get(0) && !lazyQuit) {
            int returnCode = child.waitFor();
            results.setReturnCode(returnCode);

            if (returnCode != successCode) {
                results.setError(ExecResults.BADRETURNCODE);
            }
        }
    } catch (InterruptedException i) {
        results.setInterrupted();
    } catch (Throwable t) {
        results.setThrowable(t);
    } finally {
        if (child != null) {
            child.destroy();
        }
    }

    return (results);
}

From source file:Exec.java

/**
 * Description of the Method//from w w w .jav  a  2 s  .c  om
 * 
 * @param command
 *            Description of the Parameter
 * @param input
 *            Description of the Parameter
 * @param successCode
 *            Description of the Parameter
 * @param timeout
 *            Description of the Parameter
 * @param lazy
 *            Description of the Parameter
 * @return Description of the Return Value
 */
public static ExecResults execOptions(String[] command, String input, int successCode, int timeout,
        boolean lazy) {
    Process child = null;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ByteArrayOutputStream errors = new ByteArrayOutputStream();
    ExecResults results = new ExecResults(command[0], input, successCode, timeout);
    BitSet interrupted = new BitSet(1);
    boolean lazyQuit = false;
    ThreadWatcher watcher;

    try {
        // start the command
        child = Runtime.getRuntime().exec(command);

        // get the streams in and out of the command
        InputStream processIn = child.getInputStream();
        InputStream processError = child.getErrorStream();
        OutputStream processOut = child.getOutputStream();

        // start the clock running
        if (timeout > 0) {
            watcher = new ThreadWatcher(child, interrupted, timeout);
            new Thread(watcher).start();
        }

        // Write to the child process' input stream
        if ((input != null) && !input.equals("")) {
            try {
                processOut.write(input.getBytes());
                processOut.flush();
                processOut.close();
            } catch (IOException e1) {
                results.setThrowable(e1);
            }
        }

        // Read from the child process' output stream
        // The process may get killed by the watcher at any time
        int c = 0;

        try {
            while (true) {
                if (interrupted.get(0) || lazyQuit) {
                    break;
                }

                // interrupted
                c = processIn.read();

                if (c == -1) {
                    break;
                }

                // end of stream
                output.write(c);

                if (lazy && (processIn.available() < 1)) {
                    lazyQuit = true;
                }

                // if lazy and nothing then quit (after at least one read)
            }

            processIn.close();
        } catch (IOException e2) {
            results.setThrowable(e2);
        } finally {
            if (interrupted.get(0)) {
                results.setInterrupted();
            }

            results.setOutput(output.toString());
        }

        // Read from the child process' error stream
        // The process may get killed by the watcher at any time
        try {
            while (true) {
                if (interrupted.get(0) || lazyQuit) {
                    break;
                }

                // interrupted
                c = processError.read();

                if (c == -1) {
                    break;
                }

                // end of stream
                output.write(c);

                if (lazy && (processError.available() < 1)) {
                    lazyQuit = true;
                }

                // if lazy and nothing then quit (after at least one read)
            }

            processError.close();
        } catch (IOException e3) {
            results.setThrowable(e3);
        } finally {
            if (interrupted.get(0)) {
                results.setInterrupted();
            }

            results.setErrors(errors.toString());
        }

        // wait for the return value of the child process.
        if (!interrupted.get(0) && !lazyQuit) {
            int returnCode = child.waitFor();
            results.setReturnCode(returnCode);

            if (returnCode != successCode) {
                results.setError(ExecResults.BADRETURNCODE);
            }
        }
    } catch (InterruptedException i) {
        results.setInterrupted();
    } catch (Throwable t) {
        results.setThrowable(t);
    } finally {
        if (child != null) {
            child.destroy();
        }
    }

    return (results);
}

From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java

public void execute(MediaRecord record, File directory) throws EncoderException {

    LOGGER.info(" ffmpeg ?  video ...  Ffmpeg  ===>>> " + args);

    final ProcessBuilder pb = new ProcessBuilder().directory(directory);
    pb.redirectErrorStream(true);//from w  ww  .j av  a  2  s.  co  m
    if (null != directory) {
        LOGGER.info("ffmpeg ??==========>>>" + directory.toString());
    }

    pb.command(args);

    try {
        final Process process = pb.start();
        inputStream = process.getInputStream();

        MediaInputStreamParser.parseMediaRecord(inputStream, record);

        outputStream = process.getOutputStream();
        errorStream = process.getErrorStream();
        // ???????.
        //         BufferedInputStream in = new BufferedInputStream(inputStream);
        //         BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
        //         String lineStr;
        //         while ((lineStr = inBr.readLine()) != null)
        //            LOGGER.info("process.getInputStream() ===>>> " + lineStr);

        int waitfor = process.waitFor();
        if (waitfor != 0) {
            //p.exitValue()==0?1??
            if (process.exitValue() == 1) {
                LOGGER.info("===>>> ffmpeg ? Failed!");
                throw new EncoderException("ffmpeg ? Failed!");
            } else {
                LOGGER.info("==========>>> ffmpeg ??.");
            }
        } else {
            LOGGER.info("==========>>> ffmpeg ??.");
        }

    } catch (IOException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
    } catch (InterruptedException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
        Thread.currentThread().interrupt();
    } finally {
        destroy();
    }
}

From source file:com.ppedregal.typescript.maven.TscMojo.java

private boolean useBinary(String[] args) throws MojoExecutionException {
    if (useTsc) {

        // lets try execute the 'tsc' executable directly
        List<String> arguments = new ArrayList<String>();
        arguments.add("tsc");
        if (libraryDirectory.exists()) {
            File[] libFiles = libraryDirectory.listFiles();
            if (libFiles != null) {
                for (File libFile : libFiles) {
                    if (libFile.getName().endsWith(".d.ts") && libFile.exists()) {
                        String path = libFile.getAbsolutePath();
                        if (!watching) {
                            getLog().info("Adding library file " + libFile);
                        }/*from w  w  w  . j  ava  2  s. c  o m*/
                        arguments.add(path);
                    }
                }
            }
        }
        for (String arg : args) {
            arguments.add(arg);
        }

        getLog().debug("About to execute command: " + arguments);
        ProcessBuilder builder = new ProcessBuilder(arguments);
        try {
            Process process = builder.start();
            redirectOutput(process.getInputStream(), false);
            redirectOutput(process.getErrorStream(), true);

            int value = process.waitFor();
            if (value != 0) {
                getLog().error("Failed to execute tsc. Return code: " + value);
            } else {
                getLog().debug("Compiled file successfully");
            }
        } catch (IOException e) {
            getLog().error("Failed to execute tsc: " + e);
            throw createMojoExecutionException(e);
        } catch (InterruptedException e) {
            throw new MojoExecutionException(e.getMessage());
        }
        return true;
    }
    return false;
}

From source file:com.sonymobile.jenkins.plugins.kerberossso.KerberosFilterTest.java

@Test // TODO do key auth
public void skipFilterWhenCliUsed() throws Exception {
    // This only makes sense when login is required for all URLs
    PluginImpl.getInstance().setAnonymousAccess(false);

    // Turn of the jnlp port to make sure this used servlet request
    rule.jenkins.getTcpSlaveAgentListener().shutdown();

    String authorizedKeys = IOUtils.toString(getClass().getResource("KerberosFilterTest/cli-ssh-key.pub"));
    rule.jenkins.getUser("mockUser").addProperty(new UserPropertyImpl(authorizedKeys));
    String privateKey = getClass().getResource("KerberosFilterTest/cli-ssh-key").getFile();

    // This is supposed to bypass kerberos
    rejectAuthentication();//from   w w w.j  a v a2s. com

    URL jar = rule.jenkins.servletContext.getResource("/WEB-INF/jenkins-cli.jar");
    FilePath cliJar = new FilePath(tmp.getRoot()).child("cli.jar");
    cliJar.copyFrom(jar);
    new File(cliJar.getRemote()).deleteOnExit();

    String java = JavaEnvUtils.getJreExecutable("java");
    String jenkinsUrl = rule.getURL().toExternalForm();

    Process cliProcess = new ProcessBuilder(java, "-jar", cliJar.getRemote(), "-s", jenkinsUrl, "-i",
            privateKey, "who-am-i").start();
    int ret = cliProcess.waitFor();
    String err = IOUtils.toString(cliProcess.getErrorStream());
    String out = IOUtils.toString(cliProcess.getInputStream());
    assertThat(err, out, containsString("Authenticated as: mockUser"));
    assertEquals(err, 0, ret);

    cliProcess = new ProcessBuilder(java, "-jar", cliJar.getRemote(), "-s", jenkinsUrl, "who-am-i").start();
    ret = cliProcess.waitFor();
    err = IOUtils.toString(cliProcess.getErrorStream());
    out = IOUtils.toString(cliProcess.getInputStream());
    assertThat(err, out, containsString("Authenticated as: anonymous"));
    assertEquals(err, 0, ret);
}

From source file:com.xebialabs.overcast.command.CommandProcessor.java

public CommandResponse run(final Command command) {

    logger.debug("Executing command {}", command);

    try {//from  w  w w .  j ava  2  s  .  c  o m
        Process p = new ProcessBuilder(command.asList()).directory(new File(execDir)).start();

        // We do this small trick to have stdout and stderr of the process on the console and
        // at the same time capture them to strings.
        ByteArrayOutputStream errors = new ByteArrayOutputStream();
        ByteArrayOutputStream messages = new ByteArrayOutputStream();

        Thread t1 = showProcessOutput(new TeeInputStream(p.getErrorStream(), errors), System.err);
        Thread t2 = showProcessOutput(new TeeInputStream(p.getInputStream(), messages), System.out);

        int code = p.waitFor();

        t1.join();
        t2.join();

        CommandResponse response = new CommandResponse(code, errors.toString(), messages.toString());

        if (!response.isSuccessful()) {
            throw new NonZeroCodeException(command, response);
        }

        return response;

    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Cannot execute " + command.toString(), e);
    } catch (IOException e) {
        throw new RuntimeException("Cannot execute " + command.toString(), e);
    }
}

From source file:com.kolich.common.util.runtime.RuntimeClosure.java

private final Either<Exception, T> doit(final Process process) {
    Either<Exception, T> result = null;
    try {/*w  w  w . ja va  2  s  .  c  om*/
        result = Right.right(run(process));
        success(process);
    } catch (Exception e) {
        result = Left.left(e);
    } finally {
        if (process != null) {
            closeQuietly(process.getInputStream());
            closeQuietly(process.getOutputStream());
            closeQuietly(process.getErrorStream());
        }
    }
    return result;
}

From source file:com.netscape.cms.profile.constraint.ExternalProcessConstraint.java

public void validate(IRequest request, X509CertInfo info) throws ERejectException {
    CMS.debug("About to execute command: " + this.executable);
    ProcessBuilder pb = new ProcessBuilder(this.executable);

    // set up process environment
    Map<String, String> env = pb.environment();
    for (String k : envVars.keySet()) {
        String v = request.getExtDataInString(envVars.get(k));
        if (v != null)
            env.put(k, v);/*  w w  w.  j av a 2s.com*/
    }
    for (String k : extraEnvVars.keySet()) {
        String v = request.getExtDataInString(extraEnvVars.get(k));
        if (v != null)
            env.put(k, v);
    }

    Process p;
    String stdout = "";
    String stderr = "";
    boolean timedOut;
    try {
        p = pb.start();
        timedOut = !p.waitFor(timeout, TimeUnit.SECONDS);
        if (timedOut)
            p.destroyForcibly();
        else
            stdout = IOUtils.toString(p.getInputStream());
        stderr = IOUtils.toString(p.getErrorStream());
    } catch (Throwable e) {
        String msg = "Caught exception while executing command: " + this.executable;
        CMS.debug(msg);
        CMS.debug(e);
        throw new ERejectException(msg, e);
    }
    if (timedOut)
        throw new ERejectException("Request validation timed out");
    int exitValue = p.exitValue();
    CMS.debug("ExternalProcessConstraint: exit value: " + exitValue);
    CMS.debug("ExternalProcessConstraint: stdout: " + stdout);
    CMS.debug("ExternalProcessConstraint: stderr: " + stderr);
    if (exitValue != 0)
        throw new ERejectException(stdout);
}