Example usage for java.lang.reflect Method getParameterAnnotations

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

Introduction

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

Prototype

@Override
public Annotation[][] getParameterAnnotations() 

Source Link

Usage

From source file:org.brekka.stillingar.spring.bpp.ConfigurationBeanPostProcessor.java

/**
 * Encapsulate the 'listener' method that will be invoked once all fields/setter methods have been updated. The
 * parameters of this method will be added as individual {@link ValueDefinition}'s to <code>valueList</code>.
 * /*  www  .j av  a2 s.co m*/
 * @param method
 *            the method being encapsulated
 * @param valueList
 *            the list of value definitions that the new {@link ValueDefinition}s for this field will be added to.
 * @param bean
 *            the bean being configured.
 * @return the {@link PostUpdateChangeListener} that will invoke the listener method on configuration update.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected PostUpdateChangeListener processListenerMethod(Method method, List<ValueDefinition<?, ?>> valueList,
        Object bean) {
    Class<?>[] parameterTypes = method.getParameterTypes();
    Type[] genericParameterTypes = method.getGenericParameterTypes();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    List<ParameterValueResolver> argList = new ArrayList<ParameterValueResolver>();
    for (int i = 0; i < parameterTypes.length; i++) {
        ParameterValueResolver arg = null;
        Annotation[] annotations = parameterAnnotations[i];
        Class type = parameterTypes[i];
        boolean list = false;
        if (type == List.class) {
            type = listType(genericParameterTypes[i]);
            list = true;
        }
        Qualifier qualifier = null;
        for (Annotation annotation : annotations) {
            if (annotation instanceof Configured) {
                Configured paramConfigured = (Configured) annotation;
                MethodParameterListener mpl = new MethodParameterListener();
                ValueDefinition<Object, ?> value;
                if (list) {
                    value = new ValueListDefinition<Object>(type, paramConfigured.value(), mpl);
                } else {
                    value = new SingleValueDefinition<Object>(type, paramConfigured.value(), mpl);
                }
                valueList.add(value);
                arg = mpl;
                break;
            } else if (annotation instanceof Qualifier) {
                qualifier = (Qualifier) annotation;
            }
        }
        if (arg == null) {
            if (qualifier != null) {
                try {
                    beanFactory.getBean(qualifier.value(), type);
                    arg = new BeanReferenceResolver(beanFactory, qualifier, type);
                } catch (NoSuchBeanDefinitionException e) {
                    throw new ConfigurationException(format(
                            "Listener method '%s' parameter %d is not marked as %s and no bean "
                                    + "definition could be found in the container with the qualifier '%s' and type '%s'.",
                            method.getName(), (i + 1), Configured.class.getSimpleName(), qualifier.value(),
                            type.getName()));
                }
            } else {
                try {
                    beanFactory.getBean(type);
                    arg = new BeanReferenceResolver(beanFactory, type);
                } catch (NoSuchBeanDefinitionException e) {
                    throw new ConfigurationException(format(
                            "Listener method '%s' parameter %d is not marked as %s and no bean "
                                    + "definition could be found in the container with the type '%s'.",
                            method.getName(), (i + 1), Configured.class.getSimpleName(), type.getName()));
                }
            }
        }
        argList.add(arg);
    }
    return new PostUpdateChangeListener(bean, method, argList);
}

From source file:org.solmix.datax.support.InvokerObject.java

