/**
* Usually returns a resource name that adheres to the ZooKeeper naming rules. There are some cases that are purposefully not
* caught by this method. For example, the token "zookeeper" and unicode characters greater then 16 bits in size.
*
* @param resource
* @return
*/
public static String normalize(String resource) {
if (resource.equals(".")) {
return "\\x2e";
}
if (resource.equals("..")) {
return "\\x2e\\x2e";
}
char[] oldChars = resource.toCharArray();
char[] newChars = new char[oldChars.length * 6];
int i = 0;
for (char oldChar : oldChars) {
if (oldChar != '/'
&& (0x19 < oldChar && oldChar < 0x7F || 0x9F < oldChar && oldChar < 0xd800 || 0xF8FF < oldChar && oldChar < 0xFFF0)) {
newChars[i] = oldChar;
i++;
} else {
newChars[i] = '\\';
newChars[i + 1] = 'x';
String hexValue = Integer.toHexString(oldChar);
hexValue.getChars(0, hexValue.length(), newChars, i + 2);
i += 2 + hexValue.length();
}
}
return new String(newChars, 0, i);
}
/**
* Returns the xsd:hexBinary representation of the given string.
*/
public static String convertStringToHex(String string) {
return DatatypeConverter.printHexBinary(string.getBytes());
}
/**
* Returns the string represented by the xsd:hexBinary input.
*/
public static String convertHexToString(String hex) {
return new String(DatatypeConverter.parseHexBinary(hex));
}