Portable Device Path on Windows - java

I've actually got an Windows/Java Question. I've got a plugged-in device which I want to access via Java. Normally you can access an e.g. USB-Stick via the Drive letter... but this tablet is displayed by Windows as a "Portable Device"... which means, that the Path is something like "Computer\Archos 5S" and there is no Drive letter.
I want to access a file on this device via Java, but I am not able to figure out the correct path to it. There is a similar question out there, but without a productive answer. Or is there another way to access this device via Java?
Actually I've not solved this problem... I am still not able to access such a device via java.
At the moment I am trying to access a windows ShellFolder in Java.
A Shellfolder like: "Shell:::{35786D3C-B075-49b9-88DD-029876E11C01}"
Is this possible with Java?
Recently I uncovered the sun.awt class "ShellFolder"... is this the wanted feature?
thanks for your help
Ripei

The solution to above problem using JMTP library on https://code.google.com/p/jmtp/
Here is my code
package jmtp;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.Guid;
import java.io.*;
import java.math.BigInteger;
import jmtp.PortableDevice;
import jmtp.*;
public class Jmtp {
public static void main(String[] args) {
PortableDeviceManager manager = new PortableDeviceManager();
PortableDevice device = manager.getDevices()[0];
// Connect to my mp3-player
device.open();
System.out.println(device.getModel());
System.out.println("---------------");
// Iterate over deviceObjects
for (PortableDeviceObject object : device.getRootObjects()) {
// If the object is a storage object
if (object instanceof PortableDeviceStorageObject) {
PortableDeviceStorageObject storage = (PortableDeviceStorageObject) object;
for (PortableDeviceObject o2 : storage.getChildObjects()) {
//
// BigInteger bigInteger1 = new BigInteger("123456789");
// File file = new File("c:/JavaAppletSigningGuide.pdf");
// try {
// storage.addAudioObject(file, "jj", "jj", bigInteger1);
// } catch (Exception e) {
// //System.out.println("Exception e = " + e);
// }
//
System.out.println(o2.getOriginalFileName());
}
}
}
manager.getDevices()[0].close();
}
}
Do not forget add jmtp.dll files (that comes up with jmtp download) as a native library. For more info, see my answer on Including Native Library in Netbeans.

Like *nix systems, all devices (including drives) have paths that are part of a common root, this is normally hidden from users because they use the drive letters which are aliases to these fundamental paths, but you can also use full device paths by prefixing the path with "\\.\"
For instance, on my machine D: translates as "\Device\HarddiskVolume1" and can be accessed by passing "\\.\HarddiskVolume1" to CreateFile.
So the path to your device is probably "\\.\Archos 5s".

you can always download and install the Windows mobile developer Powertoys (http://www.microsoft.com/download/en/details.aspx?id=10601) and copy from and to the device using the command line utility cecopy, which you can run from any programming language. There are other options there too, but it's most targeted at .Net

Related

Can we open shared drive on client machine using java web application?

My java web application is deployed on server machine. I have a share drive which is accessible from client machine as well as server machine . Using below code i am able to open that drive on server machine :
Spring Controller code :
#RequestMapping(value = "/openAttachment", method = RequestMethod.POST)
public ResponseEntity<List<String>>
OpenFolder(#RequestParam("workflowName") String workflowName ) throws
IOException, InterruptedException {
String folderPath =Constants.workFlowAttachPath+workflowName;
if ((new File(folderPath)).exists()) {
Process p = Runtime
.getRuntime()
.exec("rundll32 url.dll,FileProtocolHandler "+folderPath);
p.waitFor();
}
List<String> msgList = new ArrayList<> ();
msgList.add(Constants.SUCCESSFUL);
return new ResponseEntity<List<String>>(msgList, HttpStatus.OK);
}
Constant used here is :
public static final String workFlowAttachPath="\\\\10.82.31.27\\Area20\\Attachment\\";
But i am unable to open this folder from local machine(browser) on local machine .
Is this possible ? If possible then how ? Thanks in advance.
No, you can't do that. If you're okay with hardcoding windows and system state into your code, you can mount that folder on a drive letter, say, drive 'N:', and then use path:
psf String workFlowAttachPath = "N:\\Attachment\\";
you can mount this on windows with something like:
net use N: \\\\10.82.31.27\\Area20 /PERSISTENT:YES
but I'm just going off of memory on that one so you'd have to check the docs on the net use windows command for the details. You should be able to invoke 'net.exe' via Runtime.getRuntime().exec() but I advise against that. You're already hardcoding IPs and who knows what in this code, might as well take care of mounting the N: drive externally too. This avoids having to deal with errors from the net command from within your java code, which is notoriously hard; windows likes to translate its commands and can throw quite a few weird errors, writing code to invoke windows utilities from java and understand their outputs is a non-trivial job.

How to crash my OS programatically?

Have written a Java code which sends mail when whole system RAM reaches > 95%.
I want to write a Java code to test this scenario. Have written few(recursive etc...), but those are crashing the JVM but not System.
Any help please ?
UN_ORTHODOX SOLUTION but it works anyway
NOTE! I Used WINDOWS 8.1 host machine
I found this DOC on myself too! in old days; about JVM and host system access issues. I used this code to get details about host system!
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
private static void printUsage() {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("get")
&& Modifier.isPublic(method.getModifiers())) {
Object value;
try {
value = method.invoke(operatingSystemMXBean);
} catch (Exception e) {
value = e;
} // try
System.out.println(method.getName() + " = " + value);
} // if
} // for
}
NOTE !
that's not the real way To do but I did it by opening the Default browser (in most of cases I know most of the time its GOOGLE CHROME) , had 8GB ram those days so opening a few tabs with some random youtube and other links it helped me to reach up the memory usage unto 90% in no time! because it eats the RAM (No offence to CHROME people!) doing that I was able to achieve the test you are trying to get. :-)
TO Open a default browser just take a look on this thread its quite nice with different ways to do it!
well if you are using it for android well read about proguard rules for memory management and try using any external library which takes up too much memory like any dummy faceRecog library or simply just accessing some NDK features or so check this link for more

