I am playing around with some GIT commands in terminal, but I want to write a java program to automate the process.Please note I am not writing a program straight into a terminal. I am writing it in eclipse. This following code works on windows, but not MAC. How should I change it to run on MAC?
import java.io.*;
public class NewClass {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("GIT");
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();
}
}
}
"GIT" should be "git" for case sensitive systems like Mac OS. Note that without arguments, this will only give you a listing of the git syntax.
Please follow the basic steps outlined in this CS article from Princeton (How to run Java Program on a Mac)
Related
I'm on Windows 10, using ProcessBuilder to run a .exe from my Java program and using BufferedReader to get the number it outputs when it's provided the path that my Java program provides. It's working, but it's freezing the program for an unbearable while when it tries to get the output.
It worked smoothly when I tested it on Ubuntu 20, but I can't make it go fast on Windows. Also, if I run the .exe file from cmd, it goes fast as it should.
Here's my Main class code:
package teste;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
Process process;
String command = "src\\teste\\flir_image_extractor.exe -avg -i C:\\Users\\Daniel\\Desktop\\example.jpg";
try {
ProcessBuilder builder = new ProcessBuilder();
if (isWindows) {
builder.command("cmd.exe", "/c", command);
} else {
builder.command("sh", "-c", command);
}
System.out.println("this");
builder.directory(new File(System.getProperty("user.dir")));
builder.redirectErrorStream(true);
process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line); // Do something with the return
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I tested it with prints, and it hangs just as it enters the while loop, so it looks like readLine() is the issue. Does anyone know what could be slowing it down?
I'm running the code in Eclipse.
I thank you in advance.
A few things to try. It may be the Eclipse console - some versions have been slow if there is a lot of output. You could test this by running this Java app from Windows command line to see if issue goes away, or you could remove your reader.readLine() / System.out.println loop and replace with transferTo:
try(var stdo = p.getInputStream()) {
stdo.transferTo(System.out);
}
Don't forget to wait for the process exit:
int rc = exec.waitFor();
If the Eclipse console is the issue, redirect output to a file before start and check the file afterwards:
pb.redirectOutput(new File("stdout.log"));
Ideally, don't use CMD.EXE / shell to run applications that may be run directly, try as:
String[]command = new String[] {"src\\teste\\flir_image_extractor.exe","-avg", "-i", "C:\\Users\\Daniel\\Desktop\\example.jpg"};
Environment: Windows 10 (Java) -> Windows 10 (PowerShell and C#)
Java: 1.8.0_252
Trying to remotely execute a C# program via PowerShell from Java. Seem to be having issues with the path. The C# program is in a subdirectory under a shared drive.
import java.io.*;
public class CallCSharp {
public static void main(String[] args) {
try {
ProcessBuilder builder = new ProcessBuilder("powershell.exe", "/c",
"\\SharedDrive\\Data\\Bin\\Program.exe \\\\10.1.1.1 -u user -p password");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
} catch (Exception e){
e.printStackTrace();
}
}
}
The error returned is
The term '\SharedDrive\Data\Bin\Program.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
The path is correct and the C# program can be run successfully.
Suspect I am not formatting the ProcessBuilder call correctly.
I am writing a Java application in IntelliJ IDE. The application used Rserve package to connect to R and perform some functions. When I want to run my code for the first time, I have to launch R in the command line and start the Rserve as a daemon, which looks something like this:
R
library(Rserve)
Rserve()
After doing this, I can easily access all the function in R without any errors. However, since this Java code would be bundled as an executable file, so is there a way that Rserve() is invoked automatically as soon as the code is run so that I have to skip this manual step of starting Rserve using the command line?
Here is the code for the Class I wrote to get Rserve working from Java
public class InvokeRserve {
public static void invoke() {
String s;
try {
// run the Unix ""R CMD RServe --vanilla"" command
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("R CMD RServe --vanilla");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
// System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}
I know this question has been asked a long back . I think You have the answer. But the below answer may help others. That's why I am posting my answer.
answer:- Instead of going again and again to the R console to start Rserve. One thing you can do is you can write a java program to start Rserve.
Below code you can use in a java program to start Rserve.
https://www.sitepoint.com/community/t/call-linux-command-from-java-application/3751. This is the link where you will get the code to run a linux command from java.I have changed the command only and posting below.
package javaapplication13;
import java.io.*;
public class linux_java {
public static void main(String[] args) {
try {
String command ="R CMD Rserve";
BufferedWriter out = new BufferedWriter(new FileWriter(
new File(
"/home/jayshree/Desktop/testqavhourly.tab"), true));
final Process process = Runtime.getRuntime().exec(command);
BufferedReader buf = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line;
while ((line = buf.readLine()) != null) {
out.write(line);
out.newLine();
}
buf.close();
out.close();
int returnCode = process.waitFor();
System.out.println("Return code = " + returnCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
So writing a test storm topology with minimal Java experience, so I'm figuring things out in a brute force way. My experience writing storm topologies is also minimal.
I have three supervisor nodes on my cluster and want each of them to run ls in the terminal, funnel the output to a file and then return it to the nimbus node.
Firstly, how would i code an individual computer to run ls in the terminal? Funneling the output to a file is simple enough for me to figure out. I just don't know how to write programs that execute terminal commands.
Secondly, how do i tell each of my supervisor nodes to run ls individually?
You can use below snippet to run a command in shell. So use this same method to invoke the specific ls command using ssh in all supervisor nodes (from external node like nimbus).
public String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
Hope this helped.
Im facing this strange issue of not being able to execute a simple "whoami" unix command on a AIX server. I have a webapplication that is deployed on an AIX server. Now I want to see under which WAS user my webapplication is currently running. So I added the below code:
public String whoami() throws Exception {
Process p = Runtime.getRuntime().exec("whoami");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
String output = "";
while ((line = in.readLine()) != null) {
//System.out.println(line);
output += line;
}
in.close();
p.destroy();
return output;
}
}
The above code is added in a jar file which is referred by a JSP. The JSP has to receive the output of the code above and it displays the WAS User name. But when i deploy the webapplication on the server and try to observe the output, im getting an error message like
Error 500: access denied (java.io.FilePermission <> execute)
However, When I remove the above code and run my webapplication, everything runs fine. What wron am i doing here. Did I miss doing anything? Please help. This is the first time im working on UNIX
It looks like your web server has been configured with a Java security policy that prohibits executing external applications.
See http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html for information about Java Security Policies, and the documentation for your web server.
You will need to supply (or edit) a policy file to contain something like:
grant {
permission java.io.FilePermission
"/usr/bin/whoami", "execute";
};
Just out of curiosity
Have you considered to use:
user.name
System property in Java?
AFAIK whoami is a shell command and Runtime#exec() executes programs only.
you can try Runtime.getRuntime().exec(new String[]{"sh","-c","whoami"}) to call sh and let it execute whoami
another thing: do you need to destroy the process after reading?
You can use the ProcessBuilder class instead of getRuntime().exec("whoami").
Here is sample code
import java.io.*;
import java.util.*;
public class DoProcessBuilder {
public static void main(String args[]) throws IOException {
if (args.length <= 0) {
System.err.println("Need command to run");
System.exit(-1);
}
Process process = new ProcessBuilder(args).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}