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:net.paslavsky.springrest.SpringAnnotationPreprocessor.java

private Map<String, Integer> getParametersWithAnnotation(Method method,
        Class<? extends Annotation> annotationClass) {
    Map<String, Integer> parameters = new HashMap<String, Integer>();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    for (int i = 0; i < parameterAnnotations.length; i++) {
        Annotation[] annotations = parameterAnnotations[i];
        if (isAnnotationPresent(annotations, annotationClass)) {
            String name = getValue(annotations, annotationClass);
            if (StringUtils.isEmpty(name)) {
                throw new SpringRestClientConfigurationException(
                        "REST client can't identify name by " + annotationClass);
            }//from   w  ww .  j a  v a 2  s .c o  m
            parameters.put(name, i);
        }
    }
    return parameters;
}

From source file:com.cuubez.visualizer.processor.ResourceVariableProcessor.java

public void process() {

    List<RootResource> rootResourceList = InformationRepository.getInstance().getRootResources();

    for (RootResource rootResource : rootResourceList) {

        for (SubResource subResource : rootResource.getSubResources()) {

            Method selectedMethod = subResource.getReflectionMethod();
            final Class[] paramTypes = selectedMethod.getParameterTypes();

            final Annotation[][] paramAnnotations = selectedMethod.getParameterAnnotations();

            for (int i = 0; i < paramAnnotations.length; i++) {

                boolean pathParam = false;
                boolean queryParam = false;
                boolean headerParam = false;
                boolean mandatory = false;
                String name = null;
                String parameterDetail = null;

                for (Annotation annotation : paramAnnotations[i]) {

                    if (annotation instanceof PathParam) {
                        name = ((PathParam) annotation).value();
                        pathParam = true;

                    } else if (annotation instanceof QueryParam) {

                        name = ((QueryParam) annotation).value();
                        queryParam = true;

                    } else if (annotation instanceof HeaderParam) {

                        name = ((HeaderParam) annotation).value();
                        headerParam = true;

                    } else if (annotation instanceof M) {
                        mandatory = true;
                    } else if (annotation instanceof ParameterDetail) {
                        parameterDetail = ((ParameterDetail) annotation).value();
                    }/*from   w  w w  .  j  a  v a2  s  . c  om*/
                }

                if (!pathParam && !headerParam && !queryParam) {
                    subResource.setRequestBody(paramTypes[i]);
                }

                constructPathVariableContext(name, pathParam, parameterDetail, paramTypes[i], subResource);
                constructQueryVariableContext(name, queryParam, parameterDetail, mandatory, paramTypes[i],
                        subResource);
                constructHeaderVariableContext(name, headerParam, parameterDetail, mandatory, paramTypes[i],
                        subResource);

            }

        }
    }

}

From source file:com.sf.ddao.chain.MethodInvocationHandler.java

public MethodInvocationHandler(Class<?> iFace, Method method, List<Command> commands) {
    this.iFace = iFace;
    isNullReturnDisallowed = notNullableTypes.contains(method.getReturnType());
    this.method = method;
    this.chain = new ChainBase(commands);
    final Annotation[][] parametersAnnotations = method.getParameterAnnotations();
    for (int i = 0; i < parametersAnnotations.length; i++) {
        for (Annotation parameterAnnotation : parametersAnnotations[i]) {
            if (parameterAnnotation.annotationType().equals(UseContext.class)) {
                contextParamIndex = i;/*from  w  w  w . j  a va 2  s. c  o  m*/
                return;
            }
        }
    }
}

From source file:ca.uhn.fhir.rest.method.MethodUtil.java