public Object invoke() throws InvokerException {
    Method method = getServiceMethod();
    Object instance = getServiceInstance();
    List<Object> methodArgs = new ArrayList<Object>();
    Class<?>[] parameterTypes = method.getParameterTypes();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    GenericParameterNode[] genericParamTypes = getGenericParameterTypes(method);
    Map<Integer, MethodArgInfo> argsInfo = invokerInfo.getMethodArgs();
    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> paramType = parameterTypes[i];
        MethodArgInfo argInfo = (argsInfo == null ? null : argsInfo.get(i));
        GenericParameterNode genericParamInfo = genericParamTypes[i];
        Annotation[] parameterannotation = parameterAnnotations[i];
        if (genericParamInfo != null && genericParamInfo.getClassByIndex(0) == paramType)
            genericParamInfo = genericParamInfo.getChildNode();
        try {//from w  ww . ja  v  a 2  s.  co  m
            methodArgs.add(lookupValue(paramType, argInfo, parameterannotation, genericParamInfo));
        } catch (Exception e) {
            String errorString = new StringBuilder().append("Unable to assign a  argument to slot #")
                    .append(i + 1).append(" taking type: ").append(paramType.getName()).append(" of method:")
                    .append(method.toString()).append(" Can't lookup arguments match this type").toString();
            throw new InvokerException(errorString, e);
        }

    }

    Object args[] = DataUtils.listToArray(methodArgs);
    if (LOG.isTraceEnabled()) {
        LOG.trace((new StringBuilder()).append("method takes: ").append(parameterTypes.length)
                .append(" args.  I've assembled: ").append(methodArgs.size()).append(" args")
                .append(" invoking method:").append(getFormattedMethodSignature(method))
                .append(" with arg types: ").append(getFormattedParamTypes(args)).toString());
    }

    try {
        return method.invoke(instance, args);
    } catch (InvocationTargetException e) {
        throw new InvokerException(e.getMessage(), e.getCause());
    } catch (Exception e) {
        throw new InvokerException("Invoke Exception", e);
    }

}

From source file:org.b3log.latke.servlet.RequestProcessors.java

/**
 * getRendererId from mark {@link Render},using"-" as split:class_method_PARAMETER.
 * @param processorClass class//from ww  w  .  ja v  a 2 s  .c  om
 * @param processorMethod method
 * @param i the index of the 
 * @return string
 */
private static String getRendererId(final Class<?> processorClass, final Method processorMethod, final int i) {

    final StringBuilder sb = new StringBuilder();

    if (processorClass.isAnnotationPresent(Render.class)) {
        final String v = processorClass.getAnnotation(Render.class).value();

        if (StringUtils.isNotBlank(v)) {
            sb.append(v).append(v);
        }
    }

    if (processorMethod.isAnnotationPresent(Render.class)) {

        final String v = processorClass.getAnnotation(Render.class).value();

        if (StringUtils.isNotBlank(v)) {
            if (sb.length() > 0) {
                sb.append("-");
            }
            sb.append(v).append(v);
        }
    }

    for (java.lang.annotation.Annotation annotation : processorMethod.getParameterAnnotations()[i]) {
        if (annotation instanceof Render) {
            final String v = ((PathVariable) annotation).value();

            if (sb.length() > 0) {
                sb.append("-");
            }
            sb.append(v).append(v);
        }
    }

    return sb.toString();
}

From source file:org.vosao.rest.RestManager.java

private MatchResult matchQueryMethod(Object restService, String methodName, Map<String, String> queryParams) {
    MatchResult result = null;/*w  w w .  ja  v a 2s .  c o  m*/
    for (Method m : restService.getClass().getMethods()) {
        if (!m.getName().equals(methodName))
            continue;
        if (m.isVarArgs())
            throw new IllegalArgumentException("Varargs are not supported");

        Class<?>[] paramTypes = m.getParameterTypes();
        if (paramTypes.length != queryParams.size())
            continue;
        List<String> paramsList = new ArrayList<String>();
        for (int i = 0; i < paramTypes.length; i++) {
            String paramName = getParamNameFromArgAnnotation(m.getParameterAnnotations()[i]);
            if (paramName != null && queryParams.containsKey(paramName)) {
                paramsList.add(queryParams.get(paramName));
            }
        }
        if (paramsList.size() != queryParams.size())
            continue;
        Object[] convertedArgs = null;
        try {
            convertedArgs = convertArgs(paramTypes, paramsList);
        } catch (Exception e) {
        }
        if (convertedArgs == null)
            continue;
        return new MatchResult(m, convertedArgs);
    }
    return result;
}

From source file:com.khs.sherpa.servlet.request.DefaultSherpaRequest.java

