Need to run .jar from console for it to work - java

I have a java application.
I'm using eclipse to write, compile and create a runnable .jar.
The program is used to discover OCF devices.
It uses UDP and multicast.
Multicast code
public static void sendMulticast(byte[] data) throws Exception{
DatagramPacket pack = new DatagramPacket(data, data.length, mgroup, mport);
msocket.send(pack);
}
public static byte[] recieveMulticast(int timeout) throws Exception{
DatagramPacket packet;
byte[] data = new byte[AppConfig.ocf_buffer_size];
packet = new DatagramPacket(data, data.length);
msocket.setSoTimeout(timeout);
msocket.receive(packet);
return data;
}
The code works when I start it from eclipse. It also works when I run the .jar from console on Linux.
But when I start it with a double click, it doesn't work.
When started from console, it finds my test device in less then a second. When started with a double click it doesn't find it ever.
I haven't tested it on Windows yet, but the problem remains on Linux all the same.
What is the difference when you start .jar from console or by double clicking?
Why is it effecting messages on multicast?
I'm using "Package required libraries into generated JAR".
I'm using java 1.7 in eclipse, and 1.8 on Linux, maybe thats the problem? But why does running it from console work?
I would understand if I used sudo, but I didn't.

When you are running any jar from console, Console/Terminal knows which program responsible to run the any jar i.e
java -jar example.jar
but when double-clicking environment, OS/GUI manager doesn't know default responsible program to run the jar. ( Same way when you try to open some unknown extension file, Operating system will ask you open with which program/application)
To make Java open .jar files per default (i.e. double click) right click on any .jar file to select Properties. In the following window select the "Open With" tab to see e.g. the follwing choice:

The problem was in current location, system property
user.dir
This is the first function I call in my main. It doesn't work from eclipse, so I'll put an argument for disabling it (it will be disabled only during development).
static void setCurrentDir() throws URISyntaxException{
String s;
s = ESP8266_Configurator.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
s = s.substring(0, s.lastIndexOf('/'));
System.setProperty("user.dir",s);
}
I hope this helps someone. Code should be exported with extracted libraries, not packaged, otherwise it doesn't work.

Related

Running shell script on tomcat7

I have been breaking my head for two days trying to fix the file permissions for my tomcat7 server. I have a library class (.jar file included in myapp/WEB-INF) which needs to run a shell script. The library is written by me and works fine within NetBeans ie. no hassle in creating,reading and deleting files. That is because NetBeans runs the program as blumonkey(my username on my Ubuntu System). But when I import this into tomcat and run it, tomcat "executes" the command, produces no definite output, tries to check for a file(which will be generated when the script succeeds) and throws a FileNotFoundException.
More Details as follows:
Tomcat7 installed using apt-get, has its data in 2 locations - /var/lib/tomcat7 with conf and webapps folders and /usr/share/tomcat7 with the bin and lib folders
The user uploads a .zip file which is stores to /home/blumonkey/data. Rest of the program runs on the documents stored here. All new folders/files uploaded by tomcat have, obviously, tomcat7 as the owner.
I have tried things like changing the ownership to blumonkey, adding tomcat7 to blumonkey user group but none of the methods worked (Somewhere around here I probably messed up changing permissions carelessly :/ ). Apparently tomcat7 is unable to process on the files it owns.(How can this be?).
The script works when I run it in the terminal. But it doesn't work when I do a sudo -u tomcat7 script.sh, ie run it as tomcat7. It just exits with no message. I doubt that this it what is happening as I have tried to debug by redirecting the errors and outputs in ProcessBuilder but they came empty.
Any help regarding how to fix the issue and get the script running would be greatly appreciated. Please comment if you need any more info.
The code for script execution
private static void RunShellCommandFromJava(String command,String fn, String arg1,String arg2) throws Exception
{
try
{
System.out.println(System.getProperty("user.name"));
ProcessBuilder pbuilder = new ProcessBuilder("/bin/bash",command,fn,arg1,arg2);
System.out.println(pbuilder.command());
pbuilder.redirectErrorStream(true);
Process p = pbuilder.start();
p.waitFor();
}
catch(Exception ie)
{
throw ie;
}
}
The command which needs to be executed
"/bin/bash /abs/path/to/script.sh /abs/path/to/doc/in/data-folder maxpages=30 maxsearches=3"
PS : I have followed this question but it didn't help. I also tried other options like Runtime.exec(), bash,/bin/bash/ and /bin/bash/ -c, some of them don't work at all, others give no results.
Try to use Runtime and check standard error to find out what was the problem (probably permissions or paths):
// run command
String[] fixCmd = new String[] { "/bin/bash", "/abs/path/to/script.sh", "/abs/path/to/doc/in/data-folder", "maxpages=30", "maxsearches=3" };
Process start = Runtime.getRuntime().exec(fixCmd);
// monitor standard error to find out what's wrong
BufferedReader r = new BufferedReader(new InputStreamReader(start.getErrorStream()));
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}

