title: Parse ldap filter to escape special characters
body: <p>An ejb service takes a ldap filter as string and returns a result from ActiveDirectory.
  <br><br>The problem is that sometimes attribute values contain special characters that need to be escaped for the entire filter as specified here:
  <br><a href="https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx</a>
  <br>and for distinguished name attibute values as specified here:
  <br><a href="https://msdn.microsoft.com/en-us/library/aa366101(v=vs.85).aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/aa366101(v=vs.85).aspx</a>
  <br>In order to accomplish this the service must do the following:</p>
  
  <ol>
  <li>Analyze the string for dn values, separate them and escape them as per dn escape rules if they are not already escaped.</li>
  <li>Search the remainder of the string for special characters in attribute values and escape them as per general filter escape rules if they are not already escaped.</li>
  <li>Combine the results as the new escaped filter and pass it on.</li>
  </ol>
  
  <p>Java native <code>javax.naming.ldap.Rdn</code> escapes dn values all right but is not idempotent. As for the other tasks, so far I have been unable to find a library that would allow me to accomplish them.
  <br><br>Right now I am inclined to think that the job of escaping the ldap filter should be done by the user of the service rather than by the service itself as it is very hard for the service to tell escapes from actual values. Also, parsing a complex string such as a ldap filter without a well tested library seems to me error prone.
  <br><br>Any ideas on how to solve this? Can this task be automated at all?</p>