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.streamsets.pipeline.stage.executor.shell.ShellExecutor.java

private void executeScript(Record record) throws StageException {
    File script = null;//from  w w  w  .j  av  a2 s. com
    try {
        script = File.createTempFile("sdc-script-executor", ".sh");
        ELVars variables = getContext().createELVars();
        RecordEL.setRecordInContext(variables, record);

        // Serialize the script into a file on disk (in temporary location)
        FileUtils.writeStringToFile(script, config.script);

        ImmutableList.Builder<String> commandBuilder = new ImmutableList.Builder<>();
        if (impersonationMode != ImpersonationMode.DISABLED) {
            commandBuilder.add(sudo);
            commandBuilder.add("-E");
            commandBuilder.add("-u");
            commandBuilder.add(user);
        }

        commandBuilder.add(shell);
        commandBuilder.add(script.getPath());

        List<String> commandLine = commandBuilder.build();

        // External process configuration
        ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
        for (Map.Entry<String, String> entry : config.environmentVariables.entrySet()) {
            processBuilder.environment().put(eval.eval(variables, entry.getKey(), String.class),
                    eval.eval(variables, entry.getValue(), String.class));
        }

        // Start process and configure forwarders for stderr/stdin
        LOG.debug("Executing script: {}", StringUtils.join(commandLine, " "));
        Process process = processBuilder.start();
        new Thread(new ProcessStdIOForwarder(false, process.getInputStream())).start();
        new Thread(new ProcessStdIOForwarder(true, process.getErrorStream())).start();

        int pid = retrievePidIfFeasible(process);
        LOG.debug("Created process with PID {}", pid);

        // User configures the maximal time for the script execution
        boolean finished = process.waitFor(timeout, TimeUnit.MILLISECONDS);
        if (!finished) {
            process.destroyForcibly();
            throw new OnRecordErrorException(record, Errors.SHELL_002);
        }

        if (process.exitValue() != 0) {
            throw new OnRecordErrorException(record, Errors.SHELL_003, process.exitValue());
        }
    } catch (OnRecordErrorException e) {
        errorRecordHandler.onError(e);
    } catch (Exception e) {
        errorRecordHandler.onError(new OnRecordErrorException(record, Errors.SHELL_001, e.toString(), e));
    } finally {
        if (script != null && script.exists()) {
            script.delete();
        }
    }
}

From source file:ee.ria.xroad.monitor.executablelister.AbstractExecLister.java

/**
 * Method for testability/*  w  w  w . j  av  a 2s .  c om*/
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
ProcessOutputs executeProcess() throws IOException, InterruptedException {

    ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", getCommand());

    Process p = b.start();
    p.waitFor();
    ProcessOutputs outputs = new ProcessOutputs();
    // need to read all of output everytime, reading it partially causes bad problems
    outputs.setOut(CharStreams.toString(new InputStreamReader(p.getInputStream())).replace("'", ""));
    outputs.setErr(CharStreams.toString(new InputStreamReader(p.getErrorStream())));
    return outputs;
}

From source file:com.gemstone.gemfire.test.dunit.standalone.ProcessManager.java

public synchronized void launchVM(int vmNum) throws IOException {
    if (processes.containsKey(vmNum)) {
        throw new IllegalStateException("VM " + vmNum + " is already running.");
    }//w w w  .j  a v  a2s .c  o m

    String[] cmd = buildJavaCommand(vmNum, namingPort);
    System.out.println("Executing " + Arrays.asList(cmd));
    File workingDir = getVMDir(vmNum);
    try {
        FileUtil.delete(workingDir);
    } catch (IOException e) {
        //This delete is occasionally failing on some platforms, maybe due to a lingering
        //process. Allow the process to be launched anyway.
        System.err.println(
                "Unable to delete " + workingDir + ". Currently contains " + Arrays.asList(workingDir.list()));
    }
    workingDir.mkdirs();
    if (log4jConfig != null) {
        FileUtils.copyFileToDirectory(log4jConfig, workingDir);
    }

    //TODO - delete directory contents, preferably with commons io FileUtils
    Process process = Runtime.getRuntime().exec(cmd, null, workingDir);
    pendingVMs++;
    ProcessHolder holder = new ProcessHolder(process);
    processes.put(vmNum, holder);
    linkStreams(vmNum, holder, process.getErrorStream(), System.err);
    linkStreams(vmNum, holder, process.getInputStream(), System.out);
}

