0

Is there an (easy) way to specify default values for LDAPField annotated variables? For example, I don't want the list myNumericAttr to be null if no values were found but instead would like it to hold an empty list.

import com.unboundid.ldap.sdk.persist.LDAPField;
import com.unboundid.ldap.sdk.persist.LDAPObject;

@LDAPObject(structuralClass="myStructuralClass")
public class MyObject
{
    @LDAPField(attribute="myStringAttr")
    private String myStringAttr;

    @LDAPField(attribute="myNumericAttr")
    private List<Long> myNumericAttr;
}

As a workaround I could implement a postDecodeMethod myself but that would result in a lot of code.

@SuppressWarnings("unused")
private void doPostDecode() throws LDAPPersistException, IllegalArgumentException, IllegalAccessException
{
    for (Field field : this.getClass().getDeclaredFields())
    {
        if(field.isAnnotationPresent(LDAPField.class))
        {
            // check if field value is null
            if (field.get(this) == null)
            {
                String fieldType = field.getType().getName();
                log.info("field type: {}", fieldType);
                if (fieldType.equals("java.lang.String"))
                {
                    field.set(this, "");
                }
                else if (fieldType.equals("java.util.List"))
                {
                    // Find out the type of list we are dealing with
                    ParameterizedType listGenericType = (ParameterizedType) field.getGenericType();
                    Class<?> listActualType = (Class<?>) listGenericType.getActualTypeArguments()[0];
                    log.debug("actual type of list: {}", listActualType.getName());
                    field.set(this, getModel(listActualType));
                }
            }
        }
    }
}

private <T> ArrayList<T> getModel(Class<T> type) {
    ArrayList<T> arrayList = new ArrayList<T>();
    return arrayList;
}

So my question is, did I miss some feature or is implementing your own postDecodeMethod the only possibility at the moment?

jansohn
  • 2,246
  • 2
  • 28
  • 40

1 Answers1

1

Take a look at the defaultDecodeValue element of the @LDAPField annotation type. For example:

@LDAPField(attribute="myStringAttr",
           defaultDecodeValue="thisIsTheDefaultValue")
private String myStringAttr;

If the attribute myStringAttr doesn't exist in the entry being decoded, then the persistence framework will act as if it does exist with a value of "thisIsTheDefaultValue".

Neil Wilson
  • 1,706
  • 8
  • 4
  • Thanks, that works! I had only tried the defaultDecodeValue element with the list which didn't work since I tried to pass it an empty ArrayList. – jansohn Aug 13 '15 at 06:45
  • Seems I celebrated too early. Specifying a defaultDecodeValue for a list will not create an empty list but a list with one element. – jansohn Aug 13 '15 at 07:03