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

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang3.reflect.FieldUtils;

import io.ljunggren.reflectionUtils.ReflectionUtils;
import io.ljunggren.sanitizer.sanitation.SanitationRegistry;
import lombok.Getter;

/**
 * Entry point for sanitizing the annotated fields of an object.
 *
 * <p>Construct with the target object, optionally enable {@link #recursive()}
 * traversal, then call {@link #sanitize()} to apply all annotation-driven
 * cleansing in place.</p>
 */
@Getter
public class Sanitizer {

    private final Object object;
    private boolean recursive;

    public Sanitizer(Object object) {
        this.object = object;
    }

    /**
     * Enables recursive descent into embedded objects, collections, and arrays
     * of non-primitive types.
     *
     * @return this {@code Sanitizer} for chaining
     */
    public Sanitizer recursive() {
        this.recursive = true;
        return this;
    }

    /**
     * Walks the configured object and applies sanitation to every annotated
     * field.
     *
     * @return this {@code Sanitizer} for chaining
     */
    public Sanitizer sanitize() {
        List<Item> items = findItems(object);
        sanitizeItems(items);
        return this;
    }

    private List<Item> findItems(Object object) {
        List<Item> items = new ArrayList<>();
        findItems(object, items);
        return items;
    }

    private List<Item> findItems(Object object, List<Item> items) {
        List<Field> fields = findObjectFields(object);
        for (Field field : fields) {
            try {
                Object value = FieldUtils.readField(field, object, true);
                if (field.getAnnotations().length > 0) {
                    items.add(new Item(object, field, value));
                }
                if (checkEmbedded(field.getType())) {
                    if (ReflectionUtils.isCollection(field.getType())) {
                        @SuppressWarnings("unchecked")
                        Collection<Object> embeddeds = (Collection<Object>) value;
                        if (embeddeds == null) {
                            continue;
                        }
                        for (Object embedded : embeddeds) {
                            if (embedded != null && checkEmbedded(embedded.getClass())) {
                                findItems(embedded, items);
                            }
                        }
                        continue;
                    }
                    if (value != null) {
                        findItems(value, items);
                    }
                }
            } catch (IllegalAccessException e) {
                throw new IllegalStateException(
                        "Failed to read field " + field.getName(), e);
            }
        }
        return items;
    }

    private boolean checkEmbedded(Class<?> type) {
        if (!recursive) {
            return false;
        }
        if (ReflectionUtils.isPrimitive(type)) {
            return false;
        }
        if (ReflectionUtils.isEnum(type)) {
            return false;
        }
        if (type.getPackage() == null) {
            return false;
        }
        if (ReflectionUtils.isCollection(type)) {
            return true;
        }
        return !type.getPackage().getName().startsWith("java");
    }

    private List<Field> findObjectFields(Object object) {
        if (object != null) {
            Class<?> clazz = object.getClass();
            return FieldUtils.getAllFieldsList(clazz);
        }
        return new ArrayList<>();
    }

    private void sanitizeItems(List<Item> items) {
        SanitationRegistry registry = SanitationRegistry.defaultRegistry();
        items.forEach(item -> sanitizeItem(item, registry));
    }

    private void sanitizeItem(Item item, SanitationRegistry registry) {
        Annotation[] annotations = item.getField().getAnnotations();
        for (Annotation annotation : annotations) {
            registry.sanitize(annotation, item);
        }
    }

}