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.seasar.cadhelin.impl.ConverterFactoryImpl.java

public Converter[] createConverters(Method method, String[] parameterNames) {
    Class<?>[] parameterTypes = method.getParameterTypes();
    Converter[] converters = new Converter[parameterTypes.length];
    Annotation[][] annot = method.getParameterAnnotations();
    if (parameterNames == null) {
        LOG.warn("cannot find parameterNames for method " + method);
        return converters;
    }/*ww w  . j  a  v a2s.c o m*/
    for (int i = 0; i < parameterTypes.length; i++) {
        Param param = findParam(annot[i]);
        Converter converter = findConverter(parameterNames[i], parameterTypes[i], param);
        if (converter == null) {
            LOG.warn("cannot find converter for method " + method);
            continue;
        }
        converter.setParameterName(parameterNames[i]);
        converter.setParameterType(parameterTypes[i]);
        if (param != null) {
            converter.setDefaultValue(param.defaultVal());
            converter.setRequired(param.required());
            converter.setOnError(param.onError());
        }
        converter.getMessageArguments().put("name", parameterNames[i]);
        setUpValidater(converter, param);
        converters[i] = converter;
    }
    return converters;
}

From source file:org.restlet.ext.jaxrs.internal.client.JaxRsClientInvocationHandler.java

private void setRequestParams(Method javaMethod, Object[] args, Request request)
        throws IllegalMethodParamTypeException {

    int argIndex = 0;

    Annotation[][] parameterAnnotations = javaMethod.getParameterAnnotations();
    for (Annotation[] annotations : parameterAnnotations) {

        String representationAsText = getRepresentationAsText(args[argIndex]);

        if (representationAsText != null) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof HeaderParam) {
                    addHeaderParam(request, representationAsText, annotation);
                    argIndex++;//from   www  .  jav  a  2 s .c  o m
                } else if (annotation instanceof QueryParam) {
                    addQueryParam(request, representationAsText, annotation);
                    argIndex++;
                } else if (annotation instanceof FormParam) {

                    // TODO
                    argIndex++;
                } else if (annotation instanceof CookieParam) {
                    addCookieParam(request, representationAsText, annotation);
                    argIndex++;
                } else if (annotation instanceof MatrixParam) {

                    // TODO
                    argIndex++;
                } else if (annotation instanceof PathParam) {
                    addPathParam(request, representationAsText, annotation);
                    argIndex++;
                }
            }
        }
    }

    // TODO - possibly throw an exception if the arg count != processed
    // annotations?
}

From source file:org.shredzone.cilla.plugin.social.manager.SocialHandlerInvoker.java

/**
 * Sets the {@link Method} to be invoked.
 *
 * @param method//from  w w  w.  j a v  a 2 s .  c  o m
 *            {@link Method} to be invoked
 */
public void setMethod(Method method) {
    this.method = method;

    Annotation[][] annotations = method.getParameterAnnotations();
    methodAnnotations = new Annotation[annotations.length];

    for (int ix = 0; ix < annotations.length; ix++) {
        for (Annotation sub : annotations[ix]) {
            if (sub instanceof PageLink || sub instanceof PageTitle) {
                if (methodAnnotations[ix] != null) {
                    throw new IllegalArgumentException("Conflicting annotations " + sub + " and "
                            + methodAnnotations[ix] + " in social bookmark handler " + bean.getClass().getName()
                            + "#" + method.getName() + "()");
                }
                methodAnnotations[ix] = sub;
            }
        }
    }

    SocialBookmark sbAnno = method.getAnnotation(SocialBookmark.class);
    if (sbAnno != null && sbAnno.identifier() != null && !sbAnno.identifier().isEmpty()) {
        identifier = sbAnno.identifier();
    } else {
        String name = method.getName();
        if (name.endsWith("SocialBookmark")) {
            name = name.substring(0, name.length() - "SocialBookmark".length());
        }
        identifier = name;
    }
}

From source file:java2typescript.jaxrs.ServiceDescriptorGenerator.java

private List<Param> generateParams(Method method) {
    List<Param> params = new ArrayList<Param>();
    for (Annotation[] annotations : method.getParameterAnnotations()) {
        Param param = new Param();
        param.setType(BODY); // By default, in case of no annotation
        param.setName("body");
        for (Annotation annotation : annotations) {
            fillParam(annotation, param);
        }//from w  w w.j  a v  a2 s.  c om
        params.add(param);
    }
    return params;
}

From source file:org.shredzone.commons.view.manager.ViewInvoker.java

/**
 * Creates a new {@link ViewInvoker}./* w  w  w  .  j a  va  2s .c o m*/
 *
 * @param bean
 *            target Spring bean to be invoked
 * @param method
 *            target method to be invoked
 * @param conversionService
 *            {@link ConversionService} to be used for parameter conversion
 */
