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:com.expedia.seiso.web.controller.delegate.RepoSearchDelegate.java

private Object getResult(Class<?> itemClass, Method searchMethod, Pageable pageable,
        MultiValueMap<String, String> params) {

    val searchMethodName = searchMethod.getName();
    log.trace("Finding {} using method {}", itemClass.getSimpleName(), searchMethodName);
    val repo = repositories.getRepositoryFor(itemClass);
    val paramClasses = searchMethod.getParameterTypes();
    val allAnns = searchMethod.getParameterAnnotations();
    val paramVals = new Object[paramClasses.length];

    for (int i = 0; i < paramClasses.length; i++) {
        log.trace("Processing param {}", i);
        if (paramClasses[i] == Pageable.class) {
            paramVals[i] = pageable;/* w w w .j av  a 2s  .  c o m*/
        } else {
            val currentAnns = allAnns[i];
            for (val currentAnn : currentAnns) {
                if (Param.class.equals(currentAnn.annotationType())) {
                    log.trace("Found @Param");
                    if (conversionService.canConvert(String.class, paramClasses[i])) {
                        val paramAnn = (Param) currentAnn;
                        val paramName = paramAnn.value();
                        val paramValAsStr = params.getFirst(paramName);
                        log.trace("Setting param: {}={}", paramName, paramValAsStr);
                        paramVals[i] = conversionService.convert(paramValAsStr, paramClasses[i]);
                    } else {
                        log.trace("BUG! Not setting the param value!");
                    }
                }
            }
        }
    }

    log.trace("Invoking {}.{} with {} params", repo.getClass().getName(), searchMethodName, paramVals.length);
    return ReflectionUtils.invokeMethod(searchMethod, repo, paramVals);
}

From source file:org.lunarray.model.descriptor.builder.annotation.resolver.parameter.def.DefaultParameterResolverStrategy.java

/**
 * Process parameter.//from w  w  w .  j  a  v  a2s .c  o  m
 * 
 * @param index
 *            The parameter index.
 * @param type
 *            The parameter type.
 * @param primary
 *            The primary declaring method.
 * @param operation
 *            The operation.
 * @return The described parameter.
 * @param <P>
 *            The parameter type.
 */
private <P> DescribedParameter<P> process(final int index, final Class<P> type, final Method primary,
        final DescribedOperation operation) {
    final ParameterBuilder<P> builder = DescribedParameter.createBuilder();
    // Base attributes.
    builder.index(index).parameterType(type).entityType(primary.getDeclaringClass());
    // Generic type.
    builder.genericType(primary.getGenericParameterTypes()[index]).operation(operation);
    // Process annotations.
    for (final Annotation annotation : primary.getParameterAnnotations()[index]) {
        builder.addAnnotation(annotation);
    }
    for (final Method m : operation.getMatches()) {
        for (final Annotation annotation : m.getParameterAnnotations()[index]) {
            builder.addAnnotation(annotation);
        }
    }
    return builder.buildDescribed();
}

From source file:io.dyn.core.handler.AnnotationHandlerMethodResolver.java

@Override
public Map<Object, HandlerMethod> resolve(Class<?> aClass, Object... args) {
    final Map<Object, HandlerMethod> handlerMethods = new HashMap<>();
    //log.debug("Finding handler methods in %s", aClass);
    Class<?> clazz = aClass;
    while (null != clazz && clazz != Object.class) {
        ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
            @Override/*  ww  w  .jav a 2s .  com*/
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

                Class<?>[] paramTypes = method.getParameterTypes();
                String[] paramNames = PARAMETER_NAME_DISCOVERER.getParameterNames(method);
                HandlerMethodArgument[] handlerMethodArgs = new HandlerMethodArgument[paramTypes.length];
                Annotation[][] paramAnnos = method.getParameterAnnotations();
                Expression[] valueExpressions = new Expression[paramTypes.length];
                for (int i = 0; i < paramTypes.length; i++) {
                    String paramName = (null != paramNames ? paramNames[i] : "arg" + i);
                    if (paramAnnos[i].length > 0) {
                        for (int j = 0; j < paramAnnos[i].length; j++) {
                            if (paramAnnos[i][j] instanceof Value) {
                                valueExpressions[i] = SpelExpression.DEFAULT_PARSER
                                        .parseExpression(((Value) paramAnnos[i][j]).value());
                                break;
                            }
                        }
                    }
                    handlerMethodArgs[i] = new HandlerMethodArgument(i, paramName, paramTypes[i],
                            valueExpressions[i]);
                }

                Guard guard = null;
                When when = Handlers.find(When.class, method);
                if (null != when) {
                    guard = new Guard(SpelExpression.DEFAULT_PARSER.parseExpression(when.value()));
                }

                On on = Handlers.find(On.class, method);
                String eventName = Handlers.findEventName(method);
                if (null != eventName) {
                    Object key = eventName;
                    if (eventName.contains("#{")) {
                        key = SpelExpression.DEFAULT_PARSER.parseExpression(eventName,
                                ParserContext.TEMPLATE_EXPRESSION);
                    }
                    handlerMethods.put(key, new HandlerMethod(method, handlerMethodArgs, guard));

                }
            }
        }, Handlers.USER_METHODS);
        clazz = clazz.getSuperclass();
    }
    return (handlerMethods.size() > 0 ? handlerMethods : null);
}