Reading subfolders within the registry (JAVA)

I'm busy creating a program that will read parts of the registry to find out what USB devices have been connected to a windows system etc... I've managed to create a piece of software what will display the values, however each person's registry will hold different information.
I've tried looking everywhere to find help/guidence with code to be able to scan a registry folder and display the subfolders within it. I know there is plenty of code for reading ordinary file locations however none will work with attempting to read the registry.
The folder location I am trying to read is:
"\"HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR\
I've managed to create a program which will read the values from the above location however I have to manualy specify each subfolder into the code.
I hope i've explained what i need, sorry if it's confusing
Thanks in advance
I've used jRegistryKey.dll jRegistryKey.jar
Here you go
ftp://ftp.heanet.ie/mirrors/sourceforge/j/project/jr/jregistrykey/manual/original/jreg_key.pdf
e.g. code:
import ca.beq.util.win32.registry.RegistryKey;
import ca.beq.util.win32.registry.RegistryValue;
import ca.beq.util.win32.registry.RootKey;
enumeration from example ---
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software");
if(r.hasSubkeys()) {
Iterator i = r.subkeys();
while(i.hasNext()) {
RegistryKey x = (RegistryKey)i.next();
System.out.println(x.toString());
} // while
} // if
RegistryKey r = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE, "Software\\app\\update\\Date");
if (r.hasValue("LastSuccessfulUpdate")) {
RegistryValue v = r.getValue("LastSuccessfulUpdate");
updateDate = v.getStringValue();
Date now = new Date(Long.parseLong(updateDate.trim() + "000"));
................
}

Java: load shared libraries with dependencies