public ViewInvoker(Object bean, Method method, ConversionService conversionService) {
    this.bean = bean;
    this.method = method;
    this.conversionService = conversionService;

    Annotation[][] annotations = method.getParameterAnnotations();
    viewAnnotations = new Annotation[annotations.length];
    optionals = new boolean[annotations.length];

    for (int ix = 0; ix < annotations.length; ix++) {
        for (Annotation sub : annotations[ix]) {
            if (sub instanceof PathPart || sub instanceof Parameter || sub instanceof Attribute
                    || sub instanceof Cookie || sub instanceof SessionId || sub instanceof Qualifier) {
                if (viewAnnotations[ix] != null) {
                    throw new IllegalArgumentException("Conflicting annotations " + sub + " and "
                            + viewAnnotations[ix] + " in view handler " + bean.getClass().getName() + "#"
                            + method.getName() + "()");
                }
                viewAnnotations[ix] = sub;
            }

            if (sub instanceof Optional || sub instanceof SessionId || sub instanceof Qualifier) {
                optionals[ix] = true;
            }
        }
    }
}

From source file:uk.co.grahamcox.xml.XmlHandler.java

/**
 * Handle the start of an element/*from  w ww .  ja  v  a 2  s. c om*/
 * @param uri The namespace URI
 * @param localName The local name - without prefix - of the element
 * @param qNAme The qualified name - with prefix - of the element
 * @param attributes The attributes of the element
 * @throws SAXException if an error occurs
 */
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    String name = buildName(uri, localName);
    LOG.debug("Processing " + name);
    elementStack.push(name);
    for (Entry<Method, Path> entry : startElements.entrySet()) {
        if (entry.getValue().matches(elementStack)) {
            Method method = entry.getKey();
            LOG.debug("Found matching callback method: " + method);
            Class<?>[] parameterTypes = method.getParameterTypes();
            Annotation[][] parameterAnnotations = method.getParameterAnnotations();

            Object[] params = new Object[parameterTypes.length];
            for (int i = 0; i < params.length; ++i) {
                params[i] = null;
                for (Annotation annotation : parameterAnnotations[i]) {
                    if (annotation instanceof Attribute) {
                        String attribute = ((Attribute) annotation).value();
                        String value = attributes.getValue(attribute);
                        params[i] = value;
                        break;
                    }
                }
            }
            invokeCallback(method, params);
        }
    }
}

From source file:org.shredzone.cilla.web.fragment.manager.FragmentInvoker.java

/**
 * Creates a new {@link FragmentInvoker}.
 *
 * @param bean//  ww w.j a  v a2  s  . co m
 *            target Spring bean to be invoked
 * @param method
 *            target method to be invoked
 * @param template
 *            JSP template to be used for rendering, or {@code null} if none is
 *            defined
 * @param conversionService
 *            {@link ConversionService} to be used for converting
 */
public FragmentInvoker(Object bean, Method method, String template, ConversionService conversionService) {
    this.bean = bean;
    this.method = method;
    this.template = template;
    this.conversionService = conversionService;

    Annotation[][] annotations = method.getParameterAnnotations();
    expressions = new Expression[annotations.length];
    items = new boolean[annotations.length];

    ExpressionParser parser = new SpelExpressionParser();

    for (int ix = 0; ix < annotations.length; ix++) {
        for (Annotation sub : annotations[ix]) {
            if (sub instanceof FragmentValue) {
                expressions[ix] = parser.parseExpression(((FragmentValue) sub).value());
            } else if (sub instanceof FragmentItem) {
                items[ix] = true;
            }
        }
    }
}

From source file:com.feedzai.fos.server.remote.impl.RemoteInterfacesTest.java

private void testMatch(Class<?> api, Class<?> remote, int remoteFieldAdditions) {
    Method[] apiMethods = api.getMethods();
    Method[] remoteMethods = remote.getMethods();

    Arrays.sort(apiMethods, buildComparator());
    Arrays.sort(remoteMethods, buildComparator());

    // Checks if @RemoteInterface is different from the class/interface itself.
    assertNotSame(/*ww w  .  ja  v a2s  . com*/
            String.format("@RemoteInterface cannot be the same for the class name in %s", api.getSimpleName()),
            api, remote);
    // Checks if the remote implementation can be assigned to Remote (i.e. if in the hierarchy extends/implements Remote).
    assertTrue(
            String.format("'%s' does not implement '%s'", remote.getSimpleName(), Remote.class.getSimpleName()),
            Remote.class.isAssignableFrom(remote));

    assertEquals(desc(api, null, "Number of methods matches"), apiMethods.length, remoteMethods.length);

    for (int i = 0; i < apiMethods.length; i++) {
        // Check if the names match
        Method expected = apiMethods[i];
        Method actual = remoteMethods[i];

        assertEquals(desc(api, actual, "Names match"), expected.getName(), actual.getName());
        assertTrue(desc(api, actual, "Number of arguments matches"), expected.getParameterTypes().length
                - actual.getParameterAnnotations().length <= remoteFieldAdditions);

        boolean remoteOrException = false;
        for (Class klass : actual.getExceptionTypes()) {
            remoteOrException = Exception.class.equals(klass) || RemoteException.class.equals(klass);
            if (remoteOrException) {
                break;
            }
        }

        // Checks if remote implementations throw Exception or RemoteException.
        assertTrue(desc(remote, actual,
                String.format("%s does not throw either RemoteException or Exception", actual.getName())),
                remoteOrException);
    }
}

