Cant get Jna to recognize and set registry

43 Views Asked by At

So essentially I am trying to read the data from registry to keep a persistent variable in case my Java program crashes which runs 7-8 hours a day

import com.sun.jna.platform.win32.Advapi32;
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.WinReg;
import com.sun.jna.platform.win32.WinReg.HKEY;
import com.sun.jna.platform.win32.WinReg.HKEYByReference;

//Sets the data within registry in case of crash
try {
Advapi32Util.registrySetIntValue(WinReg.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Control\\Session Manager\\Environment", "Tracked Counters", counter);
} catch(Throwable e) {
    return null;
}

try {
int counter = Advapi32Util.registryGetIntValue(WinReg.HKEY_LOCAL_MACHINE,           "System\\CurrentControlSet\\Control\\Session Manager\\Environment", "Tracked counters");
} catch(Throwable e) {
    return null;
}

I can't figure out why it's not working. I have tried giving it admin access. I also tried setting the environment variable via Current_User and forgoing admin rights. I am not familar with Java

I expected the counter in the registry to enumerate as the script ran instead the value stayed at 0

1

There are 1 best solutions below

0
Bobby Singer On

So I used a different method to solve the issue. Not sure why it wasn't working I suspect since the script itself is ancient and is made to run with Java 1.7. I would have preferred to write to environment variables so I could hook in the data into another script rather than reading the Javasoft key but for now, I have settled on using preferences.

import java.util.prefs.*;

//runs at the top of script set default to 0 if reboot
runcounter = Preferences.userNodeForPackage(xxx.class).getInt("Counter Number", 0);

//runs after counter
runcounter = runcounter +1;
Preferences.userNodeForPackage(xxx.class).putInt("Counter Number",  runcounter);