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:hu.bme.mit.sette.common.util.process.ProcessUtils.java

/**
 * Searches the running processes. It calls
 * <code>ps asx | grep "[searchExpression]"</code>
 *
 * @param searchExpression/*from  w ww  .j  a v a  2  s  .com*/
 *            the search expression
 * @return the list
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static List<Integer> searchProcess(final String searchExpression) throws IOException {
    // validate search expression
    Validate.notBlank(searchExpression, "The search expression must not be blank");

    for (char ch : ProcessUtils.SEARCH_EXPR_DISALLOWED_CHARS) {
        Validate.isTrue(searchExpression.indexOf(ch) < 0,
                "The search expression must not contain " + "the '%c' character (searchExpression: [%s])", ch,
                searchExpression);
    }

    for (int i = 0; i < searchExpression.length(); i++) {
        char ch = searchExpression.charAt(i);
        Validate.isTrue(SEARCH_EXPR_MIN <= ch && ch <= SEARCH_EXPR_ASCII_MAX,
                "The ASCII codes of the characters of the " + "search expression "
                        + "must be between 0x%02X and 0x%02X " + "(searchExpression: [%s])",
                SEARCH_EXPR_MIN, SEARCH_EXPR_ASCII_MAX, searchExpression);
    }

    // open process

    // command: /bin/bash -c "ps asx | grep \"MyProc\""
    // example: 1000 12345 ... where 12345 is the PID
    String command = String.format("ps asx | grep \"%s\"", searchExpression);

    Process p = Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", command });

    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

    List<Integer> pids = new ArrayList<>();

    // read pids
    while (true) {
        String line = br.readLine();

        if (br.readLine() == null) {
            break;
        }

        Matcher m = ProcessUtils.SEARCH_PROCESS_PATTERN.matcher(line);

        if (m.matches() && !m.group(2).contains(command)) {
            pids.add(Integer.parseInt(m.group(1)));
        }
    }

    return pids;
}

From source file:brooklyn.util.io.FileUtil.java

private static int exec(List<String> cmds, OutputStream out, OutputStream err) {
    StreamGobbler errgobbler = null;/*from   w w w.ja va2  s .  c  om*/
    StreamGobbler outgobbler = null;

    ProcessBuilder pb = new ProcessBuilder(cmds);

    try {
        Process p = pb.start();

        if (out != null) {
            InputStream outstream = p.getInputStream();
            outgobbler = new StreamGobbler(outstream, out, (Logger) null);
            outgobbler.start();
        }
        if (err != null) {
            InputStream errstream = p.getErrorStream();
            errgobbler = new StreamGobbler(errstream, err, (Logger) null);
            errgobbler.start();
        }

        int result = p.waitFor();

        if (outgobbler != null)
            outgobbler.blockUntilFinished();
        if (errgobbler != null)
            errgobbler.blockUntilFinished();

        return result;
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    } finally {
        Streams.closeQuietly(outgobbler);
        Streams.closeQuietly(errgobbler);
    }
}

From source file:io.github.jeddict.jcode.parser.ejs.EJSUtil.java

