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:br.unb.cic.bionimbuz.services.storage.bucket.methods.CloudMethodsAmazonGoogle.java

private void CheckStorageDlBandwith(BioBucket bucket) throws Exception {

    // Download//from w  w  w  . j a v a  2 s  .c  om
    final String command = "/bin/dd if=" + bucket.getMountPoint() + "/testfile-" + myId
            + " of=/tmp/testfile 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.setDlBandwith(31 * 1024 * 1024 / value);
}

From source file:com.android.ide.common.process.MtlProcessExecutor.java

private static ListenableFuture<Integer> grabProcessOutput(@NonNull final Process process,
        @NonNull final ProcessOutput output) {
    final SettableFuture<Integer> result = SettableFuture.create();
    final AtomicReference<Exception> exceptionHolder = new AtomicReference<Exception>();

    /*// w w w .j a va2s  .  c  o m
     * It looks like on windows process#waitFor() can return before the thread have filled the
     * arrays, so we wait for both threads and the process itself.
     *
     * To make sure everything is complete before setting the future, the thread handling
     * "out" will wait for all its input to be read, will wait for the "err" thread to finish
     * and will wait for the process to finish. Only after all three are done will it set
     * the future and terminate.
     *
     * This means that the future will be set while the "out" thread is still running, but
     * no output is pending and the process has already finished.
     */
    final Thread threadErr = new Thread("stderr") {
        @Override
        public void run() {
            InputStream stderr = process.getErrorStream();
            OutputStream stream = output.getErrorOutput();

            try {
                ByteStreams.copy(stderr, stream);
                stream.flush();
            } catch (IOException e) {
                exceptionHolder.compareAndSet(null, e);
            }
        }
    };

    Thread threadOut = new Thread("stdout") {
        @Override
        public void run() {
            InputStream stdout = process.getInputStream();
            OutputStream stream = output.getStandardOutput();

            try {
                ByteStreams.copy(stdout, stream);
                stream.flush();
            } catch (Exception e) {
                exceptionHolder.compareAndSet(null, e);
            }

            try {
                threadErr.join();
                int processResult = process.waitFor();
                if (exceptionHolder.get() != null) {
                    result.setException(exceptionHolder.get());
                }

                result.set(processResult);
                output.close();
            } catch (Exception e) {
                result.setException(e);
            }
        }
    };

    threadErr.start();
    threadOut.start();

    return result;
}

From source file:uk.co.codezen.maven.composer.mojo.AbstractComposerMojo.java

/**
 * Execute an arbitrary command, forwarding the process stdout to the Log info level
 * and the process stderr to the Java error level.
 *
 * @param command Command to execute//from  w ww  . j ava  2  s  . c  om
 * @param workingDirectory Working directory
 * @throws IOException IO problem executing command
 */
private int runCommand(List<String> command, String workingDirectory) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.directory(new File(workingDirectory));
    Process composerProcess = processBuilder.start();

    // Link Maven stdout/stderr with process
    pipe(composerProcess.getInputStream(), System.out);
    pipe(composerProcess.getErrorStream(), System.err);

    while (true) {
        try {
            composerProcess.waitFor();
            break;
        } catch (InterruptedException e) {
            // Do nothing, re-run loop
        }
    }

    return composerProcess.exitValue();
}

From source file:io.snappydata.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  av a 2s.  c o  m*/

    String[] cmd = buildJavaCommand(vmNum, namingPort);
    System.out.println("Executing " + Arrays.asList(cmd));
    File workingDir = getVMDir(vmNum, true);
    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, workingDir.getAbsoluteFile());
    processes.put(vmNum, holder);
    linkStreams(vmNum, holder, process.getErrorStream(), System.err);
    linkStreams(vmNum, holder, process.getInputStream(), System.out);
}

From source file:Util.PacketGenerator.java

public void GenerateGraphGnuplot() {
    try {//  www . j ava2  s.  c om
        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();
    }
}

From source file:com.photon.phresco.framework.impl.ApplicationManagerImpl.java

private BufferedInputStream executeLiquibaseMavenCommand(ProjectInfo projectInfo, ActionType action,
        StringBuilder command, String workingDirectory) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug(/* w w w . j a v  a 2  s.  co  m*/
                "Entering Method ApplicationManagerImpl.executeMavenCommand(Project project, ActionType action, StringBuilder command)");
        S_LOGGER.debug("executeMavenCommand() Project Code = " + projectInfo.getProjectCode());
        S_LOGGER.debug("executeMavenCommand() Command = " + command.toString());
        S_LOGGER.debug("executeMavenCommand() ActionType Name = " + action.getActionType());
    }

    createPomArg(projectInfo, command, workingDirectory);
    Commandline cl = new Commandline(command.toString());
    if (StringUtils.isNotEmpty(workingDirectory)) {
        cl.setWorkingDirectory(workingDirectory);
    }
    try {
        Process process = cl.execute();
        InputStream inputStream = process.getInputStream();
        InputStream errorStream = process.getErrorStream();
        SequenceInputStream sequenceInputStream = new SequenceInputStream(inputStream, errorStream);
        return new BufferedInputStream(new MyWrapper(sequenceInputStream));
    } catch (CommandLineException e) {
        throw new PhrescoException(e);
    }
}

From source file:io.treefarm.plugins.haxe.components.nativeProgram.AbstractNativeProgram.java

protected int processExecution(Process process, Logger outputLogger, boolean tolerateErrors)
        throws NativeProgramException {
    try {//from   w  w  w  .ja  v  a  2 s.  c  o m
        CleanStream cleanError = new CleanStream(process.getErrorStream(), outputLogger, getErrorStream(),
                myName());

        CleanStream cleanOutput = new CleanStream(process.getInputStream(), outputLogger,
                CleanStream.CleanStreamType.INFO, myName());

        cleanError.start();
        cleanOutput.start();

        int returnValue = process.waitFor();
        int errorCount = cleanError.getCount();

        if (!tolerateErrors) {
            if (returnValue == 0 && errorCount > 0) {
                returnValue = errorCount;
            }
        } else {
            logger.info(errorCount + " errors ignored.");
        }

        return returnValue;
    } catch (InterruptedException e) {
        throw new NativeProgramException("Program was interrupted", e);
    }
}

From source file:br.unb.cic.bionimbuz.services.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());
    }/*  ww w.  j  a va2 s .c  o m*/

    float latency = 0;
    int i;

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

        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 List<String> output = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(isr)) {
            String line;
            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);

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

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

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

From source file:com.blackducksoftware.integration.hub.cli.SimpleScanService.java

/**
 * If running in an environment that handles process creation, this method should be overridden to construct a
 * process to execute the scan in the environment-specific way.
 *//*  w w  w .jav a 2  s .  co m*/
public Result executeScan(HubServerConfig hubServerConfig, HubSupportHelper hubSupportHelper,
        CIEnvironmentVariables ciEnvironmentVariables, CLILocation cliLocation, int scanMemory,
        boolean verboseRun, boolean dryRun, String project, String version, List<String> scanTargetPaths,
        String workingDirectoryPath, List<String> cmd)
        throws IOException, InterruptedException, IllegalArgumentException, EncryptionException {
    printCommand(cmd);

    final File standardOutFile = new File(logDirectory, "CLI_Output.txt");
    standardOutFile.createNewFile();
    try (FileOutputStream outputFileStream = new FileOutputStream(standardOutFile)) {
        ScannerSplitStream splitOutputStream = new ScannerSplitStream(logger, outputFileStream);
        final ProcessBuilder processBuilder = new ProcessBuilder(cmd).redirectError(PIPE).redirectOutput(PIPE);

        processBuilder.environment().put("BD_HUB_PASSWORD",
                hubServerConfig.getGlobalCredentials().getDecryptedPassword());

        final String bdioEnvVar = ciEnvironmentVariables.getValue("BD_HUB_DECLARED_COMPONENTS");
        if (StringUtils.isNotBlank(bdioEnvVar)) {
            processBuilder.environment().put("BD_HUB_DECLARED_COMPONENTS", bdioEnvVar);
        }

        Process hubCliProcess = processBuilder.start();

        // The cli logs go the error stream for some reason
        StreamRedirectThread redirectThread = new StreamRedirectThread(hubCliProcess.getErrorStream(),
                splitOutputStream);
        redirectThread.start();

        int returnCode = hubCliProcess.waitFor();

        // the join method on the redirect thread will wait until the thread is dead
        // the thread will die when it reaches the end of stream and the run method is finished
        redirectThread.join();

        splitOutputStream.flush();
        logger.info(IoUtils.toString((hubCliProcess.getInputStream())));

        logger.info("Hub CLI return code : " + returnCode);
        logger.info("You can view the BlackDuck Scan CLI logs at : '" + logDirectory.getCanonicalPath() + "'");

        if (returnCode == 0) {
            return Result.SUCCESS;
        } else {
            return Result.FAILURE;
        }
    }
}

From source file:eu.itool.glassfishmavenplugin.AbstractGlassfishMojo.java

protected void launch(String fName, String params) throws MojoExecutionException {

    try {//from w  w w. jav  a 2  s  . com

        checkConfig();

        String osName = System.getProperty("os.name");
        Runtime runtime = Runtime.getRuntime();

        Process p = null;
        if (osName.startsWith("Windows")) {
            String command[] = { "cmd.exe", "/C",
                    "cd " + glassfishHomeDir.getAbsolutePath() + "\\bin & " + fName + ".bat " + " " + params };

            p = runtime.exec(command);

            InputStream is = p.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            String ln;
            while ((ln = br.readLine()) != null) {
                line += ln;
                getLog().info(ln);

            }
            if (line.contains("failed"))
                throw new MojoFailureException(line);

        } else {
            String command[] = { "sh", "-c",
                    "cd " + glassfishHomeDir.getAbsolutePath() + "/bin; ./" + fName + " " + params };
            p = runtime.exec(command);

            InputStream is = p.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            String ln;
            while ((ln = br.readLine()) != null) {
                line += ln;
                getLog().info(ln);
            }
            if (line.contains("failed"))
                throw new MojoFailureException(line);
        }

    } catch (Exception e) {
        throw new MojoExecutionException("Mojo error occurred: " + e.getMessage(), e);
    }
}