Running a .jar file displaying output/parsing commands - java

I am wanting to run a .jar file and display the output (I'm assuming I would use a rich text box) however I also want to have a text box that will allow me to send commands to the running jar file as if it were running in a command prompt window.
Either this or embedding the command prompt would be ideal. I have messed around with code and have never got it to work.
I would also like to detect certain messages that the jar file returns, for example if a certain command is ran it will display a message depending on whether or not that failed, is there a way to read everything that get returned and then have an event happen if it detects this certain string?
How To: Execute command line in C#, get STD OUT results I have been looking at things such as that, when I say I have messed around with code, I have tried the code given in these examples (changing small parts) they never worked.
To summarise:
- I want to run a jar file that obviously displays it's output in a command prompt.
- I want to hide the command prompt and display it's output in a rich text box.
- The jar file will return string such as 'user 1 has logged in' I want to update a labels text everytime that happens.

You should have a look at the ProcessBuilder and Process classes. They allow to run command line programs and read/write in the process streams.
Also, if your jar is known in advance, why no simply using the class as if it would be in a library and use the exposed APIs?

When we started learning java at school we used
String myInput = JOptionPane.showInputDialog(this, "myPrompt");
and
JOptionPane.showMessageDialog(null, "A basic JOptionPane message dialog");
for input and output. Very simple.
Or you can use the command-line:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)
String input = br.readLine();

Related

How do you write to a command prompt in Java?

