Java ProcessBuilder new console each time called? - java

Hey all not sure if there is a solution to my situation but here goes.
I am sending some 9 cmd.exe commands:
static String startDaemon_2 = "scm daemon start"; //Start Daemon
static String isRQRunning_3 = "RQAdapter.bat status"; //Check if RQ is running
static String startRQ_4 = "RQAdapter.bat start"; //Start RQ
...etc etc....
And this is my main code to fire off the commands:
static ProcessBuilder processBuilder = new ProcessBuilder();
static Process process = null;
static BufferedReader reader = null;
public static Object steps(String cmds, String dir_) {
processBuilder.command("cmd.exe", "/c", cmds);
processBuilder.directory(new File(dir_));
try {
process = processBuilder.start();
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
if (line.contains("Key:")) {
return true;
} else if (line.contains("successfully")) {
return true;
} else if (line.contains("background")) {
return true;
} else if (line.contains("not")) {
//Load the adapter then
return "startRQM_4";
} else if (line.contains("sandbox")) {
return true;
} else if (line.contains("Misfit")) {
return true;
// repair goes here
} else if (line.contains("Unresolved")) {
//at this point theres no need to carry on. theres a conflick
return "fix";
}
}
int exitCode = process.waitFor();
System.out.println(line);
if (exitCode == 0) {
return true;
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
}
And I call that function this way:
result = steps(startDaemon_2, scmDir);
if (result == "false") { System.out.println("not true"); }
result = steps(isRQMRunning_3, scmDir);
etc..... etc......
When I fire these same commands off in an actual cmd window it works just fine. Does what it should do. However, when the java program does the exact same thing it seems not to work even though there are no error.
Then I started thinking that maybe I need to define ProcessBuilder, process, reader
But it seems to still not work and without errors.
Is there some other type of way to do a few cmd.exe in the same setting? Seems it's just doing new stuff for each command.
What I mean by the last sentence is that I log in using the first command and then it goes to the other one which is start daemon, etc. But it seems to act like its brand new for each call (a.k.a. Isn't not logged in when firing the 2nd command, etc...)

Related

Run a shell file in java

In Java you can call a shell file like this:
public class Shell {
private static Shell rootShell = null;
private final Process proc;
private final OutputStreamWriter writer;
private Shell(String cmd) throws IOException {
this.proc = new ProcessBuilder(cmd).redirectErrorStream(true).start();
this.writer = new OutputStreamWriter(this.proc.getOutputStream(), "UTF-8");
}
public void cmd(String command) {
try {
writer.write(command+'\n');
writer.flush();
} catch (IOException e) { }
}
public void close() {
try {
if (writer != null) {
writer.close();
if(proc != null) {
proc.destroy();
}
}
} catch (IOException ignore) {}
}
public static void exec(String command) {
Shell.get().cmd(command);
}
public static Shell get() {
if (Shell.rootShell == null) {
while (Shell.rootShell == null) {
try {
Shell.rootShell = new Shell("su"); //Open with Root Privileges
} catch (IOException e) { }
}
}
return Shell.rootShell;
}
}
Shell.exec("echo " + bt.getLevel() + " > "+ flashfile);
right.
but I have a shell which giving an argument after executing it.
how can I pass that argument? I don't want user type anything to run this shell file. in another word, I want to fully automate a shell file.
If you want to automate a shell file with a Java programme, this can be done. You could even pipe a series of commands to this programme saved in a file and executing these as a batch.
You can execute commands batches of commands from like this:
java -cp experiments-1.0-SNAPSHOT.jar ConsoleReader < commands.txt
commands.txt is a file with a series of commands:
cmd /k date
cmd /k dir
netstat
ipconfig
Or you can with the same programme allow the user to execute commands on the command line.
Below you can find a sample programme which you can compile and be run in the above described manner.
What does it do?
It hooks a java.util.Scanner to the console input and consumes each line.
Then it spawns two threads which listen to the error and input streams and write out either to stderr or stdin.
Empty lines on the console are ignored
If you type "read " it will execute the commands on that file.
Source:
public class ConsoleReader {
public static void main(String[] args) throws IOException, DatatypeConfigurationException {
try(Scanner scanner = new Scanner(new BufferedInputStream(System.in), "UTF-8")) {
readFromScanner(scanner);
}
}
private static final Pattern FILE_INPUT_PAT = Pattern.compile("read\\s*([^\\s]+)");
private static void readFromScanner(Scanner scanner) {
while (scanner.hasNextLine()) {
try {
String command = scanner.nextLine();
if(command != null && !command.trim().isEmpty()) {
command = command.trim();
if("exit".equals(command)) {
break; // exit shell
}
else if(command.startsWith("read")) { // read from file whilst in the shell.
readFile(command);
}
else {
Process p = Runtime.getRuntime().exec(command);
Thread stdout = readFromStream(p.getInputStream(), System.out, "in");
Thread stderr = readFromStream(p.getErrorStream(), System.err, "err");
stdout.join(200);
stderr.join(200);
}
}
}
catch(Exception e) {
Logger.getLogger("ConsoleReader").log(Level.SEVERE, String.format("Failed to execute command %s", e));
}
}
}
private static void readFile(String command) throws FileNotFoundException {
Matcher m = FILE_INPUT_PAT.matcher(command);
if(m.matches()) {
String file = m.group(1);
File f = new File(file);
if (f.exists()) {
try (Scanner subScanner = new Scanner(f)) {
readFromScanner(subScanner);
}
}
}
else {
System.err.printf("Oops, could not find '%s'%n", command);
}
}
private static Thread readFromStream(InputStream stdin, PrintStream out, String name) throws IOException {
Thread thread = new Thread(() -> {
try (BufferedReader in = new BufferedReader(new InputStreamReader(stdin))) {
String line;
while ((line = in.readLine()) != null) {
out.println(line);
}
} catch (IOException e) {
Logger.getLogger("ConsoleReader").log(Level.SEVERE, "Failed to read from stream.", e);
}
}, name);
thread.setDaemon(true);
thread.start();
return thread;
}
}
Runtime.getRuntime().exec("src/[FILE LOCATION]");
I think this is the command you're looking for. Let me know if it works!

How to manage ProcessBuilder for multiple OS?

I would like to manage a Shell executor and i have some problems with Windows (not a surprise).
No pb to detect OS, no pb to start Process with ProcessBuilder, no pb to code a StreamGobbler.
But when i want to test it with JUnit, i have a strange behavior...
If i put "cmd.exe" and "/C" commands for Windows, my CMD script is not working. Without all is perfect.
Where is the problem ?
If tomorrow i want to start an exe, i think cmd.exe /c will be necessary completed with start and path to exe.
My Shell executor:
public static boolean execCmd(List<String> cmd, Map<String, String> env, File workingDir, GobblerListener gobblerListener) {
boolean result = false;
if (isWindows()) {
//cmd.add(0, "cmd.exe");
//cmd.add(1, "/C");
} else if (isUnixSolaris()) {
cmd.add(0, "/bin/ksh");
cmd.add(1, "-c");
} else {
logger.debug(ResourceBundle.getBundle(bundleName).getString("system.env.unknown"));
return result;
}
ProcessBuilder pb = new ProcessBuilder(cmd);
Map<String, String> envp = pb.environment();
for (Map.Entry<String, String> entry : env.entrySet()) {
envp.put(entry.getKey(), entry.getValue());
}
if (workingDir != null) {
pb.directory(workingDir);
}
pb.redirectErrorStream(true);
Process p = null;
try {
p = pb.start();
StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(),
gobblerListener);
outputGobbler.start();
p.waitFor();
outputGobbler.join();
int exitValue = p.exitValue();
result = (exitValue == 0 ? true : false);
} catch (InterruptedException ex) {
logger.error(ResourceBundle.getBundle(bundleName).getString(
"system.env.exec.interrupted"));
} catch (IOException e) {
logger.error(
ResourceBundle.getBundle(bundleName).getString(
"system.env.exec.exception"), e);
} finally {
if (p != null) {
p.destroy();
}
}
return result;
}
Here my StreamGobbler:
public class StreamGobbler extends Thread {
private static final Logger logger = LoggerFactory.getLogger(GobblerListener.class);
public interface Listener {
public void onLine(String line);
}
private Listener listener = null;
private InputStream is = null;
private BufferedReader reader = null;
public StreamGobbler(InputStream is, Listener onLineListener) {
this.is = is;
this.listener = onLineListener;
}
#Override
public void run() {
// keep reading the InputStream until it ends (or an error occurs)
try {
reader = new BufferedReader(new InputStreamReader(is));
try {
String line = reader.readLine();
while (line != null) {
if (listener != null && !line.trim().isEmpty())
listener.onLine(line);
line = reader.readLine();
}
} finally {
reader.close();
}
} catch (IOException e) {
logger.error("", e);
}
}
}
Thank you.

Refresh outputscreen and take inputs at the same time in java

Hi I'm about to write a programm which starts multiple minecraft servers:
If you type 'start servername', it starts this server.
If you type 'watch servername', the program shows the output of this server and you should be able to send commands (to this server) at the same time until you type sth. like 'exit'. The problem is that I don't know how to refresh the outputscreen and take the inputs from the keyboard at the same time.
Here is my code from the server class:
class Server{
private String name;
private StartCommand command;
private boolean on = false;
private Process p = null;
public Server(StartCommand c, String name){
this.command = c;
this.name = name;
}
public void start(){
try {
p = Runtime.getRuntime().exec(command.getCommand());
System.out.println("Server: " + name + " is on now!");
on = true;
} catch (IOException e) {
e.printStackTrace();
on = false;
}
}
public void watch(){
try{
Scanner sc = new Scanner(System.in);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
on = false;
}
}
}
I hope you can help me.
Greetings,
Fabian
Server console should be displayed in separate terminal and client console where user can type in the command.
Similar to any server like mysql has a log where server output's are displayed. mysql client command where user type in their sql commands.
Or else redirect watch output to a file and then type the next command.

How to Ping External IP from Java Android

I am developing a Ping application for Android 2.2.
I try my code and it works, but only in local IPs, that's my problem I want to do ping to external servers too.
Here is my code:
private OnClickListener milistener = new OnClickListener() {
public void onClick(View v) {
TextView info = (TextView) findViewById(R.id.info);
EditText edit = (EditText) findViewById(R.id.edit);
Editable host = edit.getText();
InetAddress in;
in = null;
// Definimos la ip de la cual haremos el ping
try {
in = InetAddress.getByName(host.toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Definimos un tiempo en el cual ha de responder
try {
if (in.isReachable(5000)) {
info.setText("Responde OK");
} else {
info.setText("No responde: Time out");
}
} catch (IOException e) {
// TODO Auto-generated catch block
info.setText(e.toString());
}
}
};
Ping 127.0.0.1 -> OK
Ping 8.8.8.8 (Google DNS) -> Time Out
I put the following line at Manifest XML too:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Can anyone suggest me where I'm doing wrong?
I tried following code, which works for me.
private boolean executeCommand(){
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try
{
Process mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue "+mExitValue);
if(mExitValue==0){
return true;
}else{
return false;
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
System.out.println(" Exception:"+ignore);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println(" Exception:"+e);
}
return false;
}
This is a simple ping I use in one of the projects:
public static class Ping {
public String net = "NO_CONNECTION";
public String host = "";
public String ip = "";
public int dns = Integer.MAX_VALUE;
public int cnt = Integer.MAX_VALUE;
}
public static Ping ping(URL url, Context ctx) {
Ping r = new Ping();
if (isNetworkConnected(ctx)) {
r.net = getNetworkType(ctx);
try {
String hostAddress;
long start = System.currentTimeMillis();
hostAddress = InetAddress.getByName(url.getHost()).getHostAddress();
long dnsResolved = System.currentTimeMillis();
Socket socket = new Socket(hostAddress, url.getPort());
socket.close();
long probeFinish = System.currentTimeMillis();
r.dns = (int) (dnsResolved - start);
r.cnt = (int) (probeFinish - dnsResolved);
r.host = url.getHost();
r.ip = hostAddress;
}
catch (Exception ex) {
Timber.e("Unable to ping");
}
}
return r;
}
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
#Nullable
public static String getNetworkType(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
return activeNetwork.getTypeName();
}
return null;
}
Usage: ping(new URL("https://www.google.com:443/"), this);
Result: {"cnt":100,"dns":109,"host":"www.google.com","ip":"212.188.10.114","net":"WIFI"}
Run the ping utility in Android's command and parse output (assuming you have root permissions)
See the following Java code snippet:
executeCmd("ping -c 1 -w 1 google.com", false);
public static String executeCmd(String cmd, boolean sudo){
try {
Process p;
if(!sudo)
p= Runtime.getRuntime().exec(cmd);
else{
p= Runtime.getRuntime().exec(new String[]{"su", "-c", cmd});
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
String res = "";
while ((s = stdInput.readLine()) != null) {
res += s + "\n";
}
p.destroy();
return res;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
In my case ping works from device but not from the emulator. I found this documentation:
http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking
On the topic of "Local Networking Limitations" it says:
"Depending on the environment, the emulator may not be able to support
other protocols (such as ICMP, used for "ping") might not be
supported. Currently, the emulator does not support IGMP or
multicast."
Further information:
http://groups.google.com/group/android-developers/browse_thread/thread/8657506be6819297
this is a known limitation of the QEMU user-mode network stack.
Quoting from the original doc: Note that ping is not supported
reliably to the internet as it would require root privileges. It
means you can only ping the local router (10.0.2.2).
Ping for the google server or any other server
public boolean isConecctedToInternet() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
I implemented "ping" in pure Android Java and hosted it on gitlab. It does the same thing as the ping executable, but is much easier to configure. It's has a couple useful features like being able to bind to a given Network.
https://github.com/dburckh/AndroidPing
This is what I implemented myself, which returns the average latency:
/*
Returns the latency to a given server in mili-seconds by issuing a ping command.
system will issue NUMBER_OF_PACKTETS ICMP Echo Request packet each having size of 56 bytes
every second, and returns the avg latency of them.
Returns 0 when there is no connection
*/
public double getLatency(String ipAddress){
String pingCommand = "/system/bin/ping -c " + NUMBER_OF_PACKTETS + " " + ipAddress;
String inputLine = "";
double avgRtt = 0;
try {
// execute the command on the environment interface
Process process = Runtime.getRuntime().exec(pingCommand);
// gets the input stream to get the output of the executed command
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
inputLine = bufferedReader.readLine();
while ((inputLine != null)) {
if (inputLine.length() > 0 && inputLine.contains("avg")) { // when we get to the last line of executed ping command
break;
}
inputLine = bufferedReader.readLine();
}
}
catch (IOException e){
Log.v(DEBUG_TAG, "getLatency: EXCEPTION");
e.printStackTrace();
}
// Extracting the average round trip time from the inputLine string
String afterEqual = inputLine.substring(inputLine.indexOf("="), inputLine.length()).trim();
String afterFirstSlash = afterEqual.substring(afterEqual.indexOf('/') + 1, afterEqual.length()).trim();
String strAvgRtt = afterFirstSlash.substring(0, afterFirstSlash.indexOf('/'));
avgRtt = Double.valueOf(strAvgRtt);
return avgRtt;
}
Maybe ICMP packets are blocked by your (mobile) provider. If this code doesn't work on the emulator try to sniff via wireshark or any other sniffer and have a look whats up on the wire when you fire the isReachable() method.
You may also find some info in your device log.
Here is simple code to get latency in kotlin: less if, using ip:String as input, using regex to split format, using avg for latency in ms
var avg = LATENCY_ERROR
val process = Runtime.getRuntime().exec("/system/bin/ping -c 1 $ip")
BufferedReader(InputStreamReader(process.inputStream)).forEachLine {
// it: "PING 194.194.194.194 (194.194.194.194) 56(84) bytes of data."
// it: "rtt min/avg/max/mdev = 326.137/326.137/326.137/0.000 ms"
if (it.contains("rtt ")) {
avg = Regex("\\d+\\.\\d+").findAll(it).toList()[1].value.toFloat().roundToInt()
}
}
To get the boolean value for the hit on the ip
public Boolean getInetAddressByName(String name)
{
AsyncTask<String, Void, Boolean> task = new AsyncTask<String, Void, Boolean>()
{
#Override
protected Boolean doInBackground(String... params) {
try
{
return InetAddress.getByName(params[0]).isReachable(2000);
}
catch (Exception e)
{
return null;
}
}
};
try {
return task.execute(name).get();
}
catch (InterruptedException e) {
return null;
}
catch (ExecutionException e) {
return null;
}
}
Use this Code: this method works on 4.3+ and also for below versions too.
try {
Process process = null;
if(Build.VERSION.SDK_INT <= 16) {
// shiny APIS
process = Runtime.getRuntime().exec(
"/system/bin/ping -w 1 -c 1 " + url);
}
else
{
process = new ProcessBuilder()
.command("/system/bin/ping", url)
.redirectErrorStream(true)
.start();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
StringBuffer output = new StringBuffer();
String temp;
while ( (temp = reader.readLine()) != null)//.read(buffer)) > 0)
{
output.append(temp);
count++;
}
reader.close();
if(count > 0)
str = output.toString();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("PING Count", ""+count);
Log.i("PING String", str);
Pink ip Address
public static int pingHost(String host, int timeout) throws IOException,
InterruptedException {
Runtime runtime = Runtime.getRuntime();
timeout /= 1000;
String cmd = "ping -c 1 -W " + timeout + " " + host;
Process proc = runtime.exec(cmd);
Log.d(TAG, cmd);
proc.waitFor();
int exit = proc.exitValue();
return exit;
}
Ping a host and return an int value of 0 or 1 or 2 0=success, 1=fail,
* 2=error

How to run Linux commands in Java?

I want to create diff of two files. I tried searching for code in Java that does it, but didnt find any simple code/ utility code for this. Hence, I thought if I can somehow run linux diff/sdiff command from my java code and make it return a file that stores the diff then it would be great.
Suppose there are two files fileA and fileB. I should be able to store their diff in a file called fileDiff through my java code. Then fetching data from fileDiff would be no big deal.
You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.
For example, here's a complete program that will showcase how to do it:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class testprog {
public static void main(String args[]) {
String s;
Process p;
try {
p = Runtime.getRuntime().exec("ls -aF");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
}
When compiled and run, it outputs:
line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0
as expected.
You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).
If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.
You can also write a shell script file and invoke that file from the java code. as shown below
{
Process proc = Runtime.getRuntime().exec("./your_script.sh");
proc.waitFor();
}
Write the linux commands in the script file, once the execution is over you can read the diff file in Java.
The advantage with this approach is you can change the commands with out changing java code.
You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec
Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
try to use unix4j. it s about a library in java to run linux command. for instance if you got a command like:
cat test.txt | grep "Tuesday" | sed "s/kilogram/kg/g" | sort
in this program will become:
Unix4j.cat("test.txt").grep("Tuesday").sed("s/kilogram/kg/g").sort();
You can call run-time commands from java for both Windows and Linux.
import java.io.*;
public class Test{
public static void main(String[] args)
{
try
{
Process process = Runtime.getRuntime().exec("pwd"); // for Linux
//Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line=reader.readLine())!=null)
{
System.out.println(line);
}
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
process.destroy();
}
}
}
Hope it Helps.. :)
Runtime run = Runtime.getRuntime();
//The best possible I found is to construct a command which you want to execute
//as a string and use that in exec. If the batch file takes command line arguments
//the command can be constructed a array of strings and pass the array as input to
//the exec method. The command can also be passed externally as input to the method.
Process p = null;
String cmd = "ls";
try {
p = run.exec(cmd);
p.getErrorStream();
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
}finally{
p.destroy();
}
The suggested solutions could be optimized using commons.io, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:
public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
try {
return execute(command, 0, null, false);
} catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
return execute(command, 0, null, true);
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
Process process = new ProcessBuilder().command("bash", "-c", command).start();
if(timeUnit != null) {
if(process.waitFor(timeout, timeUnit)) {
if(process.exitValue() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
} else {
if(destroyOnTimeout) process.destroy();
throw new ExecutionTimeoutException("Execution timed out: " + command);
}
} else {
if(process.waitFor() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
}
}
public static class ExecutionFailedException extends Exception {
private static final long serialVersionUID = 1951044996696304510L;
private final int exitCode;
private final List<String> errorOutput;
public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
super(message);
this.exitCode = exitCode;
this.errorOutput = errorOutput;
}
public int getExitCode() {
return this.exitCode;
}
public List<String> getErrorOutput() {
return this.errorOutput;
}
}
public static class ExecutionTimeoutException extends Exception {
private static final long serialVersionUID = 4428595769718054862L;
public ExecutionTimeoutException(final String message) {
super(message);
}
}
if the opening in windows
try {
//chm file address
String chmFile = System.getProperty("user.dir") + "/chm/sample.chm";
Desktop.getDesktop().open(new File(chmFile));
} catch (IOException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
{
JOptionPane.showMessageDialog(null, "Terjadi Kesalahan", "Error", JOptionPane.WARNING_MESSAGE);
}
}
ProcessBuilder processBuilder = new ProcessBuilder();
// -- Linux --
// Run a shell command
processBuilder.command("bash", "-c", "ls /home/kk/");
// Run a shell script
//processBuilder.command("path/to/hello.sh");
// -- Windows --
// Run a command
//processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\kk");
// Run a bat file
//processBuilder.command("C:\\Users\\kk\\hello.bat");
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
System.exit(0);
} else {
//abnormal...
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

Categories