From source file:org.eclipse.scada.configuration.recipe.lib.internal.DefaultExecutableFactory.java

protected Object[] makeArgs(final Method m, final RunnerContext localContext) {
    final Object[] args = new Object[m.getParameterTypes().length];

    for (int i = 0; i < m.getParameterTypes().length; i++) {
        final Annotation[] an = m.getParameterAnnotations()[i];

        final boolean optional = isOptional(an);

        final String name = makeName(an);
        if (name != null) {
            args[i] = localContext.getMap().get(name);
        } else {//w  ww.  j  a  v  a 2 s  .  com
            final Set<Object> values = new HashSet<>(localContext.getMap().values());
            values.add(localContext);

            final Class<?> type = m.getParameterTypes()[i];
            args[i] = findForType(values, type, i, m.getName(), m.getDeclaringClass(), optional);
        }
    }

    return args;
}

From source file:cn.guoyukun.spring.jpa.web.bind.method.annotation.PageableMethodArgumentResolver.java

/**
 * Asserts uniqueness of all {@link Pageable} parameters of the method of the given {@link MethodParameter}.
 *
 * @param parameter/*from w  w  w  . j  a v a2 s  .  co m*/
 */
private void assertPageableUniqueness(MethodParameter parameter) {

    Method method = parameter.getMethod();

    if (containsMoreThanOnePageableParameter(method)) {
        Annotation[][] annotations = method.getParameterAnnotations();
        assertQualifiersFor(method.getParameterTypes(), annotations);
    }
}

From source file:pl.bristleback.server.bristle.conf.resolver.action.ActionResolver.java

public ActionInformation prepareActionInformation(Class<?> clazz, Method action) {
    ActionInformation actionInformation = prepareAction(clazz, action);

    List<ActionParameterInformation> parameters = new ArrayList<ActionParameterInformation>();
    for (int i = 0; i < action.getParameterTypes().length; i++) {
        Type parameterType = action.getGenericParameterTypes()[i];
        ActionParameterInformation parameterInformation = parametersResolver
                .prepareActionParameter(parameterType, action.getParameterAnnotations()[i]);
        parameters.add(parameterInformation);
    }//from ww w.jav  a 2 s.  c o  m
    actionInformation.setParameters(parameters);
    ActionResponseInformation responseInformation = responseResolver.resolveResponse(action);
    actionInformation.setResponseInformation(responseInformation);
    return actionInformation;
}

From source file:org.ocelotds.core.services.ArgumentConvertorTest.java

@Test(expected = JsonUnmarshallingException.class)
public void testConvertJsonToJavaBadUnmarshaller() throws DataServiceException, JsonUnmarshallingException,
        JsonMarshallerException, NoSuchMethodException {
    System.out.println("convertJsonToJavaBadUnmarshaller");

    Method method = ClassAsDataService.class.getMethod("methodWithBadUnmarshaller", String.class);
    when(argumentServices.getIJsonMarshallerInstance(any(Class.class)))
            .thenThrow(JsonUnmarshallingException.class);
    Annotation[] annotations = method.getParameterAnnotations()[0];
    instance.convertJsonToJava("", null, annotations);
}

From source file:org.apache.geode.management.internal.cli.help.Helper.java

/**
 * get help string for a specific command, or a brief description of all the commands if buffer is
 * null or empty//from   w w  w  .jav  a 2 s  .c  om
 */
public String getHelp(String buffer, int terminalWidth) {
    if (StringUtils.isBlank(buffer)) {
        return getHelp().toString(terminalWidth);
    }

    Method method = commands.get(buffer);
    if (method == null) {
        return "no help exists for this command.";
    }

    HelpBlock helpBlock = getHelp(method.getDeclaredAnnotation(CliCommand.class),
            method.getParameterAnnotations(), method.getParameterTypes());
    return helpBlock.toString(terminalWidth);
}

From source file:io.cloudslang.lang.runtime.steps.ActionSteps.java

protected Object[] resolveActionArguments(Map<String, SerializableSessionObject> serializableSessionData,
        Method actionMethod, Map<String, Serializable> currentContext,
        Map<String, Object> nonSerializableExecutionData) {
    List<Object> args = new ArrayList<>();

    int index = 0;
    Class[] parameterTypes = actionMethod.getParameterTypes();
    for (Annotation[] annotations : actionMethod.getParameterAnnotations()) {
        index++;/*from   w  w w .  java 2 s .  co m*/
        for (Annotation annotation : annotations) {
            if (annotation instanceof Param) {
                if (parameterTypes[index - 1].equals(GlobalSessionObject.class)) {
                    handleNonSerializableSessionContextArgument(nonSerializableExecutionData, args,
                            (Param) annotation);
                } else if (parameterTypes[index - 1].equals(SerializableSessionObject.class)) {
                    handleSerializableSessionContextArgument(serializableSessionData, args, (Param) annotation);
                } else {
                    String parameterName = ((Param) annotation).value();
                    Serializable value = currentContext.get(parameterName);
                    Class parameterClass = parameterTypes[index - 1];
                    if (parameterClass.isInstance(value) || value == null) {
                        args.add(value);
                    } else {
                        StringBuilder exceptionMessageBuilder = new StringBuilder();
                        exceptionMessageBuilder.append("Parameter type mismatch for action ");
                        exceptionMessageBuilder.append(actionMethod.getName());
                        exceptionMessageBuilder.append(" of class ");
                        exceptionMessageBuilder.append(actionMethod.getDeclaringClass().getName());
                        exceptionMessageBuilder.append(". Parameter ");
                        exceptionMessageBuilder.append(parameterName);
                        exceptionMessageBuilder.append(" expects type ");
                        exceptionMessageBuilder.append(parameterClass.getName());
                        throw new RuntimeException(exceptionMessageBuilder.toString());
                    }
                }
            }
        }
        if (args.size() != index) {
            throw new RuntimeException("All action arguments should be annotated with @Param");
        }
    }
    return args.toArray(new Object[args.size()]);
}

From source file:org.lansir.beautifulgirls.proxy.ProxyInvocationHandler.java

/** 
 * Dynamic proxy invoke//from   ww  w  .  j av a2s .  c om
 */
public Object invoke(Object proxy, Method method, Object[] args)
        throws AkInvokeException, AkServerStatusException, AkException, Exception {
    AkPOST akPost = method.getAnnotation(AkPOST.class);
    AkGET akGet = method.getAnnotation(AkGET.class);

    AkAPI akApi = method.getAnnotation(AkAPI.class);
    Annotation[][] annosArr = method.getParameterAnnotations();
    String invokeUrl = akApi.url();
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

    // AkApiParams to hashmap, filter out of null-value
    HashMap<String, File> filesToSend = new HashMap<String, File>();
    HashMap<String, String> paramsMapOri = new HashMap<String, String>();
    HashMap<String, String> paramsMap = getRawApiParams2HashMap(annosArr, args, filesToSend, paramsMapOri);
    // Record this invocation
    ApiInvokeInfo apiInvokeInfo = new ApiInvokeInfo();
    apiInvokeInfo.apiName = method.getName();
    apiInvokeInfo.paramsMap.putAll(paramsMap);
    apiInvokeInfo.url = invokeUrl;
    // parse '{}'s in url
    invokeUrl = parseUrlbyParams(invokeUrl, paramsMap);
    // cleared hashmap to params, and filter out of the null value
    Iterator<Entry<String, String>> iter = paramsMap.entrySet().iterator();
    while (iter.hasNext()) {
        Entry<String, String> entry = iter.next();
        params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }

    // get the signature string if using
    AkSignature akSig = method.getAnnotation(AkSignature.class);
    if (akSig != null) {
        Class<?> clazzSignature = akSig.using();
        if (clazzSignature.getInterfaces().length > 0 // TODO: NEED VERIFY WHEN I HAVE TIME
                && InvokeSignature.class.getName().equals(clazzSignature.getInterfaces()[0].getName())) {
            InvokeSignature is = (InvokeSignature) clazzSignature.getConstructors()[0].newInstance();
            String sigValue = is.signature(akSig, invokeUrl, params, paramsMapOri);
            String sigParamName = is.getSignatureParamName();
            if (sigValue != null && sigParamName != null && sigValue.length() > 0
                    && sigParamName.length() > 0) {
                params.add(new BasicNameValuePair(sigParamName, sigValue));
            }
        }
    }

    // choose POST GET PUT DELETE to use for this invoke
    String retString = "";
    if (akGet != null) {
        StringBuilder sbUrl = new StringBuilder(invokeUrl);
        if (!(invokeUrl.endsWith("?") || invokeUrl.endsWith("&"))) {
            sbUrl.append("?");
        }
        for (NameValuePair nvp : params) {
            sbUrl.append(nvp.getName());
            sbUrl.append("=");
            sbUrl.append(nvp.getValue());
            sbUrl.append("&");
        } // now default using UTF-8, maybe improved later
        retString = HttpInvoker.get(sbUrl.toString());
    } else if (akPost != null) {
        if (filesToSend.isEmpty()) {
            retString = HttpInvoker.post(invokeUrl, params);
        } else {
            retString = HttpInvoker.postWithFilesUsingURLConnection(invokeUrl, params, filesToSend);
        }
    } else { // use POST for default
        retString = HttpInvoker.post(invokeUrl, params);
    }

    // invoked, then add to history
    //ApiStats.addApiInvocation(apiInvokeInfo);

    //Log.d(TAG, retString);

    // parse the return-string
    Class<?> returnType = method.getReturnType();
    try {
        if (String.class.equals(returnType)) { // the result return raw string
            return retString;
        } else { // return object using json decode
            return JsonMapper.json2pojo(retString, returnType);
        }
    } catch (IOException e) {
        throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, e.getMessage(), e);
    }
    /*
     * also can use gson like this eg. 
     *  Gson gson = new Gson();
     *  return gson.fromJson(HttpInvoker.post(url, params), returnType);
     */
}