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.jayway.jaxrs.hateoas.DefaultHateoasContext.java

private LinkableParameterInfo[] extractMethodParameterInfo(Method method) {
    List<LinkableParameterInfo> parameterInfoList = new LinkedList<LinkableParameterInfo>();
    Class<?>[] parameterTypes = method.getParameterTypes();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    for (int i = 0; i < parameterTypes.length; i++) {
        Annotation[] annotations = parameterAnnotations[i];

        String parameterName = null;
        String defaultValue = null;

        for (Annotation annotation : annotations) {
            if (annotation instanceof QueryParam) {
                parameterName = ((QueryParam) annotation).value();
            }//ww  w.j a  v a2  s.c  o  m
            if (annotation instanceof DefaultValue) {
                defaultValue = ((DefaultValue) annotation).value();
            }
        }

        if (parameterName != null) {
            logger.debug("Found QueryParam: {}", parameterName);

            parameterInfoList.add(new LinkableParameterInfo(parameterName, defaultValue));
        }
        if (defaultValue != null) {
            logger.debug("Found DefaultValue: {}", defaultValue);
        }
    }
    return parameterInfoList.toArray(new LinkableParameterInfo[0]);
}

From source file:org.synyx.hades.dao.query.Parameters.java

/**
 * Creates a new instance of {@link Parameters}.
 * //from   w ww.j av  a2  s.c  o  m
 * @param method
 */
public Parameters(Method method) {

    Assert.notNull(method);

    this.parameters = new ArrayList<Parameter>();

    List<Class<?>> types = Arrays.asList(method.getParameterTypes());
    Annotation[][] annotations = method.getParameterAnnotations();

    for (int i = 0; i < types.size(); i++) {
        parameters.add(new Parameter(types.get(i), annotations[i], this, i));
    }

    this.pageableIndex = types.indexOf(Pageable.class);
    this.sortIndex = types.indexOf(Sort.class);

    assertEitherAllParamAnnotatedOrNone();
}

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

/**
 * Creates a GfshParseResult instance to represent parsing outcome.
 * //from  w w w  .  jav a  2  s .c o m
 * @param method Method associated with the command
 * @param instance Instance on which this method has to be executed
 * @param arguments arguments of the method
 * @param userInput user specified commands string
 */
protected GfshParseResult(final Method method, final Object instance, final Object[] arguments,
        final String userInput) {
    super(method, instance, arguments);
    this.userInput = userInput.trim();

    CliCommand cliCommand = method.getAnnotation(CliCommand.class);
    commandName = cliCommand.value()[0];

    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    if (arguments == null) {
        return;
    }

    for (int i = 0; i < arguments.length; i++) {
        Object argument = arguments[i];
        if (argument == null) {
            continue;
        }

        CliOption cliOption = getCliOption(parameterAnnotations, i);

        String argumentAsString;
        if (argument instanceof Object[]) {
            argumentAsString = StringUtils.join((Object[]) argument, ",");
        } else {
            argumentAsString = argument.toString();
        }

        // this maps are used for easy access of option values in String form.
        // It's used in tests and validation of option values in pre-execution
        paramValueStringMap.put(cliOption.key()[0], argumentAsString);
    }
}

From source file:eu.tripledframework.eventstore.infrastructure.ReflectionObjectConstructor.java

private void applyDomainEvent(T instance, DomainEvent event) {
    Method method = getEventHandlerMethods(event);
    if (method == null) {
        throw new AggregateRootReconstructionException(
                String.format("Could not find a suitable method for event %s", event));
    }// w ww .j ava2  s .  c  o m
    try {
        method.setAccessible(true);
        Object[] parameters = getParametersValues(method.getParameterAnnotations(), event);
        method.invoke(instance, parameters);
        LOGGER.debug("Applied {}", event);
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new AggregateRootReconstructionException(
                String.format("Could not apply event %s to instance %s", event, instance), e);
    }
}

From source file:net.projectmonkey.spring.acl.enhancement.identity.strategy.method.DefaultMethodInvocationObjectIdRetrievalStrategy.java