Access denied when trying to execute a .exe in %AppData%

I'm trying to use RemoveDrive.exe, found here, in my Java application. I have it in my JAR, and I'm extracting it to a temporary file using the following code, however when I try to run it I get an IOException which says CreateProcess error=5, Access is denied. The program doesn't normally need admin priviledges though. Any ideas on what could be causing the issue?
File RDexe = File.createTempFile("rmvd", ".exe");
InputStream exesrc = (InputStream) GraphicUI.class.getResource("RemoveDrive.exe").openStream();
FileOutputStream out = new FileOutputStream(RDexe);
byte[] temp = new byte[1024];
int rc;
while((rc = exesrc.read(temp)) > 0)
out.write(temp, 0, rc);
exesrc.close();
out.close();
RDexe.deleteOnExit();
// run executable
Runtime runtime = Runtime.getRuntime();
System.out.println(RDexe.getPath() + " " + "F:\\" + " -b -s");
Process proc = runtime.exec(RDexe.getPath() + " " + "F:\\" + " -b");
InputStream is = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line; boolean ejected = false;
while((line = reader.readLine()) != null)
if(line.equalsIgnoreCase("failed")) ejected = false;
else if(line.equalsIgnoreCase("success")) ejected = true;
reader.close();
is.close();
UPDATE: If I enable the built-in Administrator account (net user administrator /active:yes), everything works fine from there. However if I right click and run as administrator in my standard account, I still get the error and UAC doesn't even ask for permission.
EDIT: Seeing as though the bounty is nearly finished, please see my SuperUser question which has helped me solve this problem... I'll be awarding the bounty and accepting an answer soon.
This may not be the problem in your situation, but some anti-virus programs will prevent executables or scripts inside temporary folders from being run. Instead of creating a temporary file, try putting it in the user directory:
File rdExe = new File(System.getProperty("user.home") + "/.yourProgramName/rmvd.exe");
rdExe.getParentFile().mkdirs();
just a heads up on another way to run files, have you thought of using the java Desktop object? : http://docs.oracle.com/javase/6/docs/api/java/awt/Desktop.html
i've found it useful when needing to run programs through my java program. something like this could work for you:
Desktop.getDesktop().open(new File("enter path and name of the file"));
hope you find it useful
I am not JAVA user but isn't it 32 vs. 64 bit issue ?
On 64 bit Windows error code 5 usually means that executable is not 64 bit compatible. Sometimes this is the case even when executable need to access only some (older win) system directory which does not exist anymore. To prove this try to use your executable in command line. if you can manage to get it work there than it is different issue. If not find executable for your OS.
Another possibility is that the file has to be physically present on some drive.
You wrote that you has it as temporary. Not shore what it means for JAVA. If it only copy it to some file and delete after use than its OK but if it is only in memory somewhere than that could be problem if executable need access to itself. To prove this just copy the file to some known location and then run it from there (in JAVA). if it works than you will need to do something about it (copy and delete executable from JAVA before and after execution to physical disk medium or whatever)
Another possibility is that error code 5 comes from JAVA environment an not from OS
In that case I have not a clue what it means (not JAVA user)
Seeing as though it has only been touched on here, I will say that the issue was related to permissions in Windows, and is not anything to do with Java.
As stated in the SuperUser question I've linked to in my original question, I found that my usual account did not have ownership of that folder for some unknown reason - so nothing could be executed; it wasn't just the temporary file I had created in Java.
Even though I am an administrator, in order to take ownership of the folder I had to enable the Built-In administrator account and grant myself ownership. Since I did that, it has all worked as expected.
Thanks to all for their efforts, I will award the bounty to the answer that was most detailed and put me on the right tracks.
What version of Windows are you running? Microsoft significantly tightened the restrictions around executing programs in Windows 7. My guess is that it the OS won't allow you to fork something that wasn't authenticated at the time your program was launched. I'd try running it on Windows 2000 or XP and see if you have the same issues.

new Rengine(...); fails without error

