Example usage for java.lang.reflect Method getAnnotation

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

Introduction

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

Prototype

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) 

Source Link

Usage

From source file:com.zxy.commons.mybatis.SelectDataSourceAspect.java

/**
 * ?key//from  w  w w  .  j  av a2 s.  com
 * 
 * @param point JoinPoint
*/
@Before("aspect()")
public void before(JoinPoint point) {
    Object target = point.getTarget();
    String method = point.getSignature().getName();
    //        Class<?>[] classz = target.getClass().getInterfaces();
    Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
    try {
        Method mt = target.getClass().getMethod(method, parameterTypes);
        //            logger.info("mt.getName={}", mt.getName());
        if (mt != null && mt.isAnnotationPresent(SelectDataSource.class)) {
            SelectDataSource data = mt.getAnnotation(SelectDataSource.class);
            HandleDataSource.putDataSource(data.value());
        } else {
            HandleDataSource.clearCustomerType();
        }
        //logger.info("method.name={}, datasource.key={}", m.getName(), HandleDataSource.getDataSource());
    } catch (Exception e) {
        logger.error("before() error.", e);
        HandleDataSource.clearCustomerType();
    }
}

From source file:com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCollapserAspect.java

@Around("hystrixCollapserAnnotationPointcut()")
public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {
    HystrixCollapser hystrixCollapser;/*  w  ww.  j  av  a  2  s  .  com*/
    Method collapserMethod = getMethodFromTarget(joinPoint);
    Object obj = joinPoint.getTarget();
    Object[] args = joinPoint.getArgs();

    Validate.notNull(collapserMethod, "failed to get collapser method from joinPoint: %s", joinPoint);
    hystrixCollapser = collapserMethod.getAnnotation(HystrixCollapser.class);

    Method commandMethod = getMethodFromTarget(joinPoint, hystrixCollapser.commandMethod());
    ExecutionType collapserExecutionType = ExecutionType.getExecutionType(collapserMethod.getReturnType());
    ExecutionType commandExecutionType = ExecutionType.getExecutionType(commandMethod.getReturnType());
    Closure closure = ClosureFactoryRegistry.getFactory(commandExecutionType).createClosure(commandMethod, obj,
            args);

    HystrixCommand hystrixCommand = commandMethod.getAnnotation(HystrixCommand.class);
    Validate.notNull(hystrixCommand,
            "collapser cannot refer to the '' method which wasn't annotated with @HystrixCommand");

    MetaHolder metaHolder = MetaHolder.builder().args(args).method(commandMethod).obj(obj).closure(closure)
            .executionType(commandExecutionType).hystrixCollapser(hystrixCollapser)
            .hystrixCommand(hystrixCommand).defaultCommandKey(commandMethod.getName())
            .defaultCollapserKey(collapserMethod.getName()).defaultGroupKey(obj.getClass().getSimpleName())
            .build();
    CommandCollapser commandCollapser = new CommandCollapser(metaHolder);
    return CommandExecutor.execute(commandCollapser, collapserExecutionType);
}

From source file:koper.aop.AbstractSendMessageAdvice.java

/**
 * Get after Topic Name on Method// ww  w . j a  va 2 s.c o m
 * @param pjp
 * @return
 * @throws NoSuchMethodException
 */
protected String getAfterSendMsgTopicOnMethod(Method method) throws NoSuchMethodException {
    SendMessageAfter sendMsgannotation = method.getAnnotation(SendMessageAfter.class);
    String topic = sendMsgannotation != null ? sendMsgannotation.topic() : null;

    if (topic == null) {
        topic = buildTopicName(method);
        topic = fixTopicName(topic);
    }

    return topic;
}

From source file:koper.aop.AbstractSendMessageAdvice.java

/**
 * Get before Topic Name on Method/*from  w ww. ja va  2  s  .  c  om*/
 * @param pjp
 * @return
 * @throws NoSuchMethodException
 */
protected String getBeforeSendMsgTopicOnMethod(Method method) throws NoSuchMethodException {
    SendMessageBefore sendMsgannotation = method.getAnnotation(SendMessageBefore.class);
    String topic = sendMsgannotation != null ? sendMsgannotation.topic() : null;

    if (topic == null) {
        topic = buildTopicName(method);
        topic = fixTopicName(topic);
    }

    return topic;
}

From source file:candr.yoclip.option.OptionPropertiesSetterTest.java

@Test(expected = OptionsBadNameException.class)
public void initWithNoName() throws NoSuchMethodException {
    final Method setter = TestCase.class.getDeclaredMethod("setWithoutPropertyName", String.class,
            String.class);
    final OptionProperties optionProperties = setter.getAnnotation(OptionProperties.class);
    new OptionPropertiesSetter<TestCase>(optionProperties, setter);
}

From source file:net.firejack.platform.core.validation.LengthProcessor.java

