1 /**
2 * Oshi (https://github.com/dblock/oshi)
3 *
4 * Copyright (c) 2010 - 2015 The Oshi Project Team
5 *
6 * All rights reserved. This program and the accompanying materials
7 * are made available under the terms of the Eclipse Public License v1.0
8 * which accompanies this distribution, and is available at
9 * http://www.eclipse.org/legal/epl-v10.html
10 *
11 * Contributors:
12 * dblock[at]dblock[dot]org
13 * alessandro[at]perucchi[dot]org
14 * widdis[at]gmail[dot]com
15 * https://github.com/dblock/oshi/graphs/contributors
16 */
17 package oshi.util;
18
19 import java.io.BufferedReader;
20 import java.io.IOException;
21 import java.io.InputStreamReader;
22 import java.util.ArrayList;
23
24 /**
25 * A class for executing on the command line and returning the result of
26 * execution.
27 *
28 * @author alessandro[at]perucchi[dot]org
29 */
30 public class ExecutingCommand {
31 /**
32 * Executes a command on the native command line and returns the result
33 *
34 * @param cmdToRun
35 * Command to run
36 * @return A list of Strings representing the result of the command
37 */
38 public static ArrayList<String> runNative(String cmdToRun) {
39 Process p = null;
40 try {
41 p = Runtime.getRuntime().exec(cmdToRun);
42 p.waitFor();
43 } catch (IOException e) {
44 return null;
45 } catch (InterruptedException e) {
46 return null;
47 }
48
49 BufferedReader reader = new BufferedReader(new InputStreamReader(
50 p.getInputStream()));
51 String line = "";
52 ArrayList<String> sa = new ArrayList<>();
53 try {
54 while ((line = reader.readLine()) != null) {
55 sa.add(line);
56 }
57 } catch (IOException e) {
58 return null;
59 }
60 return sa;
61 }
62
63 /**
64 * Return first line of response for selected command
65 *
66 * @param cmd2launch
67 * String command to be launched
68 * @return String or null
69 */
70 public static String getFirstAnswer(String cmd2launch) {
71 return getAnswerAt(cmd2launch, 0);
72 }
73
74 /**
75 * Return response on selected line index (0-based) after running selected
76 * command
77 *
78 * @param cmd2launch
79 * String command to be launched
80 * @param answerIdx
81 * int index of line in response of the command
82 * @return String whole line in response or null if invalid index or running
83 * of command fails
84 */
85 public static String getAnswerAt(String cmd2launch, int answerIdx) {
86 ArrayList<String> sa = ExecutingCommand.runNative(cmd2launch);
87
88 if (sa != null && answerIdx >= 0 && answerIdx < sa.size()) {
89 return sa.get(answerIdx);
90 }
91 return null;
92 }
93
94 }