I'm trying to set up JRI with Eclipse on a Windows 7 x64 system. I tried it once on my Laptop and it worked. Now on my Desktop it fails although everything of the R, rJava and JRI installation is exactly the same.
I set the JRI and R Paths correctly to:
C:\Program Files\R\R-2.15.1\library\rJava\jri;C:\Program Files\R\R-2.15.1\bin\x64
Also I set R_DOC_DIR etc in Eclipse.
Every time I try to run new Rengine(...); it fails without any error or exception. Debugging revealed an: <terminated, exit value: 10>C:\Program Files\Java\jre6\bin\javaw.exe (01.10.2012 18:00:31)
Is there anything I can try? It really bothers me that it works an my Laptop but not on my Workstation despite the same settings everywhere.
Edit: The code that is used to get the Rengine object.
public static Rengine getRengine(){
if (re == null) createRengine();
return re;
}
public static void createRengine(){
if (re!=null) return;
try{
if (!Rengine.versionCheck()) {
System.err.println("** Version mismatch **");
System.exit(1);
}
String[] arguments = {"--save"};
re=new Rengine(arguments, false, null);
if (!re.waitForR()) {
System.out.println("Cannot load R");
return;
}
}
catch (Exception e){
e.printStackTrace();
}
}
Edit: The last time i tried it i got an errormessage (creating of the REngine worked, this happened never before), R was missing a registryentry. After installing R 2.15.1 again it suddenly worked. Now after a restart it's the same like before. The program crashes at the creation of the REngine.
I was having the exact same problem. It turns out I had unchecked the box that asks to make a registry entry with the R version number. Once I let the installer run with that box checked, it seemed to work.
I would make sure your regedit looks like this:
Next up: getting this working in a portable way...
I am using R 3.2.2 and eclipse Mars on Windows 10 x64.
I faced the described issue today and tried around a bit. Finally, I found the root cause in the build path. Please check whether the following conditions are fulfilled:
1.) The following Java libraries from the JIRI folder on your hard disk shall be included as (user) libraries:
JIRI.jar
REngine.jar
JRIEngine.jar
2.) The native library jiri.dll is located in the subfolder "i386" for x86, whereas for x64 it is available in the subfolder "x64". The relevant one shall be added as separate native library location to the Java Build Path of the eclipse project. Otherwise, the file may not be considered as it is not located in the main JIRI folder.
Best regards
Philipp

Reading File in J2ME

I became so much upset with this simple code segment:
FileConnection fc = (FileConnection) Connector.open("file:///root1/photos/2.png");
System.out.println(is.available());
byte[] fileBytes = new byte[is.available()];
int sizef = is.read(fileBytes);
System.out.println("filesize:"+sizef);
When I deploy this midlet in my mobile (with proper file location) It works properly i.e it shows proper filesize, but in the pc emulator it is constantly giving filesize of: 0. Obviously no Exception and I have the proper file in that location.
I am using j2mewtk sdk in netbeans 6.9. I tried uninstalling, installing wtk & netbeans.
Another thing is Everytime I run the emulator it creates C:\Users\Mahsruf\j2mewtk\2.5.2\appdb\temp.DefaultColorPhone6 new location like temp.DefaultColorPhone1,2,3,4 etc.
If I use jme SDK 3.0 in netbeans the file size is still 0, but now with a extra line in output window: [WARN] [rms ] javacall_file_open: _wopen failed for: C:\Users\Mahsruf\javame-sdk\3.0\work\0\appdb\_delete_notify.dat
What am I doing wrong?
This is not coding related issue. If multiple instances of the same emulator skin run simultaneously, the toolkit generates unique file paths for each one. For example, on Windows instances of DefaultColorPhone might have a file path name of workdir\appdb\temp.DefaultColorPhone1, workdir\appdb\temp.DefaultColorPhone2, and so forth.
Solution: The file workdir\appdb\DefaultColorPhone\in.use keeps track of the number of storage roots marked as in use. If the emulator crashes, you need to delete the in.use file

How to run a Mac application From Java?

I tried the code below to run a stand-alone utility app I created from Apple script but, I get a No File or Directory Exists error.
I put identical copies (for testing) in the project, dist, parent directories but, it didn't help.
So, my questions are:
Is my call to run the app bad (perhaps because it's not a Windows exe)?
How to run a mac app from java?
Thanks
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Runtime r=Runtime.getRuntime();
Process p=null;
String s="MyLineInInput.app";
try {
p = r.exec(s);
} catch (IOException ex) {
Logger.getLogger(AudioSwitcherView.class.getName()).log(Level.SEVERE, null, ex);
}
}
A Mac App Bunde is not an executable file, it's a folder with a special structure. It can be opened using the open command, passing the App Bundle path as an argument: open MyLineInInput.app.
EDIT:
Even better would be using Desktop.getDesktop().open(new File("MyLineInInput.app"));
I used the Runtime.getRuntime().exec() method with the open command mentioned in the selected answer. I didn't use Desktop.getDesktop().open() since it unwantedly opened a terminal in my case and I didn't want to create an extra File object.
Process process = Runtime.getRuntime().exec("open /System/Applications/Books.app");
Reason for adding '/System':
It seems we need to use the /System prefix for System apps. For user-installed apps, that's not required, and it can be like /Applications/Appium.app.
To answer #Pantelis Sopasakis' issue that I also faced initially -
I get the error message: java.lang.IllegalArgumentException: The file: >/Applications/Microsoft Office 2011/Microsoft\ Excel.app doesn't exist.
In this case, it could be simply due to not escaping the space characters in the path.
Environment: JDK 11 Zulu - macOS Monterey 12.2.1 - M1 Silicon

Categories