private Object[] getParams(Method method) {
    RequestMapper map = new RequestMapper();
    map.setApplicationContext(applicationContext);
    map.setRequest(request);/*from w w  w.j av a  2 s  .c  o  m*/
    map.setResponse(response);
    map.setRequestProcessor(requestProcessor);
    Class<?>[] types = method.getParameterTypes();
    Object[] params = null;
    // get parameters
    if (types.length > 0) {
        params = new Object[types.length];
    }

    Annotation[][] parameters = method.getParameterAnnotations();
    for (int i = 0; i < parameters.length; i++) {
        Class<?> type = types[i];
        Annotation annotation = null;
        if (parameters[i].length > 0) {
            for (Annotation an : parameters[i]) {
                if (an.annotationType().isAssignableFrom(Param.class)) {
                    annotation = an;
                    break;
                }
            }

        }
        params[i] = map.map(method.getClass().getName(), method.getName(), type, annotation);
    }
    return params;
}

From source file:io.limberest.api.SwaggerReader.java

private void read(ReaderContext context) {
    final SwaggerDefinition swaggerDefinition = context.getCls().getAnnotation(SwaggerDefinition.class);
    if (swaggerDefinition != null) {
        readSwaggerConfig(swaggerDefinition);
    }/*from  www  . j a va 2 s  . c om*/
    for (Method method : context.getCls().getMethods()) {
        // TODO: how to smartly limit extension processing
        // if (ReflectionUtils.isOverriddenMethod(method, context.getCls())) {
        //     continue;
        // }
        final Operation operation = new Operation();
        String operationPath = null;
        String httpMethod = null;

        final Type[] genericParameterTypes = method.getGenericParameterTypes();
        final Annotation[][] paramAnnotations = method.getParameterAnnotations();

        // Avoid java.util.ServiceLoader mechanism which finds ServletReaderExtension
        // for (ReaderExtension extension : ReaderExtensions.getExtensions()) {
        for (ReaderExtension extension : getExtensions()) {
            if (operationPath == null) {
                operationPath = extension.getPath(context, method);
            }
            if (httpMethod == null) {
                httpMethod = extension.getHttpMethod(context, method);
            }
            if (operationPath == null || httpMethod == null) {
                continue;
            }

            if (extension.isReadable(context)) {
                extension.setDeprecated(operation, method);
                extension.applyConsumes(context, operation, method);
                extension.applyProduces(context, operation, method);
                extension.applyOperationId(operation, method);
                extension.applySummary(operation, method);
                extension.applyDescription(operation, method);
                extension.applySchemes(context, operation, method);
                extension.applySecurityRequirements(context, operation, method);
                extension.applyTags(context, operation, method);
                extension.applyResponses(context, operation, method);
                extension.applyImplicitParameters(context, operation, method);
                for (int i = 0; i < genericParameterTypes.length; i++) {
                    extension.applyParameters(context, operation, genericParameterTypes[i],
                            paramAnnotations[i]);
                }
            }
        }

        if (httpMethod != null && operationPath != null) {
            if (operation.getResponses() == null) {
                operation.defaultResponse(new Response().description("OK"));
            } else {
                for (String k : operation.getResponses().keySet()) {
                    if (k.equals("200")) {
                        Response response = operation.getResponses().get(k);
                        if ("successful operation".equals(response.getDescription()))
                            response.setDescription("OK");
                    }
                }
            }

            final Map<String, String> regexMap = new HashMap<String, String>();
            final String parsedPath = PathUtils.parsePath(operationPath, regexMap);

            if (parsedPath != null) {
                // Check for curly path params -- these are added for free if not annotated.
                for (String seg : parsedPath.split("/")) {
                    if (seg.startsWith("{") && seg.endsWith("}")) {
                        String segName = seg.substring(1, seg.length() - 1);
                        boolean declared = false;
                        for (Parameter opParam : operation.getParameters()) {
                            if ("path".equals(opParam.getIn()) && segName.equals(opParam.getName())) {
                                declared = true;
                                break;
                            }
                        }
                        if (!declared) {
                            PathParameter pathParam = new PathParameter();
                            pathParam.setName(segName);
                            pathParam.setRequired(false);
                            pathParam.setDefaultValue("");
                            operation.parameter(pathParam);
                        }
                    }
                }
            }

            Path path = swagger.getPath(parsedPath);
            if (path == null) {
                path = new Path();
                swagger.path(parsedPath, path);
            }
            path.set(httpMethod.toLowerCase(), operation);
        }
    }
}