@Override
public List<ValidationMessage> validate(Method readMethod, String property, Object value, ValidationMode mode)
        throws RuleValidationException {
    List<ValidationMessage> validationMessages = new ArrayList<ValidationMessage>();
    Annotation annotation = readMethod.getAnnotation(Length.class);
    if (annotation != null) {
        Length length = (Length) annotation;
        if (length.minLength() > length.maxLength()) {
            throw new ImproperValidationArgumentException("Min value should be equal or less then max value.");
        }/*ww  w.j  a  v a2s. c  o  m*/
        boolean validate = ArrayUtils.contains(length.modes(), mode);
        if (validate) {
            Class<?> returnType = readMethod.getReturnType();
            if (returnType == String.class) {
                String sValue = (String) value;
                String parameterName = StringUtils.isNotBlank(length.parameterName()) ? length.parameterName()
                        : property;
                if ((StringUtils.isBlank(sValue) && length.minLength() > 0)
                        || (StringUtils.isNotBlank(sValue) && sValue.length() < length.minLength())) {
                    validationMessages.add(new ValidationMessage(property, length.minLengthMsgKey(),
                            parameterName, length.minLength()));
                }
                if (StringUtils.isNotBlank(sValue) && sValue.length() > length.maxLength()) {
                    validationMessages.add(new ValidationMessage(property, length.maxLengthMsgKey(),
                            parameterName, length.maxLength()));
                }
            } else {
                throw new ImproperValidationArgumentException("Argument should be of type java.lang.String");
            }
        }
    }
    return validationMessages;
}

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

/** 
 * Dynamic proxy invoke/*from ww w  .  j  a va  2 s. co  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:com.vilt.minium.impl.BaseWebElementsImpl.java

private boolean isAsyncMethod(Method method) {
    return method.getAnnotation(Async.class) != null;
}

From source file:org.flite.cach3.aop.UpdateAssignCacheAdvice.java

private void doUpdate(final JoinPoint jp, final Object retVal) throws Throwable {
    // If we've disabled the caching programmatically (or via properties file) just flow through.
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return;//from  w  ww .  j a v a2s . c  o  m
    }

    final MemcachedClientIF cache = getMemcachedClient();
    final Method methodToCache = getMethodToCache(jp);
    List<UpdateAssignCache> lAnnotations;

    if (methodToCache.getAnnotation(UpdateAssignCache.class) != null) {
        lAnnotations = Arrays.asList(methodToCache.getAnnotation(UpdateAssignCache.class));
    } else {
        lAnnotations = Arrays.asList(methodToCache.getAnnotation(UpdateAssignCaches.class).value());
    }

    for (int i = 0; i < lAnnotations.size(); i++) {
        try {
            // This is injected caching.  If anything goes wrong in the caching, LOG the crap outta it,
            // but do not let it surface up past the AOP injection itself.

            final AnnotationInfo info = getAnnotationInfo(lAnnotations.get(i), methodToCache.getName(),
                    getJitterDefault());
            final String cacheKey = buildCacheKey(info.getAsString(AType.ASSIGN_KEY),
                    info.getAsString(AType.NAMESPACE), info.getAsString(AType.KEY_PREFIX));
            final int dataIndex = info.getAsInteger(AType.DATA_INDEX, -2).intValue();
            final Object dataObject = dataIndex == -1 ? retVal
                    : getIndexObject(dataIndex, jp.getArgs(), methodToCache.toString());
            final Object submission = (dataObject == null) ? new PertinentNegativeNull() : dataObject;
            cache.set(cacheKey, info.getAsInteger(AType.JITTER), submission);

            // Notify the observers that a cache interaction happened.
            final List<UpdateAssignCacheListener> listeners = getPertinentListeners(
                    UpdateAssignCacheListener.class, info.getAsString(AType.NAMESPACE));
            if (listeners != null && !listeners.isEmpty()) {
                for (final UpdateAssignCacheListener listener : listeners) {
                    try {
                        listener.triggeredUpdateAssignCache(info.getAsString(AType.NAMESPACE),
                                info.getAsString(AType.ASSIGN_KEY), dataObject, retVal, jp.getArgs());
                    } catch (Exception ex) {
                        LOG.warn("Problem when triggering a listener.", ex);
                    }
                }
            }
        } catch (Exception ex) {
            if (LOG.isDebugEnabled()) {
                LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error.", ex);
            } else {
                LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error: " + ex.getMessage());
            }
        }
    }

}

From source file:com.rockagen.gnext.service.spring.security.aspect.OpAspect.java

/**
 * Get method description//from   ww  w .  j a  v a 2s.c  om
 * 
 * @param method
 * @return method description
 */
private String getMethodDesc(Method method) {

    boolean hasAnnotation = method.isAnnotationPresent(OPLog.class);

    if (hasAnnotation) {
        OPLog annotation = method.getAnnotation(OPLog.class);

        String methodDescp = annotation.description();
        if (log.isDebugEnabled()) {
            log.debug("Target method: " + method.getName() + " Description: " + methodDescp);
        }
        return methodDescp;
    } else {
        return method.getName();
    }
}