Background
I started a command prompt from a Java application. Now I want to input commands into the command prompt that was just generated. How can you run commands in the prompt that was just generated by the Java program?
What I've tried
My code creates a process that starts the command prompt. And then it gets the process's OutputStream to try and write to it. But I don't see any changes happening. It should just change directories and then run a series of commands in the new directory.
// Block that makes new command prompt
List<String> commands = new ArrayList<String>();
commands.add("cmd.exe");
commands.add("/c");
commands.add("start");
commands.add("cmd.exe");
// Block that creates a writer to write to new command prompt
ProcessBuilder pb = new ProcessBuilder(commands);
Process p = pb.start();
OutputStream os = p.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
// Block that actually writes the commands
writer.write(String.format("cd %s\n", PATH);
writer.write(OTHER_COMMANDS); // I'm ommiting the other commands because there's a lot
writer.flush();
writer.close();
I'm unsure why the commands aren't written to the command prompt that pops up. I see that a new command prompt pops up, but the directory is unchanged from where it starts. How can I input commands into the prompt that I generate?
When you're writing to p, you're writing to this command's standard input:
cmd.exe /c start cmd.exe
You're writing to the first cmd.exe. Which does not do anything except start the second one. It is not possible (at least not simple) to get a handle to the second process. You can use /K, and merge the commands with && after each other. For example:
commands.add("/K");
commands.add(String.join(" && ", OTHER_COMMANDS_AS_LIST));
Your program ProcessBuilder gives you access to the stdin, stdout, and stderr of the process cmd.exe. Those are not the same things as the input and the output of a window and command prompt opened up by the program cmd.exe
There is an answer here regarding how to do it with c#: Create a cmd window and write to it from C# application
In Java I am not aware of a similar API, it might actually require using JNI or JNA in order to gain access to the Windows APIs you would need to use. The function you use (through JNI or JNA) would be the same https://learn.microsoft.com/en-us/windows/console/allocconsole referenced in that other answer. So that is one way to do it, but a full description of how to use either JNI or JNA is outside the scope of an answer here, should you choose to go that route.
As far as I can see, you're trying to implement something vaguely similar to a remote shell (SSH without network and without encryption)...
This should work like you expect for a *nix-like shell, because those shells handle their standard input and output correctly, precisely for the case that they need to be redirected (over a network, or whatever).
The Windows cmd.exe is actually not a pure shell. It is a terminal emulator (the black window that appears on the screen) and the shell, in one process. That's why it doesn't get its input from stdin, and doesn't print its output on stdout. Instead, it listens to GUI keyboard events for input and handles them internally, and the output is displayed directly in the window, without writing it to stdout.
That's why there is no easy way to "remote control" a cmd.exe. It's just not made for that.
You can try this with "proper" shells, like a Cygwin'ed bash.exe, or maybe PowerShell, or similar.
It's actually astonishing that the cmd.exe which was created as a quick'n'dirty "DOS window" some 20 years ago, is still surviving to this day and is actually used for production work...

Can someone without JDK run a program that uses the console for i/o (and has no other user interface or display)?

Essentially the question boils down to 'Is there a way to run a class/jar file using the console for input/output without having JDK'. I've written a program in Java for a colleague to use in his work, but he doesn't have/use JDK. I'm aware there are online compilers, but at this point my question has become focused on running a program directly for interest reasons.
Essentially the program is designed to output instructions to the user, the
user makes input in accordance with the instructions, and this goes back and forth for awhile before the program does some calculations based off the input and returns a final result.
I should mention that he has JRE.
My program doesn't use a GUI, it just prints instructions to the console and gathers input from responses typed in the console. It works fine on my computer when running it from the command line ('java myprogram'), but without jdk the java command isn't available to him, which seems to mean he can't run a class file.
My next attempt was to turn the program into an executable jar file, but using the command 'myprogram.jar' from the command line doesn't really do anything. The jar file does include a manifest. I added a blank screen to the code and running the jar file did create the screen, but still no i/o on the console. From what I've read, I think this is because jar files aren't automatically associated with a console, so there is nowhere for the program's output to go or input to come from. He can't use the 'java -jar myprogram.jar' command because he hasn't got the JDK, so even though that command runs the program the way I want it to, it's not an option.
Basically, I'm wondering if it's possible for someone without JDK to run a program and interact with it entirely using the console/command line and no other interface?

JSch executing multiple linux commands in one session

I'm working on a project in which I intend to make a Java GUI application that connects to a ssh server and executes remote commands on the server. I'm willing to use JSch Library. My aim is to make buttons and textfields those will provide the user the ability of sending commands and getting replies easily. I mean, instead of opening xShell and prompting "grep "hi" /usr/file.txt", the user will choose the path from the list and will enter "hi" into the textfield and will press the button for grep.
Problem is, I couldn't find a solution to execute multiple linux commands in one session (I don't want shell if i cannot redirect its input and output streams) (also I don't want the solution "cd.. \n dir \n ls -l" which works fine but not solving my problem) send the arguments those shall be taken from related GUI components.
Since I have not made so much modifications on the JSch's example code, yet, you can see the code here: http://www.jcraft.com/jsch/examples/Exec.java.html
Thanks from now on.
If using exec type of channel you can combine commands with && :
channel.setCommand(". ./.profile && env");

Auto-input 'y' when prompted in command-line from Java

The program I'm using runs through the command prompt from java using a batch file (following the solutions from Run .exe file from Java from file location, and at one point of time, it will prompt the user for an input which is either a 'y' or 'n' in order to continue the program.
How do I program using java codes such that the value 'y' or 'n' is automatically entered when prompted, without requiring users to enter it manually? I have tried using pipe (following the solutions from How do you enter something at a DOS prompt Programmatically?) but it doesn't work. Any ideas?
Grab the InputStream from the Process and write the y into it.
Look at this questions for example code:
Java Process with Input/Output Stream
Reading streams from java Runtime.exec
You can do it the old DOS way.
Create a file, say yes.txt. All it should have is y (as per your app expectations). The file can contain responses to multiple prompts each on their own lines
Now you can execute your exe file something like this
myApp.exe < yes.txt
When exe prompts, yes.txt will supply the prompt text

How to run an .exe and capture the output in an Eclipse Plugin. (Java) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Capturing stdout when calling Runtime.exec
Ok so,
I am developing an Eclipse plugin that generates some PHP code based a visual interface (i.e. the user drags and drops some stuff on a View and then my plugin will update some php files with the code associated)
I am creating the php files with FileUtils (Apache Commons) and I am generating the PHP code using an ASTParser.
My problem is that I need my freshly generated code to be beautified and nicely indented. I have googled around and found this http://www.waterproof.fr/products/phpCodeBeautifier/ . It comes as a .exe file. I have added it to resources but I'm having some trouble calling it and getting the output from it.
How can I do this? Also I have to say that I need it to work on both a Mac and a Windows machine. Can this be done? Is there an easier way to beautify the code?
Thanks!
If you can run it from command line and pass file path to beautify the code you can use following code to run it and capture the result.
Process p = Runtime.getRuntime().exec("executable.exec");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((String line = input.readLine()) != null) {
System.out.println(line);
}
see also :
How to capture the data returned from an EXE excuted from a batch?
How can i get the console output generated by a exe file?
Capturing stdout when calling Runtime.exec
I would do it as follows:
Resolve the location of the exe in an OS independent manner.
Create a Process using `Runtime.getRuntime().exec('exe_location');
Take the process.getOutputStream() and print the unformatted code into it which means the exe would read the text to be formatted on STDIN.
Take the process.getInputStream() and read out the formatted code from it which means the exe would print the formatted output on to STDOUT.
Close the streams and end the process.

Categories

Resources