package au.net.causal.projo.prefs.windows;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import au.net.causal.projo.prefs.PreferencesException;
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.WinReg.HKEY;
public final class RegistryUtils
{
public static final String NODE_SEPARATOR = "\\";
private RegistryUtils()
{
//Private constructor to prevent instantiation
}
public static void createKeyPath(HKEY root, String path)
throws PreferencesException
{
if (root == null)
throw new NullPointerException("root == null");
if (path == null)
throw new NullPointerException("path == null");
String[] segments = path.split(Pattern.quote(NODE_SEPARATOR));
String parentPath = "";
String curPath = "";
for (String segment : segments)
{
if (!curPath.isEmpty())
{
parentPath = curPath;
curPath = curPath + NODE_SEPARATOR;
}
curPath = curPath + segment;
if (!Advapi32Util.registryKeyExists(root, curPath))
{
boolean created = Advapi32Util.registryCreateKey(root, parentPath, segment);
if (!created)
throw new PreferencesException("Failed to create registry key " + root + NODE_SEPARATOR + parentPath + NODE_SEPARATOR + segment);
}
}
}
public static void deleteKeyWithChildren(HKEY root, String path)
{
if (root == null)
throw new NullPointerException("root == null");
if (path == null)
throw new NullPointerException("path == null");
//If key does not exist, then no delete needed
if (!Advapi32Util.registryKeyExists(root, path))
return;
//Scan for children and delete those first
String[] children = Advapi32Util.registryGetKeys(root, path);
for (String child : children)
{
deleteKeyWithChildren(root, path + NODE_SEPARATOR + child);
}
//Now delete the key itself
String parentPath = StringUtils.substringBeforeLast(path, NODE_SEPARATOR);
String mySegment = StringUtils.substringAfterLast(path, NODE_SEPARATOR);
Advapi32Util.registryDeleteKey(root, parentPath, mySegment);
}
}