From source file:org.lexevs.cache.AbstractMethodCachingBean.java

/**
 * Cache method.//  ww w.  j a v  a2s  .c  o m
 * 
 * @param pjp the pjp
 * 
 * @return the object
 * 
 * @throws Throwable the throwable
 */
protected Object doCacheMethod(T joinPoint) throws Throwable {

    if (!CacheSessionManager.getCachingStatus()) {
        return this.proceed(joinPoint);
    }

    Method method = this.getMethod(joinPoint);

    if (method.isAnnotationPresent(CacheMethod.class) && method.isAnnotationPresent(ClearCache.class)) {
        throw new RuntimeException("Cannot both Cache method results and clear the Cache in "
                + "the same method. Please only use @CacheMethod OR @ClearCache -- not both. "
                + " This occured on method: " + method.toString());
    }

    Object target = this.getTarget(joinPoint);

    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    String key = this.getKeyFromMethod(target.getClass().getName(), method.getName(),
            this.getArguments(joinPoint), parameterAnnotations);

    Cacheable cacheableAnnotation = AnnotationUtils.findAnnotation(target.getClass(), Cacheable.class);
    CacheMethod cacheMethodAnnotation = AnnotationUtils.findAnnotation(method, CacheMethod.class);

    CacheWrapper<String, Object> cache = this.getCacheFromName(cacheableAnnotation.cacheName(), true);

    if (method.isAnnotationPresent(ClearCache.class)) {
        return this.clearCache(joinPoint, method);
    }

    Object value = cache.get(key);
    if (value != null) {
        this.logger.debug("Cache hit on: " + key);
        if (value.equals(NULL_VALUE_CACHE_PLACEHOLDER)) {
            return null;
        } else {
            return returnResult(value, cacheMethodAnnotation);
        }
    } else {
        this.logger.debug("Caching miss on: " + key);
    }

    Object result = this.proceed(joinPoint);

    if (this.isolateCachesOnClear == false
            || (this.isolateCachesOnClear == true && (this.cacheRegistry.getInThreadCacheClearingState() == null
                    || this.cacheRegistry.getInThreadCacheClearingState() == false))) {
        this.logger.debug("Thread is not in @Clear state, caching can continue for key: " + key);

        if (result != null) {
            cache.put(key, result);
        } else {
            cache.put(key, NULL_VALUE_CACHE_PLACEHOLDER);
        }
    } else {
        this.logger.debug("Thread is in @Clear state, caching skipped for key: " + key);
    }

    return returnResult(result, cacheMethodAnnotation);
}

From source file:kenh.xscript.impl.BaseElement.java

/**
 * Find attribute annotations for all process method
 *///  w  ww . j ava2 s .c om
private void readAttributeAnnotation() {
    if (allAttributeAnnotation != null)
        return;

    allAttributeAnnotation = new Vector();

    Method[] methods = this.getClass().getMethods();

    for (Method method : methods) {
        String name = method.getName();
        Annotation process = method.getAnnotation(Processing.class);
        Annotation[][] annotations = method.getParameterAnnotations();

        if (process != null || name.equals(METHOD)) {

            boolean find = true;
            String[] group = new String[annotations.length];
            for (int i = 0; i < annotations.length; i++) {
                Annotation[] anns = annotations[i];
                if (anns == null) {
                    find = false;
                    break;
                }
                String attributeName = null;
                for (Annotation ann : anns) {
                    if (ann instanceof Attribute) {
                        attributeName = ((Attribute) ann).value();
                        break;
                    }
                }

                if (StringUtils.isBlank(attributeName)) {
                    find = false;
                    break;
                }

                group[i] = attributeName;

            }
            if (find) {

                allAttributeAnnotation.add(group);

            }
        }
    }
}

From source file:org.jdbcluster.privilege.PrivilegeCheckerImpl.java

/**
 * calculates parameter specific privileges for service method calls
 * null values for PrivilegeCluster arguments are always allowed!
 * /*from ww w.  j a  v  a2  s.  c o  m*/
 * @param calledServiceMethod the method called
 * @param args method parameters
 * @return Set<String>
 */
