Newer
Older
sanitizer / src / main / java / io / ljunggren / sanitizer / sanitation / CustomSanitation.java
package io.ljunggren.sanitizer.sanitation;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;

import io.ljunggren.sanitizer.Item;
import io.ljunggren.sanitizer.annotation.CustomSanitizer;
import io.ljunggren.sanitizer.cleanser.Cleanser;
import io.ljunggren.sanitizer.cleanser.ObjectAwareCleanser;

public class CustomSanitation extends SanitationChain {

    @Override
    public void sanitize(Annotation annotation, Item item) {
        if (annotation.annotationType() == CustomSanitizer.class) {
            Class<?> clazz = ((CustomSanitizer) annotation).value();
            try {
                if (ObjectAwareCleanser.class.isAssignableFrom(clazz)) {
                    ObjectAwareCleanser<Object> cleanser = instantiate(clazz);
                    item.setValue(cleanser.cleanse(item.getObject(), item.getValue()));
                    return;
                }
                if (Cleanser.class.isAssignableFrom(clazz)) {
                    Cleanser<Object> cleanser = instantiate(clazz);
                    item.setValue(cleanser.cleanse(item.getValue()));
                    return;
                }
                // The configured class does not implement Cleanser or
                // ObjectAwareCleanser; skip rather than fail.
            } catch (ReflectiveOperationException e) {
                throw new IllegalStateException(
                        "Failed to instantiate CustomSanitizer " + clazz.getName(), e);
            }
            return;
        }
        nextChain.sanitize(annotation, item);
    }

    @SuppressWarnings("unchecked")
    private <C> C instantiate(Class<?> clazz)
            throws InstantiationException, IllegalAccessException,
                   InvocationTargetException, NoSuchMethodException {
        return (C) clazz.getDeclaredConstructor().newInstance();
    }

}