From source file:cn.webwheel.ActionSetter.java

private List<SetterInfo> parseArgs(Method method) throws IOException {
    Annotation[][] as = method.getParameterAnnotations();
    if (as.length == 0) {
        return Collections.emptyList();
    }/* ww w  . ja v  a2 s.  c  om*/
    String[] names = MethodParameterNames.lookup(method);
    if (names == null || names.length != as.length) {
        names = new String[as.length];
    }
    for (int i = 0; i < names.length; i++) {
        for (int j = 0; j < as[i].length; j++) {
            if (as[i][j] instanceof WebParam) {
                String v = ((WebParam) as[i][j]).value();
                if (!v.isEmpty()) {
                    names[i] = v;
                    break;
                }
            }
        }
        if (names[i] == null) {
            logger.severe("need WebParam at argument[" + i + "] in " + method);
            names[i] = "arg" + i;
        }
        if (method.getParameterTypes()[i].isArray()) {
            if (names[i] != null)
                names[i] += "[]";
        }
    }
    List<SetterInfo> list = new ArrayList<SetterInfo>();
    for (int i = 0; i < names.length; i++) {
        SetterInfo si = new SetterInfo();
        list.add(si);
        si.paramName = names[i];
        JsonProperty jsp = null;
        for (Annotation a : as[i]) {
            if (a instanceof JsonProperty) {
                jsp = (JsonProperty) a;
                break;
            }
        }
        if (jsp != null) {
            si.setter = new JSonSetter(method.getGenericParameterTypes()[i]);
            continue;
        }
        si.setter = typeSetterMap.get(method.getGenericParameterTypes()[i]);
        if (si.setter != null) {
            continue;
        }
        si.setter = BeanSetter.create(method.getParameterTypes()[i], this);
        if (si.setter != null) {
            continue;
        }
        logger.severe("can not find setter at argument[" + i + "] in " + method);
        si.setter = new DefaultValueSetter(method.getParameterTypes()[i]);
    }
    return list;
}

From source file:com.netflix.hystrix.contrib.javanica.cache.CacheInvocationContext.java

/**
 * Constructor to create CacheInvocationContext based on passed parameters.
 *
 * @param cacheAnnotation the caching annotation, like {@link com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult}
 * @param cacheKeyMethod  the method to generate cache key
 * @param target          the current instance of intercepted method
 * @param method          the method annotated with on of caching annotations
 * @param args            the method arguments
 *///  w w  w . j  av a 2s.  c  o m
public CacheInvocationContext(A cacheAnnotation, MethodExecutionAction cacheKeyMethod, Object target,
        Method method, Object... args) {
    this.method = method;
    this.target = target;
    this.cacheKeyMethod = cacheKeyMethod;
    this.cacheAnnotation = cacheAnnotation;
    Class<?>[] parametersTypes = method.getParameterTypes();
    Annotation[][] parametersAnnotations = method.getParameterAnnotations();
    int parameterCount = parametersTypes.length;
    if (parameterCount > 0) {
        ImmutableList.Builder<CacheInvocationParameter> parametersBuilder = ImmutableList.builder();
        for (int pos = 0; pos < parameterCount; pos++) {
            Class<?> paramType = parametersTypes[pos];
            Object val = args[pos];
            parametersBuilder
                    .add(new CacheInvocationParameter(paramType, val, parametersAnnotations[pos], pos));
        }
        parameters = parametersBuilder.build();
        // get key parameters
        Iterable<CacheInvocationParameter> filtered = Iterables.filter(parameters,
                new Predicate<CacheInvocationParameter>() {
                    @Override
                    public boolean apply(CacheInvocationParameter input) {
                        return input.hasCacheKeyAnnotation();
                    }
                });
        if (filtered.iterator().hasNext()) {
            keyParameters = ImmutableList.<CacheInvocationParameter>builder().addAll(filtered).build();
        } else {
            keyParameters = parameters;
        }
    }
}