Example usage for java.lang.reflect Method isAnnotationPresent

List of usage examples for java.lang.reflect Method isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang.reflect Method isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:org.vaadin.spring.i18n.Translator.java

private void analyzeMethods(Class<?> clazz) {
    for (Method m : clazz.getDeclaredMethods()) {
        if (m.getParameterTypes().length == 0 && m.getReturnType() != Void.TYPE) {
            if (m.isAnnotationPresent(TranslatedProperty.class)) {
                translatedMethods.put(m.getAnnotation(TranslatedProperty.class), m);
            } else if (m.isAnnotationPresent(TranslatedProperties.class)) {
                for (TranslatedProperty annotation : m.getAnnotation(TranslatedProperties.class).value()) {
                    translatedMethods.put(annotation, m);
                }/*from  w  w  w.j  a v a2s  .  com*/
            }
        }
    }
}

From source file:gda.jython.accesscontrol.ProtectedMethodComponent.java

/**
 * Analyse the given class and add any methods annotated to be protected to the protectedMethods array.
 * /*ww  w . j  a  va2 s  .  co m*/
 * @param clazz
 */
@SuppressWarnings("rawtypes")
private void analyseClass(Class clazz) {
    // loop over this classes methods
    Method[] newMethods = clazz.getMethods();
    for (Method thisMethod : newMethods) {
        if (thisMethod.isAnnotationPresent(gda.jython.accesscontrol.MethodAccessProtected.class)
                && thisMethod.getAnnotation(MethodAccessProtected.class).isProtected()) {
            addMethod(thisMethod);
        }
    }

    // loop over the interfaces the class implements
    Class[] newInterfaces = clazz.getInterfaces();
    for (Class thisInterface : newInterfaces) {
        // if its a new interface (for performance, ensure each interface only looked at once)
        if (!ArrayUtils.contains(analysedInterfaces, thisInterface)) {
            analysedInterfaces = (Class[]) ArrayUtils.add(analysedInterfaces, thisInterface);

            // check if any method in that interface is annotated that it should be protected
            for (Method method : thisInterface.getMethods()) {
                if (method.isAnnotationPresent(gda.jython.accesscontrol.MethodAccessProtected.class)
                        && method.getAnnotation(MethodAccessProtected.class).isProtected()) {
                    addMethod(method);
                }
            }
        }
    }
}

From source file:com.reactivetechnologies.platform.rest.depre.RequestDispatchers.java

private void addAnnotatedClass(Class<?> restletClass) throws InstantiationException, IllegalAccessException {
    final JAXRSInstanceMetadata proxy = new JAXRSInstanceMetadata(restletClass.newInstance());
    if (restletClass.isAnnotationPresent(Path.class)) {
        String rootUri = restletClass.getAnnotation(Path.class).value();
        proxy.setRootUri(rootUri);/* ww w.jav a 2  s .c  o  m*/
    }
    ReflectionUtils.doWithMethods(restletClass, new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            String subUri = "";
            if (method.isAnnotationPresent(Path.class)) {
                subUri = method.getAnnotation(Path.class).value();
            }
            if (method.isAnnotationPresent(GET.class)) {
                MethodDetail m = new MethodDetail(method);
                Annotation[][] mAnnots = method.getParameterAnnotations();
                int i = 0;
                for (Annotation[] annots : mAnnots) {
                    for (Annotation annot : annots) {
                        if (annot.annotationType() == QueryParam.class) {
                            m.setQueryParam(i, ((QueryParam) annot).value());
                        }
                    }
                    i++;
                }
                proxy.addGetMethod(proxy.getRootUri() + subUri, m);
            }
            if (method.isAnnotationPresent(POST.class)) {
                MethodDetail m = new MethodDetail(method);
                Annotation[][] mAnnots = method.getParameterAnnotations();
                int i = 0;
                for (Annotation[] annots : mAnnots) {
                    for (Annotation annot : annots) {
                        if (annot.annotationType() == QueryParam.class) {
                            m.setQueryParam(i, ((QueryParam) annot).value());
                        }
                    }
                    i++;
                }
                proxy.addPostMethod(proxy.getRootUri() + subUri, m);
            }

        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {
            return (method.isAnnotationPresent(GET.class) || method.isAnnotationPresent(POST.class));
        }
    });

    allClasses.add(proxy);
}

From source file:com.flipkart.flux.deploymentunit.DeploymentUnit.java

/**
 * Given a class loader, retrieves workflow classes names from config file, and returns methods
 * which are annotated with {@link com.flipkart.flux.client.model.Task} annotation in those classes.
 *//* w  w w. j a v  a2 s.  co m*/
private void populateTaskMethods() {

    List<String> classNames = (List<String>) configuration.getProperty(WORKFLOW_CLASSES);

    try {
        //loading this class separately in this class loader as the following isAnnotationPresent check returns false, if
        //we use default class loader's Task, as both class loaders don't have any relation between them.
        Class taskAnnotationClass = deploymentUnitClassLoader.loadClass(Task.class.getCanonicalName());

        for (String name : classNames) {
            Class clazz = deploymentUnitClassLoader.loadClass(name);

            for (Method method : clazz.getMethods()) {
                if (method.isAnnotationPresent(taskAnnotationClass)) {
                    Annotation taskAnnotation = method.getAnnotationsByType(taskAnnotationClass)[0];
                    long version = 0;

                    for (Method annotationMethod : taskAnnotationClass.getDeclaredMethods()) {
                        if (annotationMethod.getName().equals("version")) {
                            version = (Long) annotationMethod.invoke(taskAnnotation);
                        }
                    }

                    MethodId methodId = new MethodId(method);
                    String taskIdentifier = methodId.toString() + _VERSION + version;

                    taskMethods.put(taskIdentifier, method);
                }
            }
        }
    } catch (Exception e) {
        throw new FluxError(FluxError.ErrorType.runtime,
                "Error while getting task methods for deploymentUnit: " + name + "/" + version, e);
    }
}

From source file:es.logongas.ix3.rule.impl.RuleEngineImpl.java

private List<Method> getRuleMethods(Object rulesObject, Class annotationClass) {
    Map<String, Method> ruleMethods = new HashMap<String, Method>();
    Method[] methods;/*  ww  w .jav  a2s .c o m*/

    if (rulesObject == null) {
        throw new RuntimeException("El objeto con la regla no puede ser null");
    }

    methods = rulesObject.getClass().getMethods();

    for (Method method : methods) {
        if (method.isAnnotationPresent(annotationClass) == true) {
            if (ruleMethods.containsKey(method.getName()) == false) {
                ruleMethods.put(method.getName(), method);
            }
        }
    }

    methods = rulesObject.getClass().getDeclaredMethods();

    for (Method method : methods) {
        if (method.isAnnotationPresent(annotationClass) == true) {
            if (ruleMethods.containsKey(method.getName()) == false) {
                method.setAccessible(true);
                ruleMethods.put(method.getName(), method);
            }
        }
    }

    return new ArrayList<Method>(ruleMethods.values());
}

From source file:nz.co.senanque.validationengine.Binder.java

public Map<ValidationObject, ProxyObject> bind(final ValidationObject object, final ValidationSession session,
        final ProxyField parent, final Integer index, ValidationObject owner) {
    MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(
            m_validationEngine.getMessageSource());
    final Map<ValidationObject, ProxyObject> ret = new IdentityHashMap<ValidationObject, ProxyObject>();
    if (object == null) {
        return ret;
    }/* w w  w . jav a 2 s .  c o m*/
    Class<?> clazz = object.getClass();
    final ClassMetadata classMetadata = m_validationEngine.getClassMetadata(clazz);
    if (classMetadata == null) {
        throw m_validationEngine.getLocaleAwareExceptionFactory().getRuntimeException(
                "nz.co.senanque.validationengine.class.not.recognised", new Object[] { clazz.getName() });
    }
    object.setValidationSession(session);
    final ProxyObject proxyObject = new ProxyObject(object, parent, index, session);
    ret.put(object, proxyObject);
    final ObjectMetadata objectMetadata = (ObjectMetadata) object.getMetadata();
    objectMetadata.setClassMetadata(proxyObject, classMetadata);
    Map<String, Property> propertyMap = ValidationUtils.getProperties(object.getClass());
    for (Property property : propertyMap.values()) {
        String fieldName = property.getFieldName();
        final PropertyMetadataImpl propertyMetadata = (PropertyMetadataImpl) classMetadata.getField(fieldName);
        if (propertyMetadata == null) {
            continue;
        }
        final ProxyFieldImpl proxyField = new ProxyFieldImpl(fieldName, proxyObject, parent, propertyMetadata,
                messageSourceAccessor);
        proxyObject.put(fieldName, proxyField);
        Method method = property.getGetter();
        if (property.getGetter().getReturnType().isAssignableFrom(List.class)) {
            try {
                @SuppressWarnings("unchecked")
                final List<ValidationObject> validationObjects = (List<ValidationObject>) method.invoke(object,
                        new Object[] {});
                final ListeningArray<Object> array = new ListeningArray<Object>();
                array.addAll(validationObjects);
                array.setValidationSession(session);
                array.setProxyField(proxyField);
                final Method setterMethod = property.getSetter();
                setterMethod.invoke(object, array);
                int index1 = 0;
                for (ValidationObject child : validationObjects) {
                    ret.putAll(bind(child, session, proxyField, index1++, owner));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            continue;
        }
        if (m_validationEngine.getClassMetadata(method.getReturnType()) != null) {
            try {
                final ValidationObject child = (ValidationObject) method.invoke(object, new Object[] {});
                ret.putAll(bind(child, session, proxyField, null, owner));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            continue;
        }
        try {
            Method getter = ValidationUtils.figureGetter(fieldName, clazz);
            if (getter.isAnnotationPresent(Ignore.class)) {
                continue;
            }
            java.lang.reflect.Field propertyField = getField(clazz, fieldName);
            Object value = ConvertUtils.convertToObject(propertyField.getType());
            proxyField.setInitialValue(value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return ret;
}

From source file:com.wso2telco.core.authfilter.impl.authorization.BasicAuthenticationFilter.java

@Override
public boolean isAuthorized(ContainerRequestContext requestContext, Method method) {

    boolean isAuthorized = false;

    requestContext.getHeaders().add(HeaderParam.USER_NAME.getTObject(), userName);

    // validate user authorization by using user roles
    if (method.isAnnotationPresent(RolesAllowed.class)) {

        RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
        Set<String> allowedRolesSet = new HashSet<>(Arrays.asList(rolesAnnotation.value()));

        isAuthorized = userAuthorizationValidator.isAuthorizedRole(userName, allowedRolesSet);

        if (!isAuthorized) {

            requestContext.abortWith(accessDenied);
            return false;
        }//from  w  ww . j  a va  2s. c  o m
    }

    return true;
}

From source file:com.googlecode.wicketelements.security.AnnotationSecurityCheck.java

private SecurityConstraint instantiateSecurityConstraint(
        Class<? extends SecurityConstraint> constraintClassParam) {
    try {/*from  w w  w .  j  av  a2 s .c o  m*/
        for (final Method m : constraintClassParam.getDeclaredMethods()) {
            if (m.isAnnotationPresent(Factory.class)) {
                try {
                    return (SecurityConstraint) m.invoke(null);
                } catch (InvocationTargetException ex) {
                    throw new IllegalStateException(
                            "Cannot execute factory method for InstantiationSecurityConstraint: "
                                    + constraintClassParam.getName());
                }
            }
        }
        return constraintClassParam.newInstance();
    } catch (InstantiationException ex) {
        throw new IllegalStateException("Cannot instantiate security constraint class.", ex);
    } catch (IllegalAccessException ex) {
        throw new IllegalStateException("Cannot instantiate security constraint class.", ex);
    }
}

From source file:com.googlecode.wicketelements.security.AnnotationSecurityCheck.java

private InstantiationSecurityConstraint instantiateInstantiationSecurityConstraint(
        Class<? extends InstantiationSecurityConstraint> constraintClassParam) {
    try {/*from  w  ww .  java  2 s .  co  m*/
        for (final Method m : constraintClassParam.getDeclaredMethods()) {
            if (m.isAnnotationPresent(Factory.class)) {
                try {
                    return (InstantiationSecurityConstraint) m.invoke(null);
                } catch (InvocationTargetException ex) {
                    throw new IllegalStateException(
                            "Cannot execute factory method for InstantiationSecurityConstraint: "
                                    + constraintClassParam.getName());
                }
            }
        }
        return constraintClassParam.newInstance();
    } catch (InstantiationException ex) {
        throw new IllegalStateException("Cannot instantiate security constraint class.", ex);
    } catch (IllegalAccessException ex) {
        throw new IllegalStateException("Cannot instantiate security constraint class.", ex);
    }
}

From source file:gobblin.runtime.cli.PublicMethodsCliObjectFactory.java

private Options inferOptionsFromMethods() {
    Options options = new Options();

    for (Method method : klazz.getMethods()) {
        if (canUseMethod(method)) {
            CliObjectOption annotation = method.isAnnotationPresent(CliObjectOption.class)
                    ? method.getAnnotation(CliObjectOption.class)
                    : null;/*from w w w.ja  v a  2 s.c o m*/
            String optionName = annotation == null || Strings.isNullOrEmpty(annotation.name())
                    ? method.getName()
                    : annotation.name();
            String description = annotation == null ? "" : annotation.description();
            Option.Builder builder = Option.builder(optionName).desc(description);
            boolean hasArg = method.getParameterTypes().length > 0;
            if (hasArg) {
                builder.hasArg();
            }
            Option option = builder.build();
            options.addOption(option);
            this.methodsMap.put(option.getOpt(), method);
        }
    }

    return options;
}