From source file:io.hops.experiments.benchmarks.interleaved.InterleavedBenchmark.java

private void runCommand(String command) {
    try {//from ww w.j a v a2  s  .c o m
        Logger.printMsg("Going to execute command " + command);
        Process p = Runtime.getRuntime().exec(command);
        printErrors(p.getErrorStream());
        printErrors(p.getInputStream());
        p.waitFor();

        if (command.contains("kill")) { //[s] for some reason NameNode does not start soon after it is killed. TODO: fix it
            Thread.sleep(1000);
        }
    } catch (IOException e) {
        e.printStackTrace();
        Logger.printMsg(
                "Exception During Restarting the NameNode Command " + command + "   Ex: " + e.toString());
    } catch (InterruptedException e) {
        Logger.error(e);
        Logger.printMsg(
                "Exception During Restarting the NameNode Command " + command + "   Ex: " + e.toString());
    }
}

From source file:com.thoughtworks.go.util.command.ProcessRunner.java

public int run() throws IOException, InterruptedException {
    File workingDir = builder.directory() == null ? new File(".") : builder.directory();
    System.out.println(String.format("Trying to run command: %s from %s",
            Arrays.toString(builder.command().toArray()), workingDir.getAbsolutePath()));
    Process process = builder.start();
    int exitCode = process.waitFor();
    System.out.println(//from ww w  .j  a va  2s.c o  m
            "Finished command: " + Arrays.toString(builder.command().toArray()) + ". Exit code: " + exitCode);
    if (exitCode != 0) {
        if (failOnError) {
            throw new RuntimeException(String.format("Command exited with code %s. \n Exception: %s", exitCode,
                    IOUtils.toString(process.getErrorStream())));
        } else {
            LOGGER.error("Command exited with code {}. \n Exception: {}", exitCode,
                    IOUtils.toString(process.getErrorStream()));
        }
    }
    return exitCode;
}

From source file:com.microsoft.azure.management.samples.Utils.java

/**
 * This method is used for invoking native commands.
 *
 * @param command/*from  w w  w  .j a  v  a  2  s.  co m*/
 *            :- command to invoke.
 * @param ignoreErrorStream
 *            : Boolean which controls whether to throw exception or not
 *            based on error stream.
 * @return result :- depending on the method invocation.
 * @throws Exception exceptions thrown from the execution
 */
public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws Exception {
    String result = "";
    String error = "";
    InputStream inputStream = null;
    InputStream errorStream = null;
    BufferedReader br = null;
    BufferedReader ebr = null;
    try {
        Process process = new ProcessBuilder(command).start();
        inputStream = process.getInputStream();
        errorStream = process.getErrorStream();
        br = new BufferedReader(new InputStreamReader(inputStream));
        result = br.readLine();
        process.waitFor();
        ebr = new BufferedReader(new InputStreamReader(errorStream));
        error = ebr.readLine();
        if (error != null && (!error.equals(""))) {
            // To do - Log error message

            if (!ignoreErrorStream) {
                throw new Exception(error, null);
            }
        }
    } catch (Exception e) {
        throw new Exception("Exception occurred while invoking command", e);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (errorStream != null) {
            errorStream.close();
        }
        if (br != null) {
            br.close();
        }
        if (ebr != null) {
            ebr.close();
        }
    }
    return result;
}

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

protected InputStream convertSCsSource(String sourceRawPath, IFolder binroot) throws CoreException {
    String scs2tgf = ScCoreModule.getSCsCompilerPath();
    String includeOsPath = srcroot.getFolder("include").getLocation().toOSString();
    String binOsPath = getRawBinaryPath(binroot, source);

    try {/*from   ww  w. ja v  a 2  s. co m*/
        Process ps = Runtime
                .getRuntime().exec(
                        String.format("\"%s\" -nc -I\"%s\" \"%s\" \"%s\"", scs2tgf, includeOsPath,
                                sourceRawPath, binOsPath),
                        null, new File(source.getParent().getLocation().toOSString()));
        if (ps.waitFor() != 0)
            return ps.getErrorStream();
    } catch (Exception e) {
        log.error("Unexpected exception", e);
        throw new CoreException(new Status(IStatus.ERROR, ScpdevPlugin.PLUGIN_ID, "Unexpected exception", e));
    }

    return null;
}

