Are there any limitations in launching an executable JAR from a VBA script using shell(...)
My jar effectivly gets some IDs from the VBA script as launch arguments, queries values from a web service and displays them using JOptionPane.ShowMessageDialog
Here is my code:
private static JFrame quotenframe = new JFrame();
public static void main(String args[]){
if(args.length < 3){
JOptionPane.showMessageDialog(quotenframe, "Not enough parameters!", "Error", JOptionPane.ERROR_MESSAGE);
closeAll(1);
}
if(args[0].split("#").length<2){
JOptionPane.showMessageDialog(quotenframe, "Invalid value! '#' missing", "Error", JOptionPane.ERROR_MESSAGE);
closeAll(1);
}
String var1 = args[0].split("#")[0];
String var2 = args[0].split("#")[1];
String var3 = args[1];
String var4 = args[2];
String result = "";
// Build resultString
JOptionPane.showMessageDialog(quotenframe, result);
closeAll(0);
}
The JAR itselfs executes without a problem when launched from a windows cmd shell, but when that same command line is run from the Shell(...) command in my VBA script, the only reaction is a java icon visible for a split second in the task bar, which then disappears.
My command is:
java -jar jarFolder\myjar.jar param1 param2 param3
and the execution directory is one level ontop of jarFolder.
It seems to me, that the JAR crashes upon launch, but, I cannot see why, as that same JAR, in the same directory, launched with the same command from a Windows shell works well.
Can it have anything to do with the JOptionPane? If not, any idea what the error could be?
The solution is, that you need to specify the full path to the jar, when invoking it using VBA's Shell(...) command, if the JAR is in a subfolder.
Related
I have compiled a jar file. Here is the code:
package javaProject;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
System.out.println("Enter something >>> ");
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());
scanner.close();
}
}
Here is my Apple Script script:
do shell script "java -jar /Users/Harry/Desktop/appleScript.app/Contents/javaProject.jar"
Nothing is printed in the console, and the scanner object doesn't ask for my input at any point, but the JFrame is created. Can anyone explain why this is the case? Thanks.
do shell script doesn't run with/in a console, the result (or error) is just returned to the script. If you are wanting to interact or view progress, the script can be run in something that does provide a console, such as the Terminal (which is scriptable). Note that a new window/tab will be created each time you run a script, unless you specify something different - for example, the following script will always use the first tab of the first window:
tell application "Terminal"
activate
try
do script "echo 'This is a test.' " in tab 1 of window 1
on error errmess -- no window
log errmess
do script "echo 'This is a test.' "
end try
end tell
I'm trying to run a java command in cmd using C# to get some inputs for my program, the path for Java is set correctly, and I am able to run Java commands in the cmd without any trouble but when I tried it in C#, it's showing " 'java' is not recognized as an internal or external command, operable program or batch file. " as if the path is not set.
But I am able to run the same command outside, don't know what seems to be the issue, kindly help, thanks in advance!
string cmd = #"/c java -jar """ + $"{treeEditDistanceDataFolder}libs" + $#"\RTED_v1.1.jar"" -f ""{f1}"" ""{f2}"" -c 1 1 1 -s heavy --switch -m";
Console.WriteLine(cmd);
var proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = cmd;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
Console.WriteLine("Process started");
string output = proc.StandardOutput.ReadToEnd();
Console.WriteLine("Output was read");
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();
This line is your problem:
proc.StartInfo.UseShellExecute = false;
When UseShellExecute is true, the system and user PATH variables will be used if the application to launch is just the executable name. Because you're setting it to false, and java doesn't exist in your application's folder, it isn't possible for .NET to find it.
You have two options:
Set UseShellExecute to true so that it can use the PATH variable to find java.
Use a fully qualified path, e.g. "C:\Program Files\Java\jdk1.8.0_101\bin\java"
See this answer for more info.
This question already has answers here:
Eclipse command line arguments
(4 answers)
Closed 5 years ago.
In my CS class we use the terminal to run our codes, using the javac to cimpile and java to run.
In my current assignment I'm receiving inputs from a file. The name of the file is given when inputing the command in the CMD (terminal) like this:
"java -cp mypath\class text.txt"
using this code:
if (args.length != 1) {
final String msg = "Usage: EmployeePay name_of_input file";
System.err.println(msg);
throw new IllegalArgumentException(msg);
}
final String inputFileName = args[0];
final File input = new File (inputFileName);
final Scanner in = new Scanner (input);
When running this with Eclipse, it throws the Exception. Is there a way in eclipse to do this command "java -cp mypath\class text.txt" without changing or adding anything to the code itself?
Go to Run/Run configurations..., then select your "run instance" in the left, then select the Arguments tab and finally enter your text.txt into the Program arguments field. Click Apply and repeat that for the other "run instances" if any.
You may click Run if you want to run your project, but do not forget tto click Apply beforehand...
I wanted to find out how to create an executable .jar file, so I wrote a small sample program to test it. This sample program takes some default text and turns it into some code based on the Caesar code. Anyway, it outputs normally when run in Eclipse.
I doubt this helps, but here's the source code for the two java classes.
Main.java
public class Main {
public static void main (String [] args){
Caesar caesarCode = new Caesar();
caesarCode.setDecodedText("this");
caesarCode.setShiftPos(3);
String cipherText = caesarCode.deencode(caesarCode.getDecodedText(), caesarCode.getShiftPos());
System.out.print(cipherText+"\n");
String plainText = caesarCode.deencode(cipherText, caesarCode.getShiftPos()*-1);
System.out.print(plainText);
}
}
Caesar.java
public class Caesar {
// global variables
String encodedText; // encoded text
String decodedText; // decoded text
int shiftPos; // shift positions to decode message
// getters and setters
public String getEncodedText() {
return encodedText;
}
public void setEncodedText(String encodedText) {
this.encodedText = encodedText;
}
public String getDecodedText() {
return decodedText;
}
public void setDecodedText(String decodedText) {
this.decodedText = decodedText;
}
public int getShiftPos() {
return shiftPos;
}
public void setShiftPos(int shiftPos) {
this.shiftPos = shiftPos;
}
public String deencode (String plainTextArg, int shiftPosArg) {
// variables
String plainText = plainTextArg;
char[] cipherTextArray;
String cipherText;
int plainTextSize;
int shiftPos = shiftPosArg;
// initialize variables
char[] plainTextArray = plainText.toCharArray();
plainTextSize = plainTextArray.length;
cipherTextArray = new char[plainTextSize];
// shift cipher String by shiftPos
for (int i = 0; i < plainTextSize; i++){
cipherTextArray[i] = (char) (plainTextArray[i] + shiftPos);
}
cipherText = String.valueOf(cipherTextArray);
// return cipher text
return cipherText;
}
}
I created my .jar file this way (on a Mac):
Created two directories on Desktop: "classes" and "source"
Copied my two files (Caesar.java, Main.java) into the source folder.
I compiled the files into .class files in the classes directory with the command "javac -d ../classes *.java"
I created a manifest.txt file with the line "Main-Class: Main", and saved it as "manifest.txt" in the classes directory.
I then created the .jar file with this command "jar -cvmf manifest.txt main.jar *.class".
The main.jar file was created successfully.
The problem is, when I ran it, nothing happened - no warnings, no popups, no error messages.
I'm thinking that it has something to do with the fact that it outputs to the terminal, but I can't wrap my head around it. I've also looked at many threads on this forum and others, but can't seem to see the problem. I'm going to experiment to see if it works for a GUI application in the meanwhile.
Greatly appreciate your help on this, thanks!
I'm thinking that it has something to do with the fact that it outputs to the terminal
If you want to see console output from your program then you will have to run it in the Terminal with java -jar main.jar. If you double click the JAR in the Finder or use the open command then it will run but any output will go to the system console log rather than being displayed directly. You can show system console messages by running syslog -C.
In Windows, press Windows+R to invoke "Run..." dialog. Type cmd there and hit Enter. The Command Prompt window will appear (it's black).
At the prompt type cd %USERPROFILE%\Desktop\classes and hit Enter.
Then type command as suggested above: java -jar main.jar
It is possible to create executable jars from within eclipse if you want to.
Right click on your project -> Export -> Java -> Runnable JAR file.
Note that You might need to run your jar file from the command line using java -jar <jarFile> to see System.out.println() and error messages.
I have a shell script that I want to execute in Eclipse from a Java code.
I am able to use external tools in order to run the script, but I want the script to run during the execution of the Java code i.e. the Java code should make a call to the script.
Earlier I was using the "Process Builder" to do so but it seems Eclipse does not support that method as it says "File not found" when I have given it all the permissions.
Any idea how to run the script from a Java code in Eclipse?
Here is the code:
String line1 = null;
String target = new String("/home/aditya_s/workspace/rs-test/src/iperf_parse.sh " + host + " " + "9000");
while(line1 == null)
{
Process p1 = Runtime.getRuntime().exec(target);
BufferedReader input1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
System.out.println("Ran");
line1 = input1.readLine();
p1.destroy();
}
BW = Double.parseDouble(line1);
TIP: Right click on the shell script and go to Properties. There give the 'Read/Write/Execute' permissions to 'Owner'. By default, the 'Execute' permission is not there. So you might get an error like 'Could not execute script.sh'.
Eclipse runs your java program just as it normally would, so ProcessBuilder will work as well. It is possible that you passed in the wrong path. If the path is relative, it will be relative to System.getProperty("user.dir").
You should be able to use the below, replace shellscript with the script you want to run.
String s = "shellscript";
Process proc = Runtime.getRuntime().exec(s);
You should look at ProcessBuilder