public static void executeCommand(FileObject workingFolder, ProgressHandler handler, String... command) {
    try {/*from  w  ww .  j  ava2  s  . c om*/
        ProcessBuilder pb = new ProcessBuilder(command);

        //                Map<String, String> env = pb.environment();
        // If you want clean environment, call env.clear() first
        //                env.put("VAR1", "myValue");
        //                env.remove("OTHERVAR");
        //                env.put("VAR2", env.get("VAR1") + "suffix");
        pb.directory(FileUtil.toFile(workingFolder));
        Process proc = pb.start();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        // read the output from the command
        String s;
        while ((s = stdInput.readLine()) != null) {
            handler.append(Console.wrap(s, FG_BLUE));
        }

        // read any errors from the attempted command
        while ((s = stdError.readLine()) != null) {
            handler.append(Console.wrap(s, FG_DARK_RED));
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:com.liferay.sync.engine.util.SyncSystemTestUtil.java

public static boolean startLiferay() throws Exception {
    if (isPortInUse(8080)) {
        Assert.fail("Liferay is currently running. Stop the process before " + "continuing on with any tests.");
    }/*  w  w  w. ja va2  s  . co  m*/

    Process process = executeCommand("run");

    InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());

    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

    String line = null;

    _logger.info("Starting Liferay Portal");

    while ((line = bufferedReader.readLine()) != null) {
        if (_logger.isDebugEnabled()) {
            _logger.debug(line);
        }

        if (line.contains("sync-web is available for use")) {
            break;
        }
    }

    return true;
}

From source file:Main.java

public static String getBusyBoxVer() {
    String text = "";
    Process process = null;
    try {/*from ww w  . java  2 s . com*/
        //Execute command.
        process = Runtime.getRuntime().exec("busybox");

        //Read file (one line is enough).
        text = readFile(process.getInputStream(), 1);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    if (!TextUtils.isEmpty(text)) {
        //Like this:
        //BusyBox v1.22.1 bionic (2015-05-25 18:22 +0800) multi-call binary.
        String[] infos = text.split(" ");
        if (infos[0].equalsIgnoreCase("busybox")) {
            if (infos[1].startsWith("v") || infos[1].startsWith("V")) {
                return infos[1].substring(1);
            }
        }
    }

    return "";
}

From source file:com.github.stagirs.lingvo.syntax.disambiguity.mystem.MyStem.java

public static List<SyntaxItem[][]> process(List<String> text) throws IOException, InterruptedException {
    FileUtils.writeLines(new File("mystem_input"), "utf-8", text);
    Process process = Runtime.getRuntime()
            .exec(new String[] { "./mystem", "-c", "-i", "-d", "mystem_input", "mystem_output" });
    process.waitFor();//from w  ww . j a  va 2  s. co  m
    InputStream is = process.getInputStream();
    try {
        List<String> lines = FileUtils.readLines(new File("mystem_output"), "utf-8");
        List<SyntaxItem[][]> resultList = new ArrayList<SyntaxItem[][]>();
        for (String line : lines) {
            String[] parts = line.split(" ");
            SyntaxItem[][] result = new SyntaxItem[parts.length][];
            for (int i = 0; i < result.length; i++) {
                if (parts[i].isEmpty()) {
                    result[i] = new SyntaxItem[0];
                    continue;
                }
                if (!parts[i].contains("{")) {
                    final String word = parts[i];
                    result[i] = new SyntaxItem[] { new SyntaxItem() {
                        @Override
                        public String getName() {
                            return word;
                        }

                        @Override
                        public String getType() {
                            return "";
                        }

                        @Override
                        public double getScore() {
                            return 0;
                        }
                    } };
                    continue;
                }
                final String word = parts[i].substring(0, parts[i].indexOf('{'));
                final String[] forms = parts[i].substring(parts[i].indexOf('{') + 1, parts[i].indexOf('}'))
                        .split("\\|");
                result[i] = new SyntaxItem[forms.length];
                for (int j = 0; j < result[i].length; j++) {
                    final String type = forms[j];
                    result[i][j] = new SyntaxItem() {
                        @Override
                        public String getName() {
                            return word;
                        }

                        @Override
                        public String getType() {
                            return type;
                        }

                        @Override
                        public double getScore() {
                            return 0;
                        }
                    };
                }
            }
            resultList.add(result);
        }
        return resultList;
    } finally {
        is.close();
    }
}

From source file:it.iit.genomics.cru.bridges.liftover.ws.LiftOverRun.java

public static Mapping runLiftOver(String genome, String fromAssembly, String toAssembly, String chromosome,
        int start, int end) {

    String liftOverCommand = RESOURCE_BUNDLE.getString("liftOverCommand");

    String liftOverPath = RESOURCE_BUNDLE.getString("liftOverPath");

    String mapChainDir = RESOURCE_BUNDLE.getString("mapChainDir");

    String tmpDir = RESOURCE_BUNDLE.getString("tmpDir");

    Mapping mapping = null;//from   ww w .  jav  a 2 s .  com

    Runtime r = Runtime.getRuntime();

    String rootFilename = String.format("%s", RandomStringUtils.randomAlphanumeric(8));

    String inputFilename = rootFilename + "-" + fromAssembly + ".bed";
    String outputFilename = rootFilename + "-" + toAssembly + ".bed";
    String unmappedFilename = rootFilename + "-" + "unmapped.bed";

    String mapChain = fromAssembly.toLowerCase() + "To" + toAssembly.toUpperCase().charAt(0)
            + toAssembly.toLowerCase().substring(1) + ".over.chain.gz";

    try {

        File tmpDirFile = new File(tmpDir);

        // if the directory does not exist, create it
        if (false == tmpDirFile.exists()) {
            System.out.println("creating directory: " + tmpDir);
            boolean result = tmpDirFile.mkdir();

            if (result) {
                System.out.println("DIR created");
            }
        }

        // Write input bed file
        File inputFile = new File(tmpDir + inputFilename);
        // if file doesnt exists, then create it
        if (!inputFile.exists()) {
            inputFile.createNewFile();
        }

        FileWriter fw = new FileWriter(inputFile.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(chromosome + "\t" + start + "\t" + end + "\n");
        bw.close();

        String commandArgs = String.format("%s %s %s %s %s", liftOverPath + "/" + liftOverCommand,
                tmpDir + inputFilename, mapChainDir + mapChain, tmpDir + outputFilename,
                tmpDir + unmappedFilename);
        System.out.println(commandArgs);

        Process p = r.exec(commandArgs);

        p.waitFor();

        BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";

        while ((line = b.readLine()) != null) {
            System.out.println(line);
        }
        b.close();

        b = new BufferedReader(new FileReader(tmpDir + outputFilename));

        while ((line = b.readLine()) != null) {
            String[] cells = line.split("\t");
            String newChromosome = cells[0];
            int newStart = Integer.parseInt(cells[1]);
            int newEnd = Integer.parseInt(cells[2]);
            mapping = new Mapping(genome, toAssembly, newChromosome, newStart, newEnd);
        }
        b.close();

        // delete
        File delete = new File(tmpDir + inputFilename);
        delete.delete();

        delete = new File(tmpDir + outputFilename);
        delete.delete();

        delete = new File(tmpDir + unmappedFilename);
        delete.delete();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return mapping;
}

From source file:Main.java

private static String propReader(String filter) {
    Process process = null;
    try {//from   ww  w . j  ava2 s.  co  m
        process = new ProcessBuilder().command("/system/bin/getprop").redirectErrorStream(true).start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

    StringBuilder log = new StringBuilder();
    String line;
    try {
        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains(filter))
                log.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    process.destroy();
    return log.toString();
}

From source file:com.liferay.blade.samples.test.BladeCLIUtil.java

public static String execute(File workingDir, String... bladeArgs) throws Exception {

    String bladeCLIJarPath = getLatestBladeCLIJar();

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

    command.add("java");
    command.add("-jar");
    command.add(bladeCLIJarPath);//from ww w .ja v  a  2 s .com

    for (String arg : bladeArgs) {
        command.add(arg);
    }

    Process process = new ProcessBuilder(command.toArray(new String[0])).directory(workingDir).start();

    process.waitFor();

    InputStream stream = process.getInputStream();

    String output = new String(IO.read(stream));

    InputStream errorStream = process.getErrorStream();

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

    if (errorStream != null) {
        errorList.add(new String(IO.read(errorStream)));
    }

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

    for (String string : errorList) {
        if (!string.isEmpty() && !string.contains("Picked up JAVA_TOOL_OPTIONS:")) {

            filteredErrorList.add(string);
        }
    }

    assertTrue(filteredErrorList.toString(), filteredErrorList.isEmpty());

    output = StringUtil.toLowerCase(output);

    return output;
}

From source file:Main.java

static void execPrivileged(final String[] cmd_array) throws Exception {
    try {/*from  ww w . ja v a2  s  .  c  o  m*/
        Process process = AccessController.doPrivileged(new PrivilegedExceptionAction<Process>() {
            public Process run() throws Exception {
                return Runtime.getRuntime().exec(cmd_array);
            }
        });
        // Close unused streams to make sure the child process won't hang
        process.getInputStream().close();
        process.getOutputStream().close();
        process.getErrorStream().close();
    } catch (PrivilegedActionException e) {
        throw (Exception) e.getCause();
    }
}