Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

ZooKeeper node name sanitization

By: a guest on Jul 6th, 2012  |  syntax: Java  |  size: 1.44 KB  |  hits: 33  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }