code: public String escapeDN(String name) {
          StringBuilder sb = new StringBuilder();
          if ((name.length() > 0) && ((name.charAt(0) == ' ') || (name.charAt(0) == '#'))) {
              sb.append('\\'); // add the leading backslash if needed
          }
          for (int i = 0; i < name.length(); i++) {
              char curChar = name.charAt(i);
              switch (curChar) {
                  case '\\':
                      sb.append("\\\\");
                      break;
                  case ',':
                      sb.append("\\,");
                      break;
                  case '+':
                      sb.append("\\+");
                      break;
                  case '"':
                      sb.append("\\\"");
                      break;
                  case '<':
                      sb.append("\\<");
                      break;
                  case '>':
                      sb.append("\\>");
                      break;
                  case ';':
                      sb.append("\\;");
                      break;
                  default:
                      sb.append(curChar);
              }
          }
          if ((name.length() > 1) && (name.charAt(name.length() - 1) == ' ')) {
              sb.insert(sb.length() - 1, '\\'); // add the trailing backslash if needed
          }
          return sb.toString();
      }
docs: Escapes the given string such that it is safe for use within an LDAP
  distinguished name (DN). This implementation is provided courtesy of
  OWASP:
  
  https://www.owasp.org/index.php/Preventing_LDAP_Injection_in_Java
  
  @param name
  The string to escape such that it has no special meaning within an
  LDAP DN.
  
  @return
  The escaped string, safe for use within an LDAP DN.