Example usage for java.lang Process getInputStream

List of usage examples for java.lang Process getInputStream

Introduction

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

Prototype

public abstract InputStream getInputStream();

Source Link

Document

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

Usage

From source file:net.sf.jasperreports.customvisualization.export.CVElementPhantomJSImageDataProvider.java

/**
 * Executes a command within the given timeout.
 * /*from  w  w  w  . j a v a 2 s  . c  o  m*/
 * @param args
 * @param currentDirectory
 * @param timeout
 */
private static void runCommand(String[] args, File currentDirectory, final int timeout) {
    Thread loggingThread = null;
    Thread interruptingThread = null;

    try {
        String cmd = "";
        for (String arg : args) {
            cmd += " " + arg;
        }

        if (log.isDebugEnabled()) {
            log.debug("Executing external command: " + cmd);
        }
        //System.out.println(cmd);

        ProcessBuilder pb = new ProcessBuilder(Arrays.asList(args));
        pb.directory(currentDirectory);

        final Process externalProcess = pb.start();
        final StringBuilder processOutput = new StringBuilder();

        final boolean[] success = new boolean[1];
        success[0] = false;

        loggingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader br = null;
                try {
                    br = new BufferedReader(new InputStreamReader(externalProcess.getInputStream()));
                    String line;
                    while ((line = br.readLine()) != null) {
                        processOutput.append(line).append("\n");

                        if (line.indexOf("SCRIPT_SUCCESS") >= 0) {
                            success[0] = true;
                            killProcess(externalProcess, 100);
                        } else if (line.indexOf("SCRIPT_ERROR") >= 0) {
                            success[0] = false;
                            killProcess(externalProcess, 100);
                        }
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("External process output:\n" + processOutput.toString());
                    }
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getMessage());
                    }
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            if (log.isWarnEnabled()) {
                                log.warn("Failed to close phantomjs process' inputstream", e);
                            }
                        }
                    }
                }
            }
        });

        interruptingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                if (killProcess(externalProcess, timeout)) {
                    success[0] = false;
                }
            }

        });
        loggingThread.start();
        interruptingThread.start();
        externalProcess.waitFor();

        // We should not care if the phantomjs process does not end on time if it succeeds in producing the desired output.
        if (externalProcess.exitValue() != 0 && !success[0]) {
            // FIXME we should do loggingThread.join(millis) because the
            // process might end before its output if fully processed

            throw new JRRuntimeException("External process did not end properly; exit value: "
                    + externalProcess.exitValue()
                    + (processOutput.length() > 0 ? "; process output:\n" + processOutput + "\n" : "."));
        }

    } catch (IOException e) {
        throw new JRRuntimeException(e);
    } catch (InterruptedException e) {
        throw new JRRuntimeException(e);
    } finally {

        if (interruptingThread != null && interruptingThread.isAlive()) {
            try {
                interruptingThread.interrupt();
            } catch (Exception ex) {
            }
        }
        if (loggingThread != null && loggingThread.isAlive()) {
            try {
                loggingThread.interrupt();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.eucalyptus.blockstorage.TGTWrapper.java

/**
 * executeTGTs the specified tgt command in a separate process. 
 * A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on 
 * the process using {@link java.util.concurrent.ExecutorService ExecutorService} 
 * framework. If the process does not complete with in the timeout, it is cancelled.
 * /*  w w  w. j av a2s . co  m*/
 * @param command
 * @param timeout
 * @return CommandOutput
 * @throws EucalyptusCloudException
 */
private static CommandOutput execute(@Nonnull String[] command, @Nonnull Long timeout)
        throws EucalyptusCloudException, CallTimeoutException {
    try {
        Integer returnValue = -999999;
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        StreamConsumer error = new StreamConsumer(process.getErrorStream());
        StreamConsumer output = new StreamConsumer(process.getInputStream());
        error.start();
        output.start();
        Callable<Integer> processMonitor = new ProcessMonitor(process);
        Future<Integer> processController = getExecutorWithInit().submit(processMonitor);
        try {
            returnValue = processController.get(timeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException tex) {
            String commandStr = buildCommand(command);
            LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out");
            processController.cancel(true);
            Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller")
                    .withVar("timeout", Long.toString(timeout)).log();
            throw new CallTimeoutException("No response from the command " + commandStr
                    + ". Process timed out after waiting for " + timeout + " milliseconds");
        }
        output.join();
        error.join();
        LOG.debug("TGTWrapper executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout="
                + output.getReturnValue() + "\n stderr=" + error.getReturnValue());
        return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue());
    } catch (CallTimeoutException e) {
        throw e;
    } catch (Exception ex) {
        throw new EucalyptusCloudException(ex);
    }
}

From source file:gov.nist.appvet.tool.sigverifier.Service.java

private static boolean execute(String command, StringBuffer output) {
    List<String> commandArgs = Arrays.asList(command.split("\\s+"));
    ProcessBuilder pb = new ProcessBuilder(commandArgs);
    Process process = null;
    IOThreadHandler outputHandler = null;
    IOThreadHandler errorHandler = null;
    int exitValue = -1;
    try {//from  www .j av a2  s  .  c om
        if (command == null || command.isEmpty()) {
            log.error("Command is null or empty");
            return false;
        }
        log.debug("Executing " + command);
        process = pb.start();
        outputHandler = new IOThreadHandler(process.getInputStream());
        outputHandler.start();
        errorHandler = new IOThreadHandler(process.getErrorStream());
        errorHandler.start();
        if (process.waitFor(Properties.commandTimeout, TimeUnit.MILLISECONDS)) {
            // Process has waited and exited within the timeout
            exitValue = process.exitValue();
            if (exitValue == 0) {
                log.debug("Command terminated normally: \n" + outputHandler.getOutput() + "\nErrors: "
                        + errorHandler.getOutput());
                StringBuffer resultOut = outputHandler.getOutput();
                output.append(resultOut);
                return true;
            } else {
                log.error("Command terminated abnormally: \n" + outputHandler.getOutput() + "\nErrors: "
                        + errorHandler.getOutput());
                StringBuffer resultError = errorHandler.getOutput();
                output.append(resultError);
                return false;
            }
        } else {
            // Process exceed timeout or was interrupted
            log.error("Command timed-out or was interrupted: \n" + outputHandler.getOutput() + "\nErrors: "
                    + errorHandler.getOutput());
            StringBuffer resultOutput = outputHandler.getOutput();
            StringBuffer resultError = errorHandler.getOutput();
            if (resultOutput != null) {
                output.append(resultOutput);
                return false;
            } else if (resultError != null) {
                output.append(resultError);
            } else {
                output.append(Properties.toolName + " timed-out");
            }
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        e.printStackTrace();
        return false;
    } finally {
        if (outputHandler.isAlive()) {
            try {
                outputHandler.inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (errorHandler.isAlive()) {
            try {
                errorHandler.inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (process.isAlive()) {
            process.destroy();
        }
    }
}

From source file:madkitgroupextension.export.Export.java

public static void execExternalProcess(String command, final boolean screen_output,
        final boolean screen_erroutput) throws IOException, InterruptedException {
    Runtime runtime = Runtime.getRuntime();
    final Process process = runtime.exec(command);

    // Consommation de la sortie standard de l'application externe dans un Thread separe
    new Thread() {
        public void run() {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line = "";
                try {
                    while ((line = reader.readLine()) != null) {
                        if (screen_output) {
                            System.out.println(line);
                        }// ww  w.j  a  v a 2 s  .  c  om
                    }
                } finally {
                    reader.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }.start();

    // Consommation de la sortie d'erreur de l'application externe dans un Thread separe
    new Thread() {
        public void run() {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String line = "";
                try {
                    while ((line = reader.readLine()) != null) {
                        if (screen_erroutput) {
                            System.out.println(line);
                        }
                    }
                } finally {
                    reader.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }.start();
    process.waitFor();
}

From source file:com.github.maven_nar.NarUtil.java

public static int runCommand(final String cmd, final String[] args, final File workingDirectory,
        final String[] env, final TextStream out, final TextStream err, final TextStream dbg, final Log log,
        final boolean expectFailure) throws MojoExecutionException, MojoFailureException {
    final Commandline cmdLine = new Commandline();

    try {/*  www  . j av  a 2s  . c  o  m*/
        dbg.println("RunCommand: " + cmd);
        cmdLine.setExecutable(cmd);
        if (args != null) {
            for (final String arg : args) {
                dbg.println("  '" + arg + "'");
            }
            cmdLine.addArguments(args);
        }
        if (workingDirectory != null) {
            dbg.println("in: " + workingDirectory.getPath());
            cmdLine.setWorkingDirectory(workingDirectory);
        }

        if (env != null) {
            dbg.println("with Env:");
            for (final String element : env) {
                final String[] nameValue = element.split("=", 2);
                if (nameValue.length < 2) {
                    throw new MojoFailureException("   Misformed env: '" + element + "'");
                }
                dbg.println("   '" + nameValue[0] + "=" + nameValue[1] + "'");
                cmdLine.addEnvironment(nameValue[0], nameValue[1]);
            }
        }

        final Process process = cmdLine.execute();
        final StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), err);
        final StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), out);

        errorGobbler.start();
        outputGobbler.start();
        process.waitFor();
        final int exitValue = process.exitValue();
        dbg.println("ExitValue: " + exitValue);
        final int timeout = 5000;
        errorGobbler.join(timeout);
        outputGobbler.join(timeout);
        if (exitValue != 0 ^ expectFailure) {
            if (log == null) {
                System.err.println(err.toString());
                System.err.println(out.toString());
                System.err.println(dbg.toString());
            } else {
                log.warn(err.toString());
                log.warn(out.toString());
                log.warn(dbg.toString());
            }
            throw new MojoExecutionException("exit code: " + exitValue);
        }
        return exitValue;
    } catch (final MojoExecutionException e) {
        throw e;
    } catch (final Exception e) {
        throw new MojoExecutionException("Could not launch " + cmdLine, e);
    }
}

From source file:msec.org.Tools.java

static public int runCommand(String[] cmd, StringBuffer sb, boolean waitflag) {

    Process pid = null;
    ProcessBuilder build = new ProcessBuilder(cmd);
    build.redirectErrorStream(true);//from w  w w.  j a  v  a2 s.  c  om
    try {
        pid = build.start();
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
    if (sb != null) {
        //BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
        InputStream in = pid.getInputStream();
        byte[] buf = new byte[10240];
        try {
            while (true) {
                int len = in.read(buf);
                if (len <= 0) {
                    break;
                }
                sb.append(new String(buf, 0, len));
            }
        } catch (Exception e) {
        }

    }
    if (waitflag) {
        try {
            pid.waitFor();
            int v = pid.exitValue();
            pid.destroy();
            return v;
        } catch (Exception e) {
        }
    }
    return 0;
}

From source file:com.eislab.af.translator.Translator_hub_i.java

private static String findOutgoingIpForGivenAdress(String remoteIP) {

    if (System.getProperty("os.name").contains("Windows")) {
        final String COMMAND = "route print -4";
        List<RouteInfo> routes = new ArrayList<>();
        try {/*from   w ww.j  a  va  2s  . c  o m*/
            Process exec = Runtime.getRuntime().exec(COMMAND);
            BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));

            System.out.println(System.getProperty("os.name"));
            String line;
            /* examples:
              0.0.0.0          0.0.0.0     10.172.180.1    10.172.180.36     20
              0.0.0.0          0.0.0.0      10.187.20.1    10.187.20.225     25
               10.172.180.0    255.255.255.0         On-link     10.172.180.36    276
              10.172.180.36  255.255.255.255         On-link     10.172.180.36    276
            */
            Pattern p = Pattern.compile(
                    "^\\s*(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+\\S+?\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(\\d+)\\s*$");
            while ((line = reader.readLine()) != null) {
                Matcher match = p.matcher(line);
                if (match.matches()) {
                    String network = match.group(1);
                    String mask = match.group(2);
                    String address = match.group(3);
                    short maskLength = 0;
                    boolean networkMatch = network.contentEquals("0.0.0.0");

                    if (!networkMatch) {
                        SubnetUtils subnet = new SubnetUtils(network, mask);
                        SubnetUtils.SubnetInfo info = subnet.getInfo();
                        networkMatch = info.isInRange(remoteIP);
                        maskLength = Short.valueOf(info.getCidrSignature().split("/")[1]);
                    }

                    if (networkMatch) {
                        short metric = Short.valueOf(match.group(4));
                        routes.add(new RouteInfo(address, (short) 0, maskLength, metric));
                    }

                }
            }
            Collections.sort(routes);
            for (RouteInfo route : routes) {
            }

            if (!routes.isEmpty())
                return routes.get(0).source;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } else if (System.getProperty("os.name").contains("Linux")) {

        List<RouteInfo> routes = new ArrayList<>();
        try {
            //ipv6 ^(.+)/(\d+)\s+(.+)\s(\d+)\s+(\d+)\s+(\d)\s+(.+)$
            //ipv4 ^\s+inet\s\addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$
            //linux route get command parsing: ipv4 ^.*via.*\s+dev\s+.*\s+src\s((?:[0-9\.]{1,3})+)
            //linux route get comand parsing: ipv6 ^.*\sfrom\s::\svia.*\sdev\s.*\ssrc\s((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)
            //final String COMMAND = "/sbin/ifconfig";
            final String COMMAND = "ip route get " + remoteIP;

            Process exec = Runtime.getRuntime().exec(COMMAND);
            BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));

            System.out.println(System.getProperty("os.name"));
            String line;
            /* examples:
             * 10.10.2.130 via 10.0.2.2 dev eth0  src 10.0.2.255
            */
            Pattern p = Pattern.compile("^.*via.*\\s+dev\\s+.*\\s+src\\s((?:[0-9|\\.]{1,3})+)");

            while ((line = reader.readLine()) != null) {
                Matcher match = p.matcher(line);
                if (match.matches()) {

                    String address = match.group(1);

                    routes.add(new RouteInfo(address, (short) 0, (short) 0, (short) 0));//metric is always 0, because we do not extract it from the ifconfig command.

                }
            }
            Collections.sort(routes);

            if (!routes.isEmpty())
                return routes.get(0).source;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return null;
}

From source file:at.alladin.rmbt.android.impl.TracerouteAndroidImpl.java

public static String readFromProcess(Process proc) throws PingException {
    BufferedReader brErr = null;/* ww w . java 2  s.c  om*/
    BufferedReader br = null;
    StringBuilder sbErr = new StringBuilder();
    StringBuilder sb = new StringBuilder();

    try {
        brErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String currInputLine = null;

        while ((currInputLine = brErr.readLine()) != null) {
            sbErr.append(currInputLine);
            sbErr.append("\n");
        }

        if (sbErr.length() > 0) {
            throw new PingException(sbErr.toString());
        }

        br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        currInputLine = null;

        while ((currInputLine = br.readLine()) != null) {
            sb.append(currInputLine);
            sb.append("\n");
        }
    } catch (PingException e) {
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
        }
        try {
            if (brErr != null) {
                brErr.close();
            }
        } catch (IOException e) {
        }
    }

    return sb.toString();
}

From source file:dsfixgui.FileIO.DSFixFileController.java

/**
 *Checks all currently-running processes for specified process
 * //from  w  ww  . j a v  a  2  s  . c  o  m
 * @param targetProcess
 *  The name of the process to be checked for
 * @return
 *  True if target process is currently running; otherwise return false
 * @throws SecurityException
 *  If the user doesn't have permission to access running processes
 * @throws IOException
 *  If an error occurs with reading the list of processes
 */
public static boolean processIsRunning(String targetProcess) throws SecurityException, IOException {
    String line;
    Process p = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\" + "tasklist.exe");
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    //Skip header, which is the first 3 lines:
    input.readLine();
    input.readLine();
    input.readLine();
    while ((line = input.readLine()) != null) {
        if (line.startsWith(targetProcess)) {
            input.close();
            //Found target process
            return true;
        }
    }

    input.close();
    //Checked all processes, target process does not exist
    return false;
}

From source file:com.jsystem.j2autoit.AutoItAgent.java

private static String extractLocation(String regkey) throws Exception {
    String cmd = "reg query " + regkey + " /ve";
    Process child = Runtime.getRuntime().exec(cmd);
    child.waitFor();/*from w  ww .  ja v  a  2 s  .  c  o m*/
    BufferedReader br = new BufferedReader(new InputStreamReader(child.getInputStream()));
    StringBuffer sb = new StringBuffer("");
    String line = null;
    while ((line = br.readLine()) != null) {
        sb.append(line).append(NEW_LINE);
    }
    Matcher mat = PATTERN_EXTRACTING_AUTOIT_LOCATION.matcher(sb.toString());
    if (mat.find()) {
        return mat.group(mat.groupCount()).trim();
    } else {
        throw new Exception("Unable to find AutoIt Location");
    }
}