@SuppressWarnings("unchecked")
public static List<IParameter> getResourceParameters(final FhirContext theContext, Method theMethod,
        Object theProvider, RestOperationTypeEnum theRestfulOperationTypeEnum) {
    List<IParameter> parameters = new ArrayList<IParameter>();

    Class<?>[] parameterTypes = theMethod.getParameterTypes();
    int paramIndex = 0;
    for (Annotation[] annotations : theMethod.getParameterAnnotations()) {

        IParameter param = null;//from   w  w  w  . j  a va 2 s  . co  m
        Class<?> parameterType = parameterTypes[paramIndex];
        Class<? extends java.util.Collection<?>> outerCollectionType = null;
        Class<? extends java.util.Collection<?>> innerCollectionType = null;
        if (SearchParameterMap.class.equals(parameterType)) {
            if (theProvider instanceof IDynamicSearchResourceProvider) {
                Search searchAnnotation = theMethod.getAnnotation(Search.class);
                if (searchAnnotation != null && searchAnnotation.dynamic()) {
                    param = new DynamicSearchParameter((IDynamicSearchResourceProvider) theProvider);
                }
            }
        } else if (TagList.class.isAssignableFrom(parameterType)) {
            // TagList is handled directly within the method bindings
            param = new NullParameter();
        } else {
            if (Collection.class.isAssignableFrom(parameterType)) {
                innerCollectionType = (Class<? extends java.util.Collection<?>>) parameterType;
                parameterType = ReflectionUtil.getGenericCollectionTypeOfMethodParameter(theMethod, paramIndex);
            }
            if (Collection.class.isAssignableFrom(parameterType)) {
                outerCollectionType = innerCollectionType;
                innerCollectionType = (Class<? extends java.util.Collection<?>>) parameterType;
                parameterType = ReflectionUtil.getGenericCollectionTypeOfMethodParameter(theMethod, paramIndex);
            }
            if (Collection.class.isAssignableFrom(parameterType)) {
                throw new ConfigurationException("Argument #" + paramIndex + " of Method '"
                        + theMethod.getName() + "' in type '" + theMethod.getDeclaringClass().getCanonicalName()
                        + "' is of an invalid generic type (can not be a collection of a collection of a collection)");
            }
        }

        /* 
         * Note: for the frst two here, we're using strings instead of static binding
         * so that we don't need the java.servlet JAR on the classpath in order to use
         * this class 
         */
        if (ourServletRequestTypes.contains(parameterType.getName())) {
            param = new ServletRequestParameter();
        } else if (ourServletResponseTypes.contains(parameterType.getName())) {
            param = new ServletResponseParameter();
        } else if (parameterType.equals(RequestDetails.class)) {
            param = new RequestDetailsParameter();
        } else if (parameterType.equals(IRequestOperationCallback.class)) {
            param = new RequestOperationCallbackParameter();
        } else if (parameterType.equals(SummaryEnum.class)) {
            param = new SummaryEnumParameter();
        } else if (parameterType.equals(PatchTypeEnum.class)) {
            param = new PatchTypeParameter();
        } else {
            for (int i = 0; i < annotations.length && param == null; i++) {
                Annotation nextAnnotation = annotations[i];

                if (nextAnnotation instanceof RequiredParam) {
                    SearchParameter parameter = new SearchParameter();
                    parameter.setName(((RequiredParam) nextAnnotation).name());
                    parameter.setRequired(true);
                    parameter.setDeclaredTypes(((RequiredParam) nextAnnotation).targetTypes());
                    parameter.setCompositeTypes(((RequiredParam) nextAnnotation).compositeTypes());
                    parameter.setChainlists(((RequiredParam) nextAnnotation).chainWhitelist(),
                            ((RequiredParam) nextAnnotation).chainBlacklist());
                    parameter.setType(theContext, parameterType, innerCollectionType, outerCollectionType);
                    MethodUtil.extractDescription(parameter, annotations);
                    param = parameter;
                } else if (nextAnnotation instanceof OptionalParam) {
                    SearchParameter parameter = new SearchParameter();
                    parameter.setName(((OptionalParam) nextAnnotation).name());
                    parameter.setRequired(false);
                    parameter.setDeclaredTypes(((OptionalParam) nextAnnotation).targetTypes());
                    parameter.setCompositeTypes(((OptionalParam) nextAnnotation).compositeTypes());
                    parameter.setChainlists(((OptionalParam) nextAnnotation).chainWhitelist(),
                            ((OptionalParam) nextAnnotation).chainBlacklist());
                    parameter.setType(theContext, parameterType, innerCollectionType, outerCollectionType);
                    MethodUtil.extractDescription(parameter, annotations);
                    param = parameter;
                } else if (nextAnnotation instanceof IncludeParam) {
                    Class<? extends Collection<Include>> instantiableCollectionType;
                    Class<?> specType;

                    if (parameterType == String.class) {
                        instantiableCollectionType = null;
                        specType = String.class;
                    } else if ((parameterType != Include.class) || innerCollectionType == null
                            || outerCollectionType != null) {
                        throw new ConfigurationException("Method '" + theMethod.getName()
                                + "' is annotated with @" + IncludeParam.class.getSimpleName()
                                + " but has a type other than Collection<" + Include.class.getSimpleName()
                                + ">");
                    } else {
                        instantiableCollectionType = (Class<? extends Collection<Include>>) CollectionBinder
                                .getInstantiableCollectionType(innerCollectionType,
                                        "Method '" + theMethod.getName() + "'");
                        specType = parameterType;
                    }

                    param = new IncludeParameter((IncludeParam) nextAnnotation, instantiableCollectionType,
                            specType);
                } else if (nextAnnotation instanceof ResourceParam) {
                    Mode mode;
                    if (IBaseResource.class.isAssignableFrom(parameterType)) {
                        mode = Mode.RESOURCE;
                    } else if (String.class.equals(parameterType)) {
                        mode = ResourceParameter.Mode.BODY;
                    } else if (byte[].class.equals(parameterType)) {
                        mode = ResourceParameter.Mode.BODY_BYTE_ARRAY;
                    } else if (EncodingEnum.class.equals(parameterType)) {
                        mode = Mode.ENCODING;
                    } else {
                        StringBuilder b = new StringBuilder();
                        b.append("Method '");
                        b.append(theMethod.getName());
                        b.append("' is annotated with @");
                        b.append(ResourceParam.class.getSimpleName());
                        b.append(" but has a type that is not an implemtation of ");
                        b.append(IBaseResource.class.getCanonicalName());
                        b.append(" or String or byte[]");
                        throw new ConfigurationException(b.toString());
                    }
                    param = new ResourceParameter((Class<? extends IResource>) parameterType, theProvider,
                            mode);
                } else if (nextAnnotation instanceof IdParam || nextAnnotation instanceof VersionIdParam) {
                    param = new NullParameter();
                } else if (nextAnnotation instanceof ServerBase) {
                    param = new ServerBaseParamBinder();
                } else if (nextAnnotation instanceof Elements) {
                    param = new ElementsParameter();
                } else if (nextAnnotation instanceof Since) {
                    param = new SinceParameter();
                    ((SinceParameter) param).setType(theContext, parameterType, innerCollectionType,
                            outerCollectionType);
                } else if (nextAnnotation instanceof At) {
                    param = new AtParameter();
                    ((AtParameter) param).setType(theContext, parameterType, innerCollectionType,
                            outerCollectionType);
                } else if (nextAnnotation instanceof Count) {
                    param = new CountParameter();
                } else if (nextAnnotation instanceof Sort) {
                    param = new SortParameter(theContext);
                } else if (nextAnnotation instanceof TransactionParam) {
                    param = new TransactionParameter(theContext);
                } else if (nextAnnotation instanceof ConditionalUrlParam) {
                    param = new ConditionalParamBinder(theRestfulOperationTypeEnum,
                            ((ConditionalUrlParam) nextAnnotation).supportsMultiple());
                } else if (nextAnnotation instanceof OperationParam) {
                    Operation op = theMethod.getAnnotation(Operation.class);
                    param = new OperationParameter(theContext, op.name(), ((OperationParam) nextAnnotation));
                } else if (nextAnnotation instanceof Validate.Mode) {
                    if (parameterType.equals(ValidationModeEnum.class) == false) {
                        throw new ConfigurationException("Parameter annotated with @"
                                + Validate.class.getSimpleName() + "." + Validate.Mode.class.getSimpleName()
                                + " must be of type " + ValidationModeEnum.class.getName());
                    }
                    param = new OperationParameter(theContext, Constants.EXTOP_VALIDATE,
                            Constants.EXTOP_VALIDATE_MODE, 0, 1).setConverter(new IOperationParamConverter() {
                                @Override
                                public Object incomingServer(Object theObject) {
                                    if (isNotBlank(theObject.toString())) {
                                        ValidationModeEnum retVal = ValidationModeEnum
                                                .forCode(theObject.toString());
                                        if (retVal == null) {
                                            OperationParameter.throwInvalidMode(theObject.toString());
                                        }
                                        return retVal;
                                    } else {
                                        return null;
                                    }
                                }

                                @Override
                                public Object outgoingClient(Object theObject) {
                                    return ParametersUtil.createString(theContext,
                                            ((ValidationModeEnum) theObject).getCode());
                                }
                            });
                } else if (nextAnnotation instanceof Validate.Profile) {
                    if (parameterType.equals(String.class) == false) {
                        throw new ConfigurationException("Parameter annotated with @"
                                + Validate.class.getSimpleName() + "." + Validate.Profile.class.getSimpleName()
                                + " must be of type " + String.class.getName());
                    }
                    param = new OperationParameter(theContext, Constants.EXTOP_VALIDATE,
                            Constants.EXTOP_VALIDATE_PROFILE, 0, 1)
                                    .setConverter(new IOperationParamConverter() {
                                        @Override
                                        public Object incomingServer(Object theObject) {
                                            return theObject.toString();
                                        }

                                        @Override
                                        public Object outgoingClient(Object theObject) {
                                            return ParametersUtil.createString(theContext,
                                                    theObject.toString());
                                        }
                                    });
                } else {
                    continue;
                }

            }

        }

        if (param == null) {
            throw new ConfigurationException("Parameter #" + ((paramIndex + 1)) + "/" + (parameterTypes.length)
                    + " of method '" + theMethod.getName() + "' on type '"
                    + theMethod.getDeclaringClass().getCanonicalName()
                    + "' has no recognized FHIR interface parameter annotations. Don't know how to handle this parameter");
        }

        param.initializeTypes(theMethod, outerCollectionType, innerCollectionType, parameterType);
        parameters.add(param);

        paramIndex++;
    }
    return parameters;
}

From source file:org.forgerock.openidm.shell.CustomCommandScope.java

/**
 * Fetches the list of arguments from a specified method.
 * Arguments are defined by annotated method arguments with only a @Descriptor.
 * @param method method to fetch the list of arguments from
 * @return a list of Strings containing argument descriptions
 *//*  w ww . j a  v  a2  s. co  m*/
protected List<String> getArguments(Method method) {
    List<String> args = new ArrayList<String>();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    for (Annotation[] annotations : parameterAnnotations) {
        String desc = null;
        boolean foundParam = false;

        for (Annotation a : annotations) {
            if (a instanceof Parameter) {
                foundParam = true;
            } else if (a instanceof Descriptor) {
                Descriptor d = (Descriptor) a;
                desc = d.value();
            }
        }

        if (desc != null && !foundParam) {
            args.add(desc);
        }
    }
    return args;
}

From source file:org.forgerock.openidm.shell.CustomCommandScope.java

/**
 * Fetches the list of parameters from a specified method.
 * Parameters are defined as by method arguments annotated with @Parameter
 * @param method method to fetch the list of parameters from
 * @return a list of Strings containing parameter descriptions
 *///from ww w .  j  a  v  a 2  s . c o  m
protected List<String> getParameters(Method method) {
    List<String> opts = new ArrayList<String>();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    for (Annotation[] annotations : parameterAnnotations) {
        String names = null;
        String desc = "";
        for (Annotation a : annotations) {
            if (a instanceof Parameter) {
                Parameter param = (Parameter) a;
                names = StringUtils.join(param.names(), ", ");
            } else if (a instanceof Descriptor) {
                Descriptor d = (Descriptor) a;
                desc = d.value();
            }

        }

        if (names != null) {
            String str = LEAD_OPTION_SPACE + names
                    + OPTIONS_SPACE.substring(Math.min(names.length(), OPTIONS_SPACE.length())) + desc;
            opts.add(str);
        }
    }
    return opts;
}

From source file:edu.umn.msi.tropix.persistence.aop.SecurityAspect.java

@Before(value = "execution(* edu.umn.msi.tropix.persistence.service.*+.*(..))")
public void doAccessCheck(final JoinPoint joinPoint) {
    LOG.trace("Verifying persistence layer access to " + joinPoint.getSignature().toLongString());
    final Method method = AopUtils.getMethod(joinPoint);
    if (method.getAnnotation(PersistenceMethod.class) == null) {
        return;/*ww  w .j  a  v  a  2  s  . co m*/
    }
    final Annotation[][] annotations = method.getParameterAnnotations();
    String userId = null;
    for (int i = 0; i < annotations.length; i++) {
        final UserId userIdAnnotation = getAnnnotation(UserId.class, annotations[i]);
        if (userIdAnnotation != null) {
            final Object arg = joinPoint.getArgs()[i];
            userId = (String) arg;
            break;
        }
    }
    Preconditions.checkNotNull(userId, "No parameter ananotations of type UserId found, but one is required.");
    @SuppressWarnings("unchecked")
    final Collection<Class<? extends Annotation>> securityAnnotations = Arrays.asList(Owns.class, Reads.class,
            Modifies.class, MemberOf.class);
    for (int i = 0; i < annotations.length; i++) {
        for (final Annotation annotation : annotations[i]) {
            if (securityAnnotations.contains(annotation.annotationType())) {
                verify(userId, joinPoint.getArgs()[i], annotations[i],
                        joinPoint.getSignature() + "[" + i + "]");
            }
        }
    }

}

From source file:org.specrunner.parameters.core.AccessImpl.java

/**
 * Get annotation for methods./*from w w w  .  ja  va2  s  .c  o  m*/
 * 
 * @param method
 *            The write method.
 * @return The annotations.
 */
protected Annotation[] getMethodAnnotations(Method method) {
    Annotation[] annotations = method.getAnnotations();
    if (UtilConverter.getConverter(annotations) == null) {
        annotations = method.getParameterAnnotations()[0];
    }
    return annotations;
}

From source file:org.sybila.parasim.core.impl.ObservingMethod.java

public ObservingMethod(Object target, Method method) {
    Validate.notNull(method);//from w ww  .  j a  v a  2 s  .co m
    Validate.notNull(target);
    if (method.getParameterTypes().length == 0) {
        throw new IllegalArgumentException("Method without parameters can't be observing point.");
    }
    Observes observes = ReflectionUtils.loadAnnotation(method.getParameterAnnotations()[0], Observes.class);
    Validate.notNull(observes, "Method where the first parameter isn't annotated by " + Observes.class.getName()
            + " annotation can't be observing point.");
    this.method = method;
    this.target = target;
    injectionPoints = new InjectionPoint[method.getGenericParameterTypes().length - 1];
    for (int i = 1; i < method.getGenericParameterTypes().length; i++) {
        injectionPoints[i - 1] = new GenericInjectionPoint(method.getParameterAnnotations()[i],
                method.getGenericParameterTypes()[i]);
    }
}

From source file:org.xenei.jena.entities.impl.EffectivePredicate.java

public EffectivePredicate(final Method m) {
    if (m != null) {

        if (m.getParameterTypes().length > 0) {

            for (final Annotation a : m.getParameterAnnotations()[0]) {
                if (a instanceof URI) {
                    this.type = URI.class;
                }/*  w ww.  j  ava  2  s .  c  o m*/
            }
        }

        final Subject s = m.getDeclaringClass().getAnnotation(Subject.class);
        if (s != null) {
            this.namespace = s.namespace();
        }
        Predicate p = m.getAnnotation(Predicate.class);
        merge(p);
        if (p != null) {
            if (StringUtils.isNotBlank(p.postExec())) {
                String mName = p.postExec().trim();
                try {
                    Method peMethod = null;
                    Class<?> argType = null;
                    final ActionType actionType = ActionType.parse(m.getName());
                    switch (actionType) {
                    case GETTER:
                        argType = m.getReturnType();
                        break;

                    case SETTER:
                    case EXISTENTIAL:
                    case REMOVER:
                        if (m.getParameterTypes().length != 1) {
                            throw new RuntimeException(
                                    String.format("%s does not have a single parameter", peMethod));
                        }
                        argType = m.getParameterTypes()[0];
                        break;
                    }
                    peMethod = m.getDeclaringClass().getMethod(mName, argType);
                    if (argType.equals(peMethod.getReturnType())) {
                        addPostExec(peMethod);
                    } else {
                        throw new RuntimeException(
                                String.format("%s does not return its parameter type", peMethod));
                    }
                } catch (NoSuchMethodException e) {
                    throw new RuntimeException("Error parsing predicate annotation", e);
                } catch (SecurityException e) {
                    throw new RuntimeException("Error parsing predicate annotation", e);
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException("Error parsing predicate annotation action type", e);
                }
            }
        }
        if (StringUtils.isBlank(name)) {
            try {
                final ActionType actionType = ActionType.parse(m.getName());
                setName(actionType.extractName(m.getName()));
            } catch (final IllegalArgumentException e) {
                // expected when not an action method.
            }
        }
    }
}