Search code examples
javaspringldapspring-ldap

Missing attributes with Spring LDAP object-directory mapper annotations


I am trying to use Spring LDAP's object-directory mapping to write an object to an LDAP server. The object is annotated with @Entity and several fields are annotated with @Attribute.

As long as all of the annotated fields are populated, everything works. But if the value of a field, say myattribute, is null or an empty string, the create and update methods of LdapTemplate throw errors. The server rejects the operation, with the complaint "Attribute value '' for attribute 'myattribute' is syntactically incorrect"

The LDAP schema permits 'myattribute' to be missing (it is a "may" attribute for the relevant objectclass), but if it is present, it is not permitted to be blank (it has Directory String syntax). I cannot change the schema.

Is there some way to get Spring LDAP to omit 'myattribute' when the corresponding POJO field is null or empty, rather than attempting to create the attribute with a blank value?


Solution

  • I have found a solution, which may not be the most elegant for my application, but it works. Instead of declaring the Java field to be type String, declare it to be type List. Then, in the setter, if the value is blank or null, I set the list length to zero instead of setting a single empty value.

    @Entry( objectClasses={"myObject"} )
    public class MyDataContainer {
    
        @Attribute("myattribute")
        private List<String> _myattribute = new ArrayList<String>(1);
    
        public String getMyAttribute() {
            if ( _myattribute.length() > 0 ) {
                return _myattribute.get(0);
            }
            return null;
        }
    
        public void setMyAttribute( String value ) {
            _myattribute.clear();
            value = ( value == null ) ? "" : value.trim();
            if ( ! "".equals( value ) ) {
                _myattribute.add( value );
            }
        }
    }