title: Reading and saving binary image from OpenLDAP server using Groovy
body: <p>I'm trying to save an image from an OpenLDAP server. It's in binary format and all my code appears to work, however, the image is corrupted.</p>
  
  <p>I then attempted to do this in PHP and was successful, but I'd like to do it in a Grails project.</p>
  
  <p><strong>PHP Example (works)</strong></p>
  
  <pre><code>&lt;?php
      $conn = ldap_connect('ldap.example.com') or die("Could not connect.\n");
      ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
      $dn = 'ou=People,o=Acme';
      $ldap_rs = ldap_bind($conn) or die("Can't bind to LDAP");
      $res = ldap_search($conn,$dn,"someID=123456789");
      $info = ldap_get_entries($conn, $res);
      $entry = ldap_first_entry($conn, $res);
      $jpeg_data = ldap_get_values_len( $conn, $entry, "someimage-jpeg");
      $jpeg_filename = '/tmp/' . basename( tempnam ('.', 'djp') );
      $outjpeg = fopen($jpeg_filename, "wb");
      fwrite($outjpeg, $jpeg_data[0]);
      fclose ($outjpeg);
      copy ($jpeg_filename, '/some/dir/test.jpg');
      unlink($jpeg_filename);
  ?&gt;
  </code></pre>
  
  <p><strong>Groovy Example (does not work)</strong></p>
  
  <pre><code>def ldap = org.apache.directory.groovyldap.LDAP.newInstance('ldap://ldap.example.com/ou=People,o=Acme')
  
  ldap.eachEntry (filter: 'someID=123456789') { entry -&gt;
  
      new File('/Some/dir/123456789.jpg').withOutputStream {
          it.write entry.get('someimage-jpeg').getBytes()  // File is created, but image is corrupted (size also doesn't match the PHP version)
      }
  
  }
  </code></pre>
  
  <p>How would I tell the Apache LDAP library that "image-jpeg" is actually binary and not a String? Is there a better simple library available to read binary data from an LDAP server? From looking at the Apache mailing list, <a href="http://mail-archives.apache.org/mod_mbox/directory-api/201105.mbox/%3CBANLkTinHeEihSqcpP92A57D7+OcN_HaNtA@mail.gmail.com%3E" rel="nofollow">someone else had a similar issue</a>, but I couldn't find a resolution in the thread.</p>
  
  <p><strong>Technology Stack</strong></p>
  
  <ul>
  <li>Grails 2.2.1 </li>
  <li><a href="http://directory.apache.org/api/groovy-ldap.html" rel="nofollow">Apache LDAP API 1.0.0 M16</a></li>
  </ul>