All Downloads are FREE. Search and download functionalities are using the official Maven repository.

lv.ctco.cukesrest.internal.switches.SwitchedByInterceptor Maven / Gradle / Ivy

The newest version!
package lv.ctco.cukesrest.internal.switches;

import com.google.common.base.Optional;
import com.google.inject.*;
import lv.ctco.cukesrest.internal.context.*;
import org.aopalliance.intercept.*;

import java.lang.annotation.*;
import java.util.*;

public class SwitchedByInterceptor implements MethodInterceptor {

    @Inject
    GlobalWorldFacade world;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Annotation[] annotations = invocation.getMethod().getAnnotations();

        SwitchedBy annotation = getAnnotation(annotations, SwitchedBy.class);
        if (annotation == null) {
            annotations = getCurrentAndSuperclassAnnotations(invocation.getThis().getClass());
            annotation = getAnnotation(annotations, SwitchedBy.class);
        }

        if (annotation != null) {
            String switchedByKey = annotation.value();
            boolean switchedBy = world.getBoolean(switchedByKey);
            if (switchedBy) {
                return null;
            }
        }
        return invocation.proceed();
    }

    private Annotation[] getCurrentAndSuperclassAnnotations(Class clazz) {
        List annotations = new ArrayList(Arrays.asList(clazz.getAnnotations()));
        for (Class superclass = clazz.getSuperclass(); superclass != null; superclass = superclass.getSuperclass()) {
            annotations.addAll(Arrays.asList(superclass.getAnnotations()));
        }
        return annotations.toArray(new Annotation[annotations.size()]);
    }

    @SuppressWarnings("unchecked")
    private  T getAnnotation(Annotation[] annotations, Class clazz) {
        for (Annotation annotation : annotations) {
            if (annotation.annotationType().equals(clazz)) {
                return (T) annotation;
            }
        }
        return null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy