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.dreamlinx.automation.DINRelay.java

/**
 * This method runs the provided command in the current runtime environment
 * within the instance of this virtual machine.
 *
 * @param commandWithArgs Command and arguments.
 * @return Process/*from www.  j av  a 2s.  c  o  m*/
 * @throws IOException
 */
private void runCommand(String[] commandWithArgs) throws IOException {
    Process p = Runtime.getRuntime().exec(commandWithArgs);
    try {
        // read and close all streams to prevent open handles
        InputStream i = p.getInputStream();
        while (i.available() > 0) {
            i.read();
        }
        i.close();
        i = p.getErrorStream();
        while (i.available() > 0) {
            i.read();
        }
        i.close();
        p.getOutputStream().close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.przemkovv.sphinx.compiler.GXXCompiler.java

private CompilationResult compile(ArrayList<String> cmd, List<File> files, File output_file)
        throws IOException, ExecutionException, InterruptedException {
    if (files != null) {
        for (File file : files) {
            if (FilenameUtils.isExtension(file.getName(), "cpp")
                    || FilenameUtils.isExtension(file.getName(), "c")) {
                cmd.add(file.getAbsolutePath());
            }/*  w w w .j av  a2  s  .  co  m*/
        }
    }

    logger.debug("Compiler command line: {}", cmd);
    final Process process = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]), null,
            output_file.getParentFile());

    Future<String> output_error_result = pool.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return Utils.readAllFromInputStream(process.getErrorStream());
        }
    });
    Future<String> output_result = pool.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return Utils.readAllFromInputStream(process.getInputStream());
        }
    });
    process.waitFor();
    CompilationResult result = new CompilationResult();
    result.output_errror = output_error_result.get();
    result.output = output_result.get();
    result.exit_value = process.exitValue();
    result.executable_file = output_file;
    result.prepare_env = prepare_env_cmd;
    return result;
}

From source file:com.theaigames.engine.io.IOPlayer.java

