Advertisement
Guest User

ZooKeeper node name sanitization

a guest
Jul 6th, 2012
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. /**
  2.  * Usually returns a resource name that adheres to the ZooKeeper naming rules. There are some cases that are purposefully not
  3.  * caught by this method. For example, the token "zookeeper" and unicode characters greater then 16 bits in size.
  4.  *
  5.  * @param resource
  6.  * @return
  7.  */
  8. public static String normalize(String resource) {
  9.   if (resource.equals(".")) {
  10.     return "\\x2e";
  11.   }
  12.   if (resource.equals("..")) {
  13.     return "\\x2e\\x2e";
  14.   }
  15.   char[] oldChars = resource.toCharArray();
  16.   char[] newChars = new char[oldChars.length * 6];
  17.   int i = 0;
  18.   for (char oldChar : oldChars) {
  19.     if (oldChar != '/'
  20.         && (0x19 < oldChar && oldChar < 0x7F || 0x9F < oldChar && oldChar < 0xd800 || 0xF8FF < oldChar && oldChar < 0xFFF0)) {
  21.       newChars[i] = oldChar;
  22.       i++;
  23.     } else {
  24.       newChars[i] = '\\';
  25.       newChars[i + 1] = 'x';
  26.       String hexValue = Integer.toHexString(oldChar);
  27.       hexValue.getChars(0, hexValue.length(), newChars, i + 2);
  28.       i += 2 + hexValue.length();
  29.     }
  30.   }
  31.   return new String(newChars, 0, i);
  32. }
  33.  
  34. /**
  35.  * Returns the xsd:hexBinary representation of the given string.
  36.  */
  37. public static String convertStringToHex(String string) {
  38.   return DatatypeConverter.printHexBinary(string.getBytes());
  39. }
  40.  
  41. /**
  42.  * Returns the string represented by the xsd:hexBinary input.
  43.  */
  44. public static String convertHexToString(String hex) {
  45.   return new String(DatatypeConverter.parseHexBinary(hex));
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement