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.synopsys.integration.executable.ProcessBuilderRunner.java

private ExecutableOutput executeProcessBuilder(ProcessBuilder processBuilder) throws ExecutableRunnerException {
    try {//from w w  w . j a v a  2 s . c  o m
        final Process process = processBuilder.start();

        try (InputStream standardOutputStream = process.getInputStream();
                InputStream standardErrorStream = process.getErrorStream()) {
            final ExecutableStreamThread standardOutputThread = new ExecutableStreamThread(standardOutputStream,
                    logger::info, logger::trace);
            standardOutputThread.start();

            final ExecutableStreamThread errorOutputThread = new ExecutableStreamThread(standardErrorStream,
                    logger::info, logger::trace);
            errorOutputThread.start();

            final int returnCode = process.waitFor();
            logger.info("process finished: " + returnCode);

            standardOutputThread.join();
            errorOutputThread.join();

            final String standardOutput = standardOutputThread.getExecutableOutput().trim();
            final String errorOutput = errorOutputThread.getExecutableOutput().trim();

            final ExecutableOutput output = new ExecutableOutput(returnCode, standardOutput, errorOutput);
            return output;
        }
    } catch (final Exception e) {
        throw new ExecutableRunnerException(e);
    }
}

From source file:org.zilverline.web.HandlerValidator.java

/**
 * Validator for SearchForm. Validates name, maxResults, startAt and query
 * //from  www.  j  av  a  2 s.com
 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
 */
public void validate(Object obj, Errors errors) {
    Handler handler = (Handler) obj;
    Map mappings = handler.getMappings();
    // convert the keys to lowercase
    Iterator mapping = mappings.entrySet().iterator();

    try {
        while (mapping.hasNext()) {
            Map.Entry element = (Map.Entry) mapping.next();
            String archiver = (String) element.getValue();
            log.debug("checking mappings: " + archiver);
            // can be empty: then java.util.Zip used
            if (StringUtils.hasLength(archiver)) {
                // the archiver is an external application with options,
                // check whether the application exists
                String exe = archiver.split(" ")[0];
                log.debug("checking mappings: " + exe);
                File exeFile = new File(exe);
                if (exeFile.exists()) {
                    log.debug("Can find " + exe);
                    continue;
                }

                // else try find the thing on the path
                Process proc = Runtime.getRuntime().exec(exe);
                // any error message?
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
                // any output?
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
                // kick them off
                errorGobbler.start();
                outputGobbler.start();

                proc.destroy();
                log.debug("Exit value: " + proc.exitValue());

                // everthing OK?
                if (proc.exitValue() != 0) {
                    // error executing proc
                    log.debug(" --> Can't execute: '" + exe + "'. Exit value: "
                            + SysUtils.getErrorTextById(proc.exitValue()));
                    log.debug("mappings must exist on disk: " + exe);
                    errors.rejectValue("mappings", null, null, "must exist on disk.");
                } else {
                    log.debug(" --> Can execute: '" + exe + "'. Exit value: "
                            + SysUtils.getErrorTextById(proc.exitValue()));
                }
            }
        }
    } catch (Exception e) {
        log.debug("Can not execute one of the mappings", e);
        errors.rejectValue("mappings", null, null, "must exist on disk.");
    }

}

From source file:gsu.ugahacksproject.tagg.java

public void trainNew(String filePath, String result) {
    try {/*  w  w  w  .jav a2  s  .  com*/
        //            System.out.println(fileContent);
        // Runtime rt = Runtime.getRuntime();
        Process p = Runtime.getRuntime()
                .exec("python " + commandPath + "/trainNew.py " + filePath + " " + result + " good");
        BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String line = null;
        while ((line = error.readLine()) != null) {
            System.out.println("Python error: " + line);
        }
        int exitVal = p.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sourceforge.vulcan.dotnet.MSBuildTool.java

@Override
protected void preparePipes(final Process process) throws IOException {
    process.getOutputStream().close();//from   w  w w . ja  v  a2s .  c om
    process.getErrorStream().close();

    if (logFile == null) {
        process.getInputStream().close();
        return;
    }

    final OutputStream logOutputStream = new FileOutputStream(logFile);

    logThread = new Thread(".NET Build Logger [" + projectName + "]") {
        @Override
        public void run() {
            final InputStream inputStream = process.getInputStream();
            try {
                try {
                    IOUtils.copy(inputStream, logOutputStream);
                } finally {
                    try {
                        logOutputStream.close();
                    } finally {
                        inputStream.close();
                    }
                }
            } catch (IOException e) {
                LOG.error("IOException capturing maven build log", e);
            }
        }
    };

    logThread.start();
}

From source file:com.bancvue.mongomigrate.MongoShellExecutor.java

@Override
public int executeJsFile(String pathToJsFile) throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder(pathToMongoExe, mongoConnectionString + "/" + databaseName,
            pathToJsFile);//  w w w.  j  a v  a2 s.  com

    final Process process = builder.start();

    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    InputStream errorStream = process.getErrorStream();
    InputStreamReader errorStreamReader = new InputStreamReader(errorStream);
    BufferedReader errorStreamBufferedReader = new BufferedReader(errorStreamReader);

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    while ((line = errorStreamBufferedReader.readLine()) != null) {
        System.out.println("ERROR: " + line);
    }

    int exitCode = process.waitFor();
    return exitCode;
}

From source file:com.microsoft.alm.plugin.external.commands.CommandTest.java

/**
 * This test makes sure that output from a command is flushed before the completion event is fired.
 *
 * @throws Exception//  w ww  .j a va 2s . com
 */
@Test
public void testRaceCondition() throws Exception {
    // Fake the tool location so this works on any machine
    PowerMockito.mockStatic(TfTool.class);
    when(TfTool.getValidLocation()).thenReturn("/path/tf_home");

    Process proc = Mockito.mock(Process.class);
    PowerMockito.mockStatic(ProcessHelper.class);
    when(ProcessHelper.startProcess(anyString(), anyList())).thenReturn(proc);
    when(proc.getErrorStream()).thenReturn(new InputStream() {
        @Override
        public int read() throws IOException {
            return -1;
        }
    });
    when(proc.getInputStream()).thenReturn(new InputStream() {
        private String result = "12345";
        private int index = 0;

        @Override
        public int read() throws IOException {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (index < result.length()) {
                return result.charAt(index++);
            } else {
                return -1;
            }
        }
    });
    when(proc.waitFor()).thenAnswer(new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            return 0;
        }
    });
    when(proc.exitValue()).thenReturn(0);

    final MyCommand cmd = new MyCommand(null);
    final String output = cmd.runSynchronously();
    Assert.assertEquals("12345", StringUtils.strip(output));
}

From source file:com.telefonica.euro_iaas.sdc.util.CommandExecutorShellImpl.java

/**
 * <p>//www . ja  v a2s .  c o m
 * executeCommand
 * </p>
 * 
 * @param command
 *            a {@link java.lang.String} object.
 * @return an array of {@link java.lang.String} objects.
 * @throws java.io.IOException
 *             if any.
 */
public String[] executeCommand(String command) throws ShellCommandException {
    String[] outputCommand = new String[2];

    try {
        // Command is executed
        logger.log(Level.INFO, "Executing command: " + command);
        Process p = Runtime.getRuntime().exec(command);

        // Leemos la salida del comando
        outputCommand[0] = IOUtils.toString(p.getInputStream());
        outputCommand[1] = IOUtils.toString(p.getErrorStream());

        Integer exitValue = null;
        // this bucle is because sometimes the flows continues and the
        // comand
        // does not finish yet.
        while (exitValue == null) {
            try {
                exitValue = p.exitValue();
            } catch (IllegalThreadStateException e) {
                logger.log(Level.FINEST, "The command does not finished yet");
            }
        }

        if (!exitValue.equals(0)) {
            logger.log(Level.SEVERE, "Error executing command: " + outputCommand[1]);
            throw new ShellCommandException(outputCommand[1]);
        }
        return outputCommand;
    } catch (IOException e) {
        throw new ShellCommandException("Unexpected exception", e);
    }
}

From source file:cn.dockerfoundry.ide.eclipse.server.core.internal.ProcessLauncher.java

/**
 * The process IO needs to be handled in order to not block the process.
 * @param p/*from w  w w  .j  a v a 2  s.c  o  m*/
 * @return
 * @throws IOException
 */
protected void handleProcessIOAsynch(Process p, StringBuffer inputBuffer, StringBuffer errorBuffer) {

    InputStream in = p.getInputStream();
    InputStream error = p.getErrorStream();

    if (in != null) {
        new ProcessStreamHandler(in, inputBuffer, getLaunchName()).start();
    }

    if (error != null) {
        new ProcessStreamHandler(error, errorBuffer, getLaunchName()).start();
    }

}

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

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

From source file:de.cologneintelligence.fitgoodies.maven.FitIntegrationTestMojo.java

private void startProcess(ProcessBuilder builder) throws MojoExecutionException {
    try {/*from  w ww .j a v  a 2 s .co  m*/
        Process process = builder.start();

        new StreamLogger(process.getErrorStream(), true, getLog()).start();
        new StreamLogger(process.getInputStream(), false, getLog()).start();

        int result = process.waitFor();

        boolean success = result == 0;
        saveResult(success);

        if (!success) {
            getLog().info("One or more fit test(s) failed with return code " + result
                    + ". Will fail in verify phase!");
        }

    } catch (Exception e) {
        throw new MojoExecutionException("Error while running fit", e);
    }
}