/**
 * Extension Point: Locate the secure object mapping from the method invocation.
 * This is the main purpose of the class so overriding this allows users to move
 * completely away from the {@link SecuredAgainst} and {@link SecuredId} annotations. 
 * @param invocation//from   w  ww . j a va 2s  . com
 * @return
 */
protected SecureObjectMapping locateSecureObjectMapping(final MethodInvocation invocation) {
    SecureObjectMapping matchingSecuredIdParamValue = null;
    SecureObjectMapping matchingAssignable = null;

    Method method = invocation.getMethod();
    Class<?> securedClass = resolveSecuredClass(method);

    Class<?>[] parameterTypes = method.getParameterTypes();
    Object[] arguments = invocation.getArguments();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    if (arguments.length == 1) {
        Object argument = arguments[0];
        Annotation[] annotations = parameterAnnotations[0];
        SecuredId parameterAnnotation = locateAnnotation(annotations);
        String internalMethod = this.internalMethod;
        if (parameterAnnotation != null) {
            internalMethod = resolveInternalMethod(parameterAnnotation);
        }
        matchingSecuredIdParamValue = new SecureObjectMappingWithInternalMethod(argument, securedClass,
                internalMethod);
    } else {
        for (int i = 0; i < arguments.length && matchingSecuredIdParamValue == null; i++) {
            Object argument = arguments[i];

            Annotation[] annotations = parameterAnnotations[i];
            SecuredId parameterAnnotation = locateAnnotation(annotations);
            if (parameterAnnotation != null) {
                String internalMethod = resolveInternalMethod(parameterAnnotation);
                matchingSecuredIdParamValue = new SecureObjectMappingWithInternalMethod(argument, securedClass,
                        internalMethod);
                break; // we've found a parameter which specifies it provides the id, so break;
            }

            Class<?> parameterType = parameterTypes[i];

            if (matchingAssignable == null && securedClass.isAssignableFrom(parameterType)) {
                //here we use the actual argument type as the secured class since we are an instance of the required type.
                matchingAssignable = new SecureObjectMappingWithInternalMethod(argument, internalMethod);
            }
        }

    }
    return firstNonNull(matchingSecuredIdParamValue, matchingAssignable);
}

From source file:org.bigmouth.nvwa.zookeeper.concurrent.spring.SynchronousAdvisor.java

private String getPath(Method method, Object[] args) {
    String path = null;//ww  w  . j  a v  a  2 s .co m
    if (method.isAnnotationPresent(SynchronousSupport.class)) {
        SynchronousSupport annotation = method.getAnnotation(SynchronousSupport.class);
        String zkPath = annotation.zkPath();
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        String primaryKey = getPrimaryKey(args, parameterAnnotations);
        if (StringUtils.isNotBlank(primaryKey)) {
            path = getPath(zkPath, primaryKey);
            PathUtils.validatePath(path);
        }
    }
    return path;
}

From source file:corner.cache.services.impl.CacheableDefinitionParserImpl.java

/**
 * @see corner.cache.services.CacheableDefinitionParser#parseAsKey(org.apache.tapestry5.ioc.Invocation, java.lang.reflect.Method, corner.cache.services.CacheManager)
 *///  w ww. j a  va2s.c  om
