Reading File in J2ME - java

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

Related

Get File Version of .exe in java on Linux

Question - Get File Version of .exe in java on Linux for some strange client.
Solution -
I used JNA library to read file version using Java. Given below code is running fine on windows platform but it is throwing below error on Linux docker image.
"Unable to load library 'version': Error loading shared library libversion.so: No such file or directory Error loading shared library libversion.so: No such file or directory Native library (linux-x86-64/libversion.so) not found in resource path..".
private String GetFileVersion(String filePath) {
File fileToCheck = new File(filePath);
short[] rtnData = new short[4];
int infoSize = Version.INSTANCE.GetFileVersionInfoSize(fileToCheck.getAbsolutePath(), null);
Pointer buffer = Kernel32.INSTANCE.LocalAlloc(WinBase.LMEM_ZEROINIT, infoSize);
try {
Version.INSTANCE.GetFileVersionInfo(fileToCheck.getAbsolutePath(), 0, infoSize, buffer);
IntByReference outputSize = new IntByReference();
PointerByReference pointer = new PointerByReference();
Version.INSTANCE.VerQueryValue(buffer, "\\", pointer, outputSize);
VerRsrc.VS_FIXEDFILEINFO fileInfoStructure = new VerRsrc.VS_FIXEDFILEINFO(pointer.getValue());
rtnData[0] = (short) (fileInfoStructure.dwFileVersionMS.longValue() >> 16);
rtnData[1] = (short) (fileInfoStructure.dwFileVersionMS.longValue() & 0xffff);
rtnData[2] = (short) (fileInfoStructure.dwFileVersionLS.longValue() >> 16);
rtnData[3] = (short) (fileInfoStructure.dwFileVersionLS.longValue() & 0xffff);
return String.format("%s.%s.%s.%s", rtnData[0], rtnData[1], rtnData[2], rtnData[3]);
} catch (Exception exception) {
return null;
} finally {
Kernel32.INSTANCE.GlobalFree(buffer);
}
}
I will start by answering the question that you asked, though I doubt it is what you actually need to know.
The types of different executable file formats are encoded in the first few bytes of the file. For example, ELF files (executables, shared libraries) are described in this Wikipedia page.
So there are a number of ways to find out what kind of executable in Java:
Write some code that reads the first few bytes and decodes the file header information, as per the format described in the Wikipedia link above.
Find an existing Java library that does this and work out how to do this. (Google for "java file magic library" and see what you can find.)
Read about the Linux file command and write some Java code to run file on each library and parse the output.
What I think you actually need to do is a bit different:
Locate the file or files in the file system that the Java is looking for: apparently libversion.so or linux-x86-64/libversion.so. (The file could well be a symlink. Follow it.)
Run file on each file to check that it is the right kind of library. They need to be 32 or 64 bit corresponding the JVM you are running, and the correct ABI and ISA for the platform.
Check that the files are where the JVM expects to find them. The JVM searches for libraries in directories listed in the "java.library.path" system property. You can (if necessary) set the path using a -Djava.library.path=... JVM option.
See "java.library.path – What is it and how to use" for more information on library loading.
(There is absolutely no need to do step 2 "from" or "in" Java.)
I think I have finally worked out what you are doing.
The Version you are using is actually coming from the package com.sun.jna.platform.win32. It is not part of the JNA library (jna.jar). I think it is actually part of jna-platform.jar. If I understand things correctly, that is the generated JNA adapter library for the Windows COM dlls.
If I have that correct, you would actually need the Windows COM native libraries compiled and built for the Linux platform to do what you are trying to do.
AFAIK, that's not possible.
So how could you make this work? Basically you need to do one of the following:
Look for an existing pure Java library for extracting the version information from a Windows ".exe" file. I don't think it is likely that you will find one.
Find the specification for the Windows ".exe" file format and write your own Java code to extract the version information. I haven't looked for the spec to see how much work it would be.
Then you rewrite the code that you added your question to use the alternative API.
The "libversion" file that I mentioned in my other answer is not relevant. It is something else. It is a red herring.

Issue with the name of cache directory in Android

In my app I am saving temporary files to my app cache folder. I am getting the name of the cache directory via this method:
context.getCacheDir();
It returns me such path: /data/user/0/my.app.packagename
But later when I am trying to get name of parent directory of my cache file via this method - file.getParent(); I am getting absolutely different path to cache directory, in my case this: /data/data/my.app-packagename
So I am just wondering why this is happening, why getParent() doesn't return the same path as context.getCacheDir()?
The behaviour is correct, technically its the same.
If you connect to your android device via adb shell and go into /data/user/ and run the 'll' command you will see that the folder 0 is just a symbolic link to /data/data/.
root#android:/data/user # ll
lrwxrwxrwx root root 1970-01-01 01:00 0 -> /data/data/
If you dont know what that means, read up on symbolic links.
So there is no issue and you can trust android that they are the same.
This behavior confused me a lot today.
Here are my 50 Cent to bring light into this:
I've started an Emulator with Android 8.1
I've connected my Android 9 Device via USB
After that I've started Android-Studio and opend the Device File Explorer.
Now strange things happend:
On Android 8.1 you see the structure /data/user/0/com.myApp/
on Android 9 there is no directory /data/user (and no symbolic link visible via android-studio)
BUT, internally the path seems to be the same (even if there is no symbolic Link visible in android studio).
I use RNFetchBlob (React native package to read files), and if I output the Result from RNFetchBlob.fs.dirs.CacheDir the result was /data/user/0/.... even if on Android 9 this Directory not exist.
But I'd gave it a try and output all files that will be found at this Directory with the following Command :
RNFetchBlob.fs.ls(RNFetchBlob.fs.dirs.CacheDir)
.then((files) => {
console.log("output-files",files);
})
...and found that this output all the files I've cached before.
If anybody knows some documentation why this behavior exist up from Android 9, please comment and point us to this.

Azure : Image Magick gives 0kb output?

I have integrated Image magick with a Java WebApp and have deployed it on Azure App Service. On azure , I am getting 0kb as output image for a image while the same image gets converted fine on my local machine.
I am using im4java for integration with Image Magick.
Below is the code:
public void compressImage(String imageSource, String destinationPath) throws IOException, InterruptedException,
IM4JavaException {
ConvertCmd cmd = getCommand();
// create the operation, add images and operators/options
IMOperation op = new IMOperation();
op.strip();
op.interlace();
op.addRawArgs(compressionRawArguments);
op.gaussianBlur(compressionGaussianBlur);
op.quality(compressedImageQuality);
op.addImage(imageSource); // source file
op.addImage(destinationPath); // destination file
// execute the operation
cmd.run(op);
}
Both imageSource and destination are temp files created using java. I have checked that imageSource file has correct size but after running this code, the destination file is always 0 Kb.
Please advise what could I be doing wrong?
Answering my own question so that It might be helpful for fellow developers who might face this problem.
Azure App Service normally has Windows Server VMs. You can check the OS of your server in web container logs.
Image Magick for windows does not allow conversion of remote http
image urls while for Unix System, it allows so. My Local machine is
MAC So it was working correctly on my local system.
2 Solutions to this problem that I found:
Either you use a linux VM on Azure
In your application, download the image URL to a temp file and
supply the absolute path of that temp file to image magick for
conversion.
I have tried both and are both working.

Using nsis to package application installer and .wav file does not play because of a path on Windows containing a space --> Program%20Files

I'm running into an issue that involves an audioInputStream, a resource folder, and nsis for a Windows installation. I'm working on an app (in Linux) that performs a desktop notification when an event occurs and everything works except for the .wav file that is supposed to play when the notification pops up. I have tested the app on a 64 bit Windows machine without installing it via nsis and it works perfectly. I received an error message indicating:
07/08/13 12:17:26 ERROR [Thread-2] (DesktopNotifierMessageAlertHandler.java:73) com.alcatel.proserv.e911.desktopNotifierMessaging.desktopNotifierMessageHandler.DesktopNotifierMessageAlertHandler - Error: java.io.FileNotFoundException: C:\Program%20Files\Alcatel-Lucent\E911DesktopNotifier\classes\audio\siren.wav (Le chemin d'accès spécifié est introuvable)
I'm working in Netbeans and using maven to build. Here is a code snippet of how I'm loading the path:
String filename = this.getClass().getResource("/audio/siren.wav").getPath();
AudioInputStream audioInputStream = null;
try{
audioInputStream = AudioSystem.getAudioInputStream(new File(filename).getAbsoluteFile());
Clip clip = null;
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}
...
I found this blog detailing how to fix an extremely similar issue:
http://braintwitter.blogspot.ro/2013/03/url-encoding-issue-with-tomcat.html
but it didn't work out with the audioInputStream I'm working with.
I know it's a problem with the space in "Program Files" which is where I have to set up the installation to occur because when I changed the InstallDir value in the setup.nsi script from $PROGRAMFILES64 to $WINDIR, it worked perfectly.
Does anyone have any suggestions for how I can modify my code to work properly since the space in Program Files is causing an encoding issue?
getResource() returns a URL, and it has URL encoding applied here. You have two options. You can convert to a URI:
String filename = this.getClass().getResource("/audio/siren.wav").toURI().getPath();
Or you can use URLDecoder to decode the path before passing it along to your AudioInputStream:
String filename = this.getClass().getResource("/audio/siren.wav").getPath();
filename = URLDecoder.decode(filename, "utf-8");
See the blurb at the end of the intro section for java.net.URL.
so I know this is pretty old thread, but anyone reading this, think twice, as the nsis packager creates this malware as scanned on virus total on a pc that's been run with malwarebytes, avira, roguekiller, hitman pro and stinger.
Antiy-AVL - Trojan/Generic.ASMalwS.3506C16, Avast-Win64:Malware-gen, AVG - Win64:Malware-gen, Cyren - W64/Tedy.B.gen!Eldorado, Jiangmin -Trojan.PSW.Python.fv, Zillya -Trojan.Disco.Script.653

Deployment in tomcat

i am getting a problem
i have deployed a war file, when i run localy through tomcat it works fine but when i run on another system by giveing my system ip and then project folder e.g
http:\192.168.0.145\DllTest it loads the applet but when i click on a button to load the functionality it is throwing an exception
Exception in thread "AWT-EventQueue-3" java.lang.UnsatisfiedLinkError: Expecting an absolute path of the library: http:\192.168.0.145:8080\DllTest\lib\jinvoke.dll
while it is working fine localy but not in another system. Please tell me what is the problem.
Is it a rights issue or something else.
You cannot load a DLL on an external host. It has to be an absolute disk file system -as the exception message already hints. Your best bet is to download it manually, create a temp file and load it instead.
File dllFile = File.createTempFile("jinvoke", ".dll");
InputStream input = new URL(getCodeBase(), "lib/jinvoke.dll").openStream();
OuptutStream output = new FileOutputStream(dllFile);
// Write input to output and close streams the usual Java IO way.
// Then load it using absolute disk file system path.
System.loadLibrary(dllFile.getAbsolutePath());
dllFile.deleteOnExit();

Categories