Reading and Writing LDAP Results

Ldaptive provides implementations for formatting LDAP results in LDIF and JSON.

LDIF

LDIF can be written to any java.io.Writer using an LdifWriter.

StringWriter writer = new StringWriter();
LdifWriter ldifWriter = new LdifWriter(writer);
SearchOperation search = new SearchOperation(new DefaultConnectionFactory("ldap://directory.ldaptive.org"));
SearchResponse response = search.execute(SearchRequest.builder()
  .dn("dc=ldaptive,dc=org")
  .filter("(uid=dfisher)")
  .returnAttributes("mail")
  .build());
ldifWriter.write(response);
System.out.println(writer.toString());

produces:

dn: uid=dfisher,ou=people,dc=ldaptive,dc=org
mail: dfisher@ldaptive.org

LDIF can be read using any java.io.Reader using an LdifReader.

FileReader reader = new FileReader("entry.ldif");
LdifReader ldifReader = new LdifReader(reader);
SearchResponse response = ldifReader.read();

JSON

JSON support is provided in a separate library that uses GSON. This support is provided in a separate library that is available in the jars directory of the latest download.

Or included as a maven dependency:

<dependencies>
  <dependency>
    <groupId>org.ldaptive</groupId>
    <artifactId>ldaptive-json</artifactId>
    <version>2.0.1</version>
  </dependency>
</dependencies>

JSON can be written to any java.io.Writer using a JsonWriter.

StringWriter writer = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(writer);
SearchOperation search = new SearchOperation(new DefaultConnectionFactory("ldap://directory.ldaptive.org"));
SearchResponse response = search.execute(SearchRequest.builder()
  .dn("dc=ldaptive,dc=org")
  .filter("(uid=dfisher)")
  .returnAttributes("mail")
  .build());
jsonWriter.write(response);
System.out.println(writer.toString());

produces:

[{"dn":"uid=dfisher,ou=people,dc=ldaptive,dc=org","mail":["dfisher@ldaptive.org"]}]

JSON can be read using any java.io.Reader using a JsonReader.

FileReader reader = new FileReader("entry.json");
JsonReader jsonReader = new JsonReader(reader);
SearchResponse response = jsonReader.read();