From source file:com.kdmanalytics.toif.adaptor.SplintAdaptor.java

@Override
public String getGeneratorVersion() {
    final String[] commands = { "splint", "-help", "version" };
    ProcessBuilder splint = new ProcessBuilder(commands);
    try {//w w  w  . j  a  v a  2 s  .  c om
        Process splintInstance = splint.start();
        InputStream in = splintInstance.getErrorStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        String strLine;

        while ((strLine = br.readLine()) != null) {
            String[] stringArray = strLine.split(" ");

            if (stringArray[1].trim().equals("3.1.2")) {
                return stringArray[1].trim();
            } else {
                System.err.println(getAdaptorName() + ": Generator " + stringArray[1]
                        + " found, only version 3.1.2 has been tested");
                return stringArray[1].trim();
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}

From source file:br.unb.bionimbuz.storage.bucket.methods.CloudMethodsAmazonGoogle.java

@Override
public void CheckStorageLatency(BioBucket bucket) throws Exception {

    if (!bucket.isMounted())
        throw new Exception("Cant check latency! Bucket not mounted: " + bucket.getName());

    float latency = 0;
    int i;/*from   w  ww.  j  a  v a2s . co m*/

    for (i = 0; i < LATENCY_CHECKS; i++) {
        //Upload
        String command = "/bin/dd if=/dev/zero of=" + bucket.getMountPoint() + "/pingfile-" + myId
                + " bs=64 count=1 oflag=dsync";

        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(command);
        //System.out.println("\nRunning command: " + command);
        InputStream stderr = proc.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stderr);
        BufferedReader br = new BufferedReader(isr);
        String line;

        List<String> output = new ArrayList<>();

        while ((line = br.readLine()) != null) {
            output.add(line);
            //System.out.println("[command] " + line);
        }

        int exitVal = proc.waitFor();
        //System.out.println("[command] Process exitValue: " + exitVal);

        if (exitVal != 0) {
            throw new Exception("Error in command: " + command);
        }
        int pos1, pos2;

        pos1 = output.get(output.size() - 1).indexOf(" copied, ");
        pos1 += 9;

        pos2 = output.get(output.size() - 1).indexOf(" s, ");

        String aux;

        aux = output.get(output.size() - 1).substring(pos1, pos2);
        aux = aux.replace(',', '.');

        float value = Float.parseFloat(aux);

        latency += value;
        //System.out.println("[current] Latency: " + (latency / (i + 1)));

        File faux = new File(bucket.getMountPoint() + "/pingfile-" + myId);
        faux.delete();
    }

    bucket.setLatency(latency / (i + 1));
}

From source file:br.unb.cic.bionimbuz.services.storage.bucket.methods.CloudMethodsAmazonGoogle.java

private void CheckStorageUpBandwith(BioBucket bucket) throws Exception {

    // Upload/*ww w  . ja va 2  s . com*/
    final String command = "/bin/dd if=/dev/zero of=" + bucket.getMountPoint() + "/testfile-" + myId
            + " bs=30M count=1 iflag=nocache oflag=nocache";

    final Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec(command);
    // System.out.println("\nRunning command: " + command);
    final InputStream stderr = proc.getErrorStream();
    final InputStreamReader isr = new InputStreamReader(stderr);
    final BufferedReader br = new BufferedReader(isr);
    String line;

    final List<String> output = new ArrayList<>();

    while ((line = br.readLine()) != null) {
        output.add(line);
        // System.out.println("[command] " + line);
    }

    final int exitVal = proc.waitFor();
    // System.out.println("[command] Process exitValue: " + exitVal);

    if (exitVal != 0) {
        throw new Exception("Error in command: " + command);
    }

    int pos1, pos2;

    pos1 = output.get(output.size() - 1).indexOf(" copied, ");
    pos1 += 9;

    pos2 = output.get(output.size() - 1).indexOf(" s, ");

    String aux;

    aux = output.get(output.size() - 1).substring(pos1, pos2);
    aux = aux.replace(',', '.');

    final float value = Float.parseFloat(aux);

    bucket.setUpBandwith(31 * 1024 * 1024 / value);
}