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.apache.nifi.registry.security.authentication.IdentityProviderFactory.java

private void performMethodInjection(final IdentityProvider instance, final Class loginIdentityProviderClass)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    for (final Method method : loginIdentityProviderClass.getMethods()) {
        if (method.isAnnotationPresent(IdentityProviderContext.class)) {
            // make the method accessible
            final boolean isAccessible = method.isAccessible();
            method.setAccessible(true);//from   w w w  .ja v  a 2s.  c o m

            try {
                final Class<?>[] argumentTypes = method.getParameterTypes();

                // look for setters (single argument)
                if (argumentTypes.length == 1) {
                    final Class<?> argumentType = argumentTypes[0];

                    // look for well known types
                    if (NiFiRegistryProperties.class.isAssignableFrom(argumentType)) {
                        // nifi properties injection
                        method.invoke(instance, properties);
                    }
                }
            } finally {
                method.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = loginIdentityProviderClass.getSuperclass();
    if (parentClass != null && IdentityProvider.class.isAssignableFrom(parentClass)) {
        performMethodInjection(instance, parentClass);
    }
}

From source file:mondrian.util.UtilCompatibleJdk15.java

@SuppressWarnings("unchecked")
public <T> T getAnnotation(Method method, String annotationClassName, T defaultValue) {
    try {/*  w ww  .ja v a  2  s.c  o  m*/
        Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) Class
                .forName(annotationClassName);
        if (method.isAnnotationPresent(annotationClass)) {
            final Annotation annotation = method.getAnnotation(annotationClass);
            final Method method1 = annotation.getClass().getMethod("value");
            return (T) method1.invoke(annotation);
        }
    } catch (IllegalAccessException e) {
        return defaultValue;
    } catch (InvocationTargetException e) {
        return defaultValue;
    } catch (NoSuchMethodException e) {
        return defaultValue;
    } catch (ClassNotFoundException e) {
        return defaultValue;
    }
    return defaultValue;
}

From source file:net.famzangl.minecraft.minebot.ai.command.CommandRegistry.java

private void getCommandsForClass(Class<?> commandClass, List<CommandDefinition> commands) {
    for (final Method m : commandClass.getMethods()) {
        if (Modifier.isStatic(m.getModifiers()) && m.isAnnotationPresent(AICommandInvocation.class)) {
            LOGGER.debug(MARKER_REGISTER, "Registering method: %s#%s()", commandClass.getCanonicalName(),
                    m.getName());/*from  ww w.  j av a2  s .com*/
            commands.addAll(getCommandsForMethod(m));
        }
    }
}

From source file:org.swordess.ldap.odm.metadata.entity.EntityMetaData.java

private EntityMetaData(Class<?> clazz) {
    this.managedClass = clazz;

    LogUtils.debug(LOG, "Extracting metadata from " + clazz);

    Entry entry = clazz.getAnnotation(Entry.class);
    if (null == entry) {
        throw new MetaDataException(
                String.format("Class %s must have a class level %s annotation", clazz, Entry.class));
    }/*  ww w.jav  a 2  s . c o m*/

    context = entry.context();
    objectClasses = entry.objectClasses();

    Set<String> allDefinedAttrNameSet = new HashSet<String>();
    for (Method m : clazz.getDeclaredMethods()) {
        m.setAccessible(true);

        // static methods and transient methods are not managed
        if (Modifier.isStatic(m.getModifiers()) || m.isAnnotationPresent(Transient.class)) {
            continue;
        }

        // methods without @Id or @Attribute are not managed
        if (!m.isAnnotationPresent(Id.class) && !m.isAnnotationPresent(Attribute.class)) {
            continue;
        }

        EntityPropertyMetaData currentPropertyMetaData = new EntityPropertyMetaData(m);
        if (currentPropertyMetaData.isId()) {
            if (null != idProperty) {
                throw new MetaDataException(String.format(
                        "You must have only one method with the %s annotation in class %s", Id.class, clazz));
            }
            idProperty = currentPropertyMetaData;
        }
        ldapPropNameToMetaData.put(currentPropertyMetaData.getLdapPropName(), currentPropertyMetaData);
        javaBeanPropNameToMetaData.put(currentPropertyMetaData.getJavaBeanPropName(), currentPropertyMetaData);
        allDefinedAttrNameSet.add(currentPropertyMetaData.getLdapPropName());
    }
    allDefinedAttrNames = allDefinedAttrNameSet.toArray(new String[0]);

    if (null == idProperty) {
        throw new MetaDataException(String.format(
                "All Entry classes must define a property with the %s annotation, error in class %s", Id.class,
                clazz));
    }

    LogUtils.debug(LOG, String.format("Extracted metadata from %s as %s", clazz, this));
}

From source file:com.art4ul.jcoon.bean.RestClientInterfaceInvocationHandler.java

@Override
public Object invoke(Object object, Method method, Object[] params) throws Throwable {
    LOG.trace("invoke(method = [{}], params = [{}])", new Object[] { method.getName(), params });

    Context context = new RestClientContext(object, method, params, restTemplate);

    if (method.isAnnotationPresent(BaseUrl.class)) {
        baseUrl = retrieveBaseUrl(context);
        return null;
    }//  w  w  w .  ja v  a 2s .c o  m
    context.setBaseUrl(baseUrl);

    AnnotationProcessor annotationProcessor = AnnotationProcessor.getInstance();

    // Process class annotations
    annotationProcessor.processAnnotationsBefore(context, originalClass.getAnnotations());

    // Process method annotations
    annotationProcessor.processAnnotationsBefore(context, method.getAnnotations());

    // Process method params
    for (int i = 0; i < params.length; i++) {
        Annotation[] annotations = method.getParameterAnnotations()[i];
        Object paramValue = params[i];
        annotationProcessor.processAnnotationsBefore(context, annotations, paramValue);
    }

    URI uri = context.buildUri();

    LOG.debug("URI= {}", uri.toString());

    HttpEntity httpEntity = context.createHttpEntity();

    Class<?> returnType = null;
    if (!method.getReturnType().equals(Void.TYPE)) {
        returnType = method.getReturnType();
    }

    ResponseEntity responseEntity = context.getRestTemplate().exchange(uri, context.getHttpMethod(), httpEntity,
            returnType);

    context.setResponseEntity(responseEntity);

    // Process method params after invocation
    for (int i = 0; i < params.length; i++) {
        Annotation[] annotations = method.getParameterAnnotations()[i];
        Object paramValue = params[i];
        annotationProcessor.processAnnotationsAfter(context, annotations, paramValue);
    }

    LOG.debug("responseEntity= {}", responseEntity.getBody());
    return responseEntity.getBody();
}

From source file:info.novatec.testit.livingdoc.interpreter.collection.CollectionInterpreter.java

private List<?> getCollectionProvider() {
    LOG.trace(ENTRY);//from  w ww  .j av  a  2  s  . c  o m
    Object target = fixture.getTarget();

    for (Method method : target.getClass().getMethods()) {
        if (method.isAnnotationPresent(CollectionProvider.class)) {
            List<?> result = toList(invoke(target, method));
            LOG.trace(EXIT_WITH, result.toString());
            return result;
        }
    }
    LOG.trace(EXIT_WITH_NULL);
    return null;
}

From source file:org.jgentleframework.configure.ConfigurationProxy.java

@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {

    if (Modifier.isAbstract(method.getModifiers())) {
        if (method.isAnnotationPresent(Block.class)) {
            Block anno = method.getAnnotation(Block.class);
            Class<?>[] clazzList = anno.value();
            ObjectBlock objBlock = new ObjectBlock(method, clazzList);
            this.objBlockList.add(objBlock);
        }/*from w w  w  .  j a  va2s .  c om*/
        // thc thi hm getOptionsList trn ConfigModule interface
        if (method.getName().equals("getOptionsList") && method.getParameterTypes().length == 0) {
            checkBlock(method);
            return this.optionsList;
        } else if (method.getName().equals("getTargetClass") && method.getParameterTypes().length == 0) {
            checkBlock(method);
            return this.targetClass;
        } else if (method.getName().equals("getConfigInstance") && method.getParameterTypes().length == 1) {
            checkBlock(method);
            return this.configObjList.get(args[0]);
        } else {
            if (!this.objBlockList.isEmpty()) {
                ObjectBlock objb = this.objBlockList.get(this.configObjList.size() - 1);
                List<Class<?>> clazzList = null;
                clazzList = objb.getBlockList();
                for (Class<?> clazz : clazzList) {
                    Object objConfig = this.configObjList.get(clazz);
                    List<Method> methodList = Arrays.asList(objConfig.getClass().getMethods());
                    if (methodList.contains(method)) {
                        checkBlock(method);
                        return method.invoke(objConfig, args);
                    } else {
                        continue;
                    }
                }
            }
            // Nu khng c
            for (Class<?> clazz : this.configObjList.keySet()) {
                Object objConfig = this.configObjList.get(clazz);
                List<Method> methodList = Arrays.asList(ReflectUtils.getAllDeclaredMethods(clazz));
                if (methodList.contains(method)) {
                    checkBlock(method);
                    return method.invoke(objConfig, args);
                } else {
                    continue;
                }
            }
            throw new NoSuchMethodException("Could not found " + method + " method!");
        }
    } else {
        checkBlock(method);
        return proxy.invokeSuper(obj, args);
    }
}

From source file:org.brushingbits.jnap.struts2.interceptor.RestWorkflowInterceptor.java

/**
 * @param invocation/*  w  ww  . j a v  a 2 s.  c  o m*/
 * @param action
 */
protected String findResultName(ActionInvocation invocation, Object action) {
    String resultName = Action.INPUT;
    try {
        Map<String, Object> session = ActionContext.getContext().getSession();
        Method method = action.getClass().getMethod(invocation.getProxy().getMethod(),
                ArrayUtils.EMPTY_CLASS_ARRAY);
        if (action instanceof ValidationWorkflowAware) {
            resultName = ((ValidationWorkflowAware) action).getInputResultName();
        } else if (method.isAnnotationPresent(InputConfig.class)) {
            InputConfig annotation = method.getAnnotation(InputConfig.class);
            if (StringUtils.isNotBlank(annotation.methodName())) {
                Method inputMethod = action.getClass().getMethod(annotation.methodName());
                resultName = (String) inputMethod.invoke(action);
            } else {
                resultName = annotation.resultName();
            }
        } else if (session.containsKey(InputResultInterceptor.INPUT_RESULT_NAME)) {
            resultName = (String) session.get(InputResultInterceptor.INPUT_RESULT_NAME);
        }
    } catch (Exception e) {
        ReflectionUtils.handleReflectionException(e);
    }
    return resultName;
}

From source file:com.socialize.SocializeActionProxy.java

protected void invoke(Activity context, SocializeListener listener, Method method, Object[] args)
        throws Throwable {

    SocializeService service = getSocialize();

    if (!service.isAuthenticated() && !method.isAnnotationPresent(NoAuth.class)) {
        doAuthAsync(context, listener, method, args);
    } else {//from  ww  w . j  a  v a 2 s.co m
        method.invoke(getBean(), args);
    }
}

From source file:org.castor.cpa.jpa.info.JPACallbackHandler.java

/**
 * Handles overridden CB methods accordingly.
 * //from ww w .j a v a 2  s  .  c o  m
 * @param annotationClass
 *            the annotation to look for
 * @param object
 *            the object to handle
 * @throws InvocationTargetException
 *             on callback invocation error
 * @throws IllegalAccessException
 *             on illegal method access error
 */
private <A extends Annotation> void handleOverriddenCallbacksFor(final Class<A> annotationClass,
        final Object object) throws InvocationTargetException, IllegalAccessException {
    Class<?> klass = object.getClass();
    Class<?> superclass = klass.getSuperclass();
    while (superclass != Object.class) {
        for (Method method : klass.getDeclaredMethods()) {
            if (method.isAnnotationPresent(annotationClass)) {
                final String methodName = method.getName();
                try {
                    final Method overridden = superclass.getDeclaredMethod(methodName);
                    if (overridden.isAnnotationPresent(annotationClass)) {
                        _overriddenCallbacks.put(methodName, object);
                    }
                } catch (NoSuchMethodException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(String.format("CB method `%s` is not overridden in `%s`.", method.getName(),
                                superclass.getSimpleName()));
                    }
                }
            }
        }
        superclass = superclass.getSuperclass();
    }
}