I am wrapping a shared library (written in C) with Java using JNA. The shared library is written internally, but that library uses functions from another external library, which again depends another external library. So the situation is something like this:
ext1 <- ext2 <- internal
I.e. the internal uses external library ext2 which again uses external library ext1. What I have tried is:
System.loadLibrary("ext1");
System.loadLibrary("ext2");
NativeLIbrary.loadLibrary("internal",xxx.class);
This approach fails with "UnresolvedException" when loading the library "ext2"; the linker complains about symbols which are indeed present in the library "ext1". So it semmes that the System.loadLibrary() function does not make the symbols from "ext1" globally available? When using the stdlib function dlopen() as:
handle = dlopen( lib_name , RTLD_GLOBAL );
All the symbols found in #lib_name will be available for symbol resolution in subsequent loads; I guess what I would like was something similar for the java variety System.loadLibrary()?
Regards - Joakim Hove
It's an old question, but I've found an acceptable solution, which should also be portable, and I thought I should post an answer. The solution is to use JNA's NativeLibrary#getInstance(), because on Linux this will pass RTLD_GLOBAL to dlopen() (and on Windows this is not needed).
Now, if you are using this library to implement a Java native method, you will also need to call System.load() (or Sysem.loadLibrary()) on the same library, after calling NativeLibrary#getInstance().
First, a link to a JNA bug: JNA-61
A comment in there says that basically one should load dependencies before the actual library to use from within JNA, not the standard Java way. I'll just copy-paste my code, it's a typical scenario:
String libPath =
"/path/to/my/lib:" + // My library file
"/usr/local/lib:" + // Libraries lept and tesseract
System.getProperty("java.library.path");
System.setProperty("jna.library.path", libPath);
NativeLibrary.getInstance("lept");
NativeLibrary.getInstance("tesseract");
OcrTesseractInterf ocrInstance = (OcrTesseractInterf)
Native.loadLibrary(OcrTesseractInterf.JNA_LIBRARY_NAME, OcrTesseractInterf.class);
I've written a small library to provide OCR capability to my Java app using Tesseract. Tesseract dependes on Leptonica, so to use my library, I need to load libraries lept and tesseract first. Loading the libraries with the standard means (System.load() and System.loadLibrary()) doesn't do the trick, neither does setting properties jna.library.path or java.library.path. Obviously, JNA likes to load libraries its own way.
This works for me in Linux, I guess if one sets the proper library path, this should work in other OSs as well.
There is yet another solution for that. You can dlopen directly inside JNI code, like this:
void loadLibrary() {
if(handle == NULL) {
handle = dlopen("libname.so", RTLD_LAZY | RTLD_GLOBAL);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
}
}
...
...
loadLibrary();
This way, you will open library with RTLD_GLOBAL.
You can find detailed description here: http://www.owsiak.org/?p=3640
OK;
I have found an acceptable solution in the end, but not without significant amount of hoops. What I do is
Use the normal JNA mechanism to map the dlopen() function from the dynamic linking library (libdl.so).
Use the dlopen() function mapped in with JNA to load external libraries "ext1" and "ext2" with the option RTLD_GLOBAL set.
It actually seems to work :-)
As described at http://www.owsiak.org/?p=3640, an easy but crude solution on Linux is to use LD_PRELOAD.
If that's not acceptable, then I'd recommend the answer by Oo.oO: dlopen the library with RTLD_GLOBAL within JNI code.
Try this, add this function to your code. Call it before you load your dlls. For the parameter, use the location of your dlls.
public boolean addDllLocationToPath(String dllLocation)
{
try
{
System.setProperty("java.library.path", System.getProperty("java.library.path") + ";" + dllLocation);
Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
fieldSysPath.setAccessible(true);
fieldSysPath.set(null, null);
}
catch (Exception e)
{
System.err.println("Could not modify path");
return false;
}
return true;
}
}
In order to fix your issue you can use this package: https://github.com/victor-paltz/global-load-library. It loads the libraries directly with the RTLD_GLOBAL flag.
Here is an example:
import com.globalload.LibraryLoaderJNI;
public class HelloWorldJNI {
static {
// Loaded with RTLD_GLOBAL flag
try {
LibraryLoaderJNI.loadLibrary("/path/to/my_native_lib_A");
} catch (UnsatisfiedLinkError e) {
System.Println("Couldn't load my_native_lib_A");
System.Println(e.getMessage());
e.printStackTrace();
}
// Not loaded with RTLD_GLOBAL flag
try {
System.load("/path/to/my_native_lib_B");
} catch (UnsatisfiedLinkError e) {
System.Println("Couldn't load my_native_lib_B");
System.Println(e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
new HelloWorldJNI().sayHello();
}
private native void sayHello();
}
It is using the same dlopen() trick as the previous answers, but it is packaged in a standalone code.

Getting hosts file location in Java

How can I get the location of the hosts file when using my application on different platforms?
think that you would have to roll your own here I'm afraid, as this is a pretty low level system function, I think that it's a little beyond what you could expect java to do for you.
This link points to some special options that you can set to alter the bind order, I don't think that they will tell you where the hosts file is, but you could could investigate in and around these options to see if you can find anything else to help you
You could use the "os.name" system property to determine the operating system. Then, retrieve the hosts file depending on where each operating system stores it. For example:
String osName = System.getProperty("os.name").toLowerCase();
File hostsFile;
if (osName.startsWith("mac os x")){
hostFile = new File("/etc/hosts");
} else if (osName.contains("windows")){
hostFile = //...
}
Take a look at the hosts file locations for each operating system and version on Wikipedia. Unfortunately you will have to implement your own logic similar to Michael's answer:
import java.awt.Desktop;
import java.io.File;
public class HostsFile
{
public static void main(String[] args) throws Exception
{
String osName = System.getProperty("os.name");
File hostsFile = null;
if (osName.contains("Windows"))
{
hostsFile = new File(System.getenv("WinDir")
+ "\\system32\\drivers\\etc\\hosts");
}
Desktop.getDesktop().open(hostsFile);
}
}

Categories