@Override
public String parseAsKey(Invocation invocation, Method method) {
    Cacheable cacheable = method.getAnnotation(Cacheable.class);
    if (cacheable == null) {
        return null;
    }
    Definition define = null;
    //if (define == null) { // ?
    Builder defineBuilder = CacheableDefine.Definition.newBuilder();
    Annotation[][] parametersAnnotations = method.getParameterAnnotations();
    for (int i = 0; i < parametersAnnotations.length; i++) {
        Annotation[] pa = parametersAnnotations[i];
        for (Annotation a : pa) {
            if (a instanceof CacheKeyParameter) {
                defineBuilder.addParameterIndex(i);
            }
        }
    }
    define = defineBuilder.build();

    // ?
    List<String> keyParameter = new ArrayList<String>();
    Object pObj;
    Class pType;
    for (int i = 0; i < define.getParameterIndexCount(); i++) {
        int pIndex = define.getParameterIndex(i);
        pObj = invocation.getParameter(pIndex);
        pType = null;
        if (pObj != null) {
            pType = entityService.getEntityClass(pObj);
        }
        if (pType == null) {
            pType = method.getParameterTypes()[pIndex];
        }
        ValueEncoder encoder = valueEncoderSource.getValueEncoder(pType);
        keyParameter.add(encoder.toClient(pObj));
    }
    //key
    String key = null;
    String keyFormat = cacheable.keyFormat();
    logger.debug("key parameter:{}", keyParameter);
    if (!StringUtils.hasText(keyFormat)) {
        key = DigestUtils.shaHex(method.toString() + keyParameter.toString());
    } else {
        key = String.format(keyFormat, keyParameter.toArray(new Object[0]));
    }

    CacheStrategy strategy = this.source.findStrategy(cacheable.strategy());
    CacheNsParameter[] nses = cacheable.namespaces();
    if (strategy == null) {
        throw new RuntimeException("fail to find cache strategy instance!");
    }
    return strategy.appendNamespace(cacheManager, cacheable.clazz(), nses, key, keyParameter.toArray());
}

From source file:com.sinosoft.one.data.jade.statement.StatementMetaData.java

public StatementMetaData(DAOMetaData daoMetaData, Method method, String sqlQuerie) {
    this.daoMetaData = daoMetaData;
    this.method = method;
    this.sql = method.getAnnotation(SQL.class) == null ? sqlQuerie : method.getAnnotation(SQL.class).value();

    this.genericReturnTypes = GenericUtils.getActualClass(method.getGenericReturnType());

    Annotation[][] annotations = method.getParameterAnnotations();
    this.parameterCount = annotations.length;
    this.sqlParams = new Param[annotations.length];
    int shardByIndex = -1;
    for (int index = 0; index < annotations.length; index++) {
        for (Annotation annotation : annotations[index]) {
            if (annotation instanceof ShardBy) {
                if (shardByIndex >= 0) {
                    throw new IllegalArgumentException("duplicated @" + ShardBy.class.getName());
                }/*w  ww .j av  a2  s . c  o m*/
                shardByIndex = index;
            } else if (annotation instanceof Param) {
                this.sqlParams[index] = (Param) annotation;
            }
        }
    }
    this.shardByIndex = shardByIndex;
}

From source file:org.akita.proxy.ProxyInvocationHandler.java

/** 
 * Dynamic proxy invoke//from ww  w  . j  av a  2  s  .  c o m
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    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(paramsMapOri);
    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
    final 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 (Exception e) {
        Log.e(TAG, retString, e); // log can print the error return-string
        throw new AkInvokeException(AkInvokeException.CODE_JSONPROCESS_EXCEPTION, e.getMessage(), e);
    }
}

From source file:org.apache.falcon.resource.channel.HTTPChannel.java

private String pathValue(Method method, Object... args) throws FalconException {

    Path pathParam = method.getAnnotation(Path.class);
    if (pathParam == null) {
        throw new FalconException("No path param mentioned for " + method);
    }/*from  w w w . ja  va  2  s. c  o  m*/
    String pathValue = pathParam.value();

    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    StringBuilder queryString = new StringBuilder("?");
    for (int index = 0; index < args.length; index++) {
        if (args[index] instanceof String || args[index] instanceof Boolean || args[index] instanceof Integer) {
            String arg = String.valueOf(args[index]);
            for (int annotation = 0; annotation < paramAnnotations[index].length; annotation++) {
                Annotation paramAnnotation = paramAnnotations[index][annotation];
                String annotationClass = paramAnnotation.annotationType().getName();

                if (annotationClass.equals(QueryParam.class.getName())) {
                    queryString.append(getAnnotationValue(paramAnnotation, "value")).append('=').append(arg)
                            .append("&");
                } else if (annotationClass.equals(PathParam.class.getName())) {
                    pathValue = pathValue.replace("{" + getAnnotationValue(paramAnnotation, "value") + "}",
                            arg);
                }
            }
        }
    }
    return pathValue + queryString.toString();
}