private Set<String> getServiceMethodParameterPrivileges(Method calledServiceMethod, Object[] args) {
    Set<String> result = new HashSet<String>();
    DomainChecker dc = DomainCheckerImpl.getInstance();
    Annotation[][] methodParameterAnnos = calledServiceMethod.getParameterAnnotations();
    if (methodParameterAnnos == null)
        return result;

    for (int i = 0; i < args.length; i++) {
        if (methodParameterAnnos.length > 0) {
            PrivilegesParameter pp = null;
            for (int t = 0; t < methodParameterAnnos[i].length; t++) {
                Annotation anno = methodParameterAnnos[i][t];
                if (anno instanceof PrivilegesParameter) {
                    pp = (PrivilegesParameter) anno;
                }
            }
            if (pp != null) {
                Object arg = args[i];
                if (arg != null) {
                    if (arg instanceof PrivilegedCluster) {
                        getServiceBeanWrapper().setWrappedInstance(arg);
                        for (String propertyPath : pp.property()) {
                            PropertyDescriptor pd = getPropertyDescriptor(propertyPath,
                                    getServiceBeanWrapper());
                            if (pd != null) {
                                Field f = getPropertyField(propertyPath, pd);
                                String domId = getDomainIdFromField(f);
                                DomainPrivilegeList dpl;
                                try {
                                    dpl = (DomainPrivilegeList) dc.getDomainListInstance(domId);
                                } catch (ClassCastException e) {
                                    throw new ConfigurationException("privileged domain [" + domId
                                            + "] needs implemented DomainPrivilegeList Interface", e);
                                }
                                String value = getPropertyValue(propertyPath, getServiceBeanWrapper());
                                result.addAll(dpl.getDomainEntryPivilegeList(domId, value));
                            }
                        }
                    } else
                        throw new ConfigurationException("Argument of method: " + calledServiceMethod.getName()
                                + " has @" + PrivilegesParameter.class.getName()
                                + " annotation but is not a instance of " + PrivilegedCluster.class.getName());
                }
            }
        }
    }
    return result;
}

From source file:org.activiti.spring.components.aop.ActivitiStateAnnotationBeanPostProcessor.java

public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    // first sift through and get all the methods
    // then get all the annotations
    // then build the metadata and register the metadata
    final Class<?> targetClass = AopUtils.getTargetClass(bean);
    final org.activiti.spring.annotations.ActivitiComponent component = targetClass
            .getAnnotation(org.activiti.spring.annotations.ActivitiComponent.class);

    ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
        @SuppressWarnings("unchecked")
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

            State state = AnnotationUtils.getAnnotation(method, State.class);

            String processName = component.processKey();

            if (StringUtils.hasText(state.process())) {
                processName = state.process();
            }//from   w ww . j  av  a 2 s .  c o m

            String stateName = state.state();

            if (!StringUtils.hasText(stateName)) {
                stateName = state.value();
            }

            Assert.notNull(stateName, "You must provide a stateName!");

            Map<Integer, String> vars = new HashMap<Integer, String>();
            Annotation[][] paramAnnotationsArray = method.getParameterAnnotations();

            int ctr = 0;
            int pvMapIndex = -1;
            int procIdIndex = -1;

            for (Annotation[] paramAnnotations : paramAnnotationsArray) {
                ctr += 1;

                for (Annotation pa : paramAnnotations) {
                    if (pa instanceof ProcessVariable) {
                        ProcessVariable pv = (ProcessVariable) pa;
                        String pvName = pv.value();
                        vars.put(ctr, pvName);
                    } else if (pa instanceof ProcessVariables) {
                        pvMapIndex = ctr;
                    } else if (pa instanceof ProcessId) {
                        procIdIndex = ctr;
                    }
                }
            }

            ActivitiStateHandlerRegistration registration = new ActivitiStateHandlerRegistration(vars, method,
                    bean, stateName, beanName, pvMapIndex, procIdIndex, processName);
            registry.registerActivitiStateHandler(registration);
        }
    }, new ReflectionUtils.MethodFilter() {
        public boolean matches(Method method) {
            return null != AnnotationUtils.getAnnotation(method, State.class);
        }
    });

    return bean;
}