code: public static String sanitize(final String input)
      {
          if ( input == null )
          {
              return "";
          }
  
          String s = "";
  
          for ( int i = 0; i < input.length(); i++ )
          {
  
              char c = input.charAt(i);
  
              if ( c == '*' )
              {
                  // escape asterisk
                  s += "\\2a";
              }
              else if ( c == '(' )
              {
                  // escape left parenthesis
                  s += "\\28";
              }
              else if ( c == ')' )
              {
                  // escape right parenthesis
                  s += "\\29";
              }
              else if ( c == '\\' )
              {
                  // escape backslash
                  s += "\\5c";
              }
              else if ( c == '\u0000' )
              {
                  // escape NULL char
                  s += "\\00";
              }
              else if ( c <= 0x7f )
              {
                  // regular 1-byte UTF-8 char
                  s += String.valueOf(c);
              }
              else if ( c >= 0x080 )
              {
  
                  // higher-order 2, 3 and 4-byte UTF-8 chars
  
                  try
                  {
                      byte[] utf8bytes = String.valueOf(c).getBytes("UTF8");
  
                      for ( byte b : utf8bytes )
                      {
                          s += String.format("\\%02x", b);
                      }
  
                  }
                  catch ( UnsupportedEncodingException e )
                  {
                      // ignore
                  }
              }
          }
  
          return s;
      }
docs: Escapes any special chars (RFC 4515) from a string representing a
  a search filter assertion value.
  
  @param input The input string.
  @return A assertion value string ready for insertion into a
  search filter string.