public IOPlayer(Process process, int index) {

    if (index == 0) {
        this.inputStream = new OutputStreamWriter(process.getOutputStream());
    } else {/*  w  w w  . j ava2 s . c om*/
        this.inputStream = new OutputStreamWriter(new TeeOutputStream(process.getOutputStream(), System.out));
    }
    this.outputGobbler = new InputStreamGobbler(process.getInputStream(), this, "output", index == 1);
    this.errorGobbler = new InputStreamGobbler(process.getErrorStream(), this, "error", index == 1);
    this.process = process;
    this.dump = new StringBuilder();
    this.errorCounter = 0;
    this.finished = false;
    this.playerIndex = index;
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.tgrep.TGrepWriter.java

/**
 * Produces a TGrep2 binary corpus file.
 *
 * @param aFilename/*from   w w  w .  j  a  v a2  s . c o  m*/
 *            the name of the file from which a corpus file shall be created, without extension
 * @throws IOException
 *             if the employed tgrep2 process is interrupted or if it reports an error
 */
private void writeTgrepBinary(String aFilename) throws IOException {
    List<String> cmd = new ArrayList<String>();
    cmd.add(tgrep2File.getAbsolutePath());
    if (writeComments) {
        // enable writing comments
        cmd.add("-C");
    }
    // specify corpus
    cmd.add("-p");
    cmd.add(new File(outputPath, aFilename + EXT_CORPUS).getAbsolutePath());
    cmd.add(new File(outputPath, aFilename + EXT_BINARY + compression.getExtension()).getAbsolutePath());

    getLogger().info("Running tgrep2 command: [" + StringUtils.join(cmd, " ") + "].");

    Process tgrepProcess = null;
    try {
        tgrepProcess = new ProcessBuilder(cmd).start();
        tgrepProcess.waitFor();
    } catch (InterruptedException e) {
        throw new IOException();
    } finally {
        if (tgrepProcess != null) {
            InputStream stderr = tgrepProcess.getErrorStream();
            if (stderr.available() > 0) {
                byte[] data = new byte[stderr.available()];
                stderr.read(data);
                String error = new String(data, "UTF-8");
                getLogger().error(error);
                throw new IOException(error);
            }
        }
    }
}

From source file:dk.deck.remoteconsole.proxy.LocalExecutor.java

public void execute(String command, String[] arguments, final PrintStream out, final PrintStream error)
        throws IOException, InterruptedException {
    List<String> args = new ArrayList<String>();
    args.add(command);//from w  w w.  j  ava2 s. c o  m
    args.addAll(Arrays.asList(arguments));
    ProcessBuilder builder = new ProcessBuilder(args);
    //        Map<String, String> env = builder.environment();
    //        System.out.println("Env:");
    //        for (Map.Entry<String, String> entry : env.entrySet()) {
    //            System.out.println(entry.getKey() + "=" + entry.getValue());
    //        }
    final Process p = builder.start();
    Runnable copyOutput = new Runnable() {

        @Override
        public void run() {
            try {
                IOUtils.copyLarge(p.getInputStream(), out);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    };
    Runnable copyError = new Runnable() {

        @Override
        public void run() {
            try {
                IOUtils.copyLarge(p.getErrorStream(), error);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    };
    new Thread(copyOutput).start();
    new Thread(copyError).start();

    int exitValue = p.waitFor();
    if (exitValue != 0) {
        throw new IllegalStateException("Exit value for dump was " + exitValue);
    }
}

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 w  w  .  j a  v a2  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:com.thoughtworks.go.util.ProcessWrapper.java

ProcessWrapper(Process process, ProcessTag processTag, String command, ConsoleOutputStreamConsumer consumer,
        String encoding, String errorPrefix) {
    this.process = process;
    this.processTag = processTag;
    this.command = command;
    this.startTime = System.currentTimeMillis();
    this.processOutputStream = StreamPumper.pump(process.getInputStream(), new OutputConsumer(consumer), "",
            encoding);//from  w  w w .  j a v  a2  s .  c  om
    this.processErrorStream = StreamPumper.pump(process.getErrorStream(), new ErrorConsumer(consumer),
            errorPrefix, encoding);
    this.processInputStream = new PrintWriter(new OutputStreamWriter(process.getOutputStream()));
}

From source file:net.przemkovv.sphinx.compiler.MSVCCompiler.java

private CompilationResult runCompiler(List<File> files, File output_file, List<String> args, File working_dir)
        throws InvalidCompilerException {
    try {/*from   ww w  .  j a  v  a  2 s.  c  o m*/

        if (output_file == null) {
            output_file = new File(working_dir, RandomStringUtils.randomAlphanumeric(8) + ".exe");
        }
        ArrayList<String> cmd = new ArrayList<>();
        if (prepare_env != null) {

            cmd.add(prepare_env.getAbsolutePath());
            cmd.add("&&");
        }
        cmd.add(msvc.getAbsolutePath());
        cmd.add("/Fe" + output_file.getAbsolutePath());
        if (args != null) {
            cmd.addAll(args);
        }
        if (files != null) {
            for (File file : files) {
                if (FilenameUtils.isExtension(file.getName(), "cpp")
                        || FilenameUtils.isExtension(file.getName(), "c")) {
                    cmd.add(file.getAbsolutePath());
                }

            }
        }

        logger.debug("Compiler command line: {}", cmd);
        final Process process = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]), null,
                output_file.getParentFile());

        Future<String> output_error_result = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return Utils.readAllFromInputStream(process.getErrorStream());
            }
        });
        Future<String> output_result = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return Utils.readAllFromInputStream(process.getInputStream());
            }
        });
        process.waitFor();
        CompilationResult result = new CompilationResult();
        result.output_errror = output_error_result.get();
        result.output = output_result.get();
        result.exit_value = process.exitValue();
        result.executable_file = output_file;
        result.prepare_env = prepare_env;
        return result;
    } catch (IOException | InterruptedException ex) {
        throw new InvalidCompilerException(ex);

    } catch (ExecutionException ex) {
        java.util.logging.Logger.getLogger(MSVCCompiler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:UnmanagedAMLauncher.java

public void launchAM(ApplicationAttemptId attemptId) throws IOException, YarnException {
    Credentials credentials = new Credentials();
    Token<AMRMTokenIdentifier> token = rmClient.getAMRMToken(attemptId.getApplicationId());
    // Service will be empty but that's okay, we are just passing down only
    // AMRMToken down to the real AM which eventually sets the correct
    // service-address.
    credentials.addToken(token.getService(), token);
    File tokenFile = File.createTempFile("unmanagedAMRMToken", "", new File(System.getProperty("user.dir")));
    try {//from   ww w .j  av  a 2 s . c om
        FileUtil.chmod(tokenFile.getAbsolutePath(), "600");
    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    }
    tokenFile.deleteOnExit();
    DataOutputStream os = new DataOutputStream(new FileOutputStream(tokenFile, true));
    credentials.writeTokenStorageToStream(os);
    os.close();

    Map<String, String> env = System.getenv();
    ArrayList<String> envAMList = new ArrayList<String>();
    boolean setClasspath = false;
    for (Map.Entry<String, String> entry : env.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (key.equals("CLASSPATH")) {
            setClasspath = true;
            if (classpath != null) {
                value = value + File.pathSeparator + classpath;
            }
        }
        envAMList.add(key + "=" + value);
    }

    if (!setClasspath && classpath != null) {
        envAMList.add("CLASSPATH=" + classpath);
    }
    ContainerId containerId = ContainerId.newContainerId(attemptId, 0);

    String hostname = InetAddress.getLocalHost().getHostName();
    envAMList.add(Environment.CONTAINER_ID.name() + "=" + containerId);
    envAMList.add(Environment.NM_HOST.name() + "=" + hostname);
    envAMList.add(Environment.NM_HTTP_PORT.name() + "=0");
    envAMList.add(Environment.NM_PORT.name() + "=0");
    envAMList.add(Environment.LOCAL_DIRS.name() + "= /tmp");
    envAMList.add(ApplicationConstants.APP_SUBMIT_TIME_ENV + "=" + System.currentTimeMillis());

    envAMList.add(ApplicationConstants.CONTAINER_TOKEN_FILE_ENV_NAME + "=" + tokenFile.getAbsolutePath());

    String[] envAM = new String[envAMList.size()];
    Process amProc = Runtime.getRuntime().exec(amCmd, envAMList.toArray(envAM));

    final BufferedReader errReader = new BufferedReader(new InputStreamReader(amProc.getErrorStream()));
    final BufferedReader inReader = new BufferedReader(new InputStreamReader(amProc.getInputStream()));

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    System.err.println(line);
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    Thread outThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = inReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    System.out.println(line);
                    line = inReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the out stream", ioe);
            }
        }
    };
    try {
        errThread.start();
        outThread.start();
    } catch (IllegalStateException ise) {
    }

    // wait for the process to finish and check the exit code
    try {
        int exitCode = amProc.waitFor();
        LOG.info("AM process exited with value: " + exitCode);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        amCompleted = true;
    }

    try {
        // make sure that the error thread exits
        // on Windows these threads sometimes get stuck and hang the execution
        // timeout and join later after destroying the process.
        errThread.join();
        outThread.join();
        errReader.close();
        inReader.close();
    } catch (InterruptedException ie) {
        LOG.info("ShellExecutor: Interrupted while reading the error/out stream", ie);
    } catch (IOException ioe) {
        LOG.warn("Error while closing the error/out stream", ioe);
    }
    amProc.destroy();
}