Question

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.

I then attempted to do this in PHP and was successful, but I'd like to do it in a Grails project.

PHP Example (works)

<?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);
?>

Groovy Example (does not work)

def ldap = org.apache.directory.groovyldap.LDAP.newInstance('ldap://ldap.example.com/ou=People,o=Acme')

ldap.eachEntry (filter: 'someID=123456789') { entry ->

    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)
    }

}

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, someone else had a similar issue, but I couldn't find a resolution in the thread.

Technology Stack

Was it helpful?

Solution 2

I found the answer. The Apache Groovy LDAP library uses JNDI under the hood. When using JNDI certain entries are automatically read as binary, but if your LDAP server uses a custom name, the library will not know that it's binary.

For those people that come across this problem using Grails, here's the steps to set a specific entry to binary format.

  • Create a new properties file call "jndi.properties" and add it to your grails-app/conf directory (all property files in this folder are automatically included in the classpath)

  • Add a line in the properties file with the name of the image variable:

    java.naming.ldap.attributes.binary=some_custom_image

  • Save the file and run the Grails application

Here is some sample code to save a binary entry to a file.

def ldap = LDAP.newInstance('ldap://some.server.com/ou=People,o=Acme')      
ldap.eachEntry (filter: 'id=1234567') { entry ->             
    new File('/var/dir/something.jpg').withOutputStream {          
        it.write entry.image          
    }         
}

OTHER TIPS

Have you checked whether the image attribute value is base-64 encoded?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top