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:org.jsr107.ri.annotations.spring.CacheContextSourceImpl.java

@Override
protected <T extends Annotation> T getAnnotation(Class<T> annotationClass, Method method,
        Class<? extends Object> targetClass) {
    // The method may be on an interface, but we need attributes from the target class.
    // If the target class is null, the method will be unchanged.
    Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
    // If we are dealing with method with generic parameters, find the original method.
    specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

    final T annotation = specificMethod.getAnnotation(annotationClass);
    if (annotation != null) {
        return annotation;
    }/*from   w  ww .  ja  va 2s .  c o m*/

    if (specificMethod != method) {
        // Fallback is to look at the original method.
        return method.getAnnotation(annotationClass);
    }

    return null;
}

From source file:com.aw.swing.mvp.binding.component.support.ValidatorBuilder.java

public PropertyValidator buildPropertyValidator(Method method) {
    PropertyValidator propertyValidator = new PropertyValidator();
    if (method.isAnnotationPresent(Validation.class)) {
        Validation validation = method.getAnnotation(Validation.class);
        String patterValidator = validation.value();
        logger.debug("Patter Validator = " + patterValidator);
        propertyValidator = PatternRules.buildPropertyValidator(patterValidator);

    }// w w  w. ja  v  a2 s .  c  o  m

    if (method.isAnnotationPresent(Email.class)) {
        propertyValidator.add(Rule.VALIDATE_EMAIL);
    }
    if (method.isAnnotationPresent(RangeNumber.class)) {
        RangeNumber range = method.getAnnotation(RangeNumber.class);
        propertyValidator.add(Rule.VALIDATE_RANGE);
        propertyValidator.setMinValue(range.min());
        propertyValidator.setMaxValue(range.max());
    }
    if (method.isAnnotationPresent(RangeDate.class)) {
        SimpleDateFormat sdf = new SimpleDateFormat(
                AWBaseContext.instance().getConfigInfoProvider().getDateFormat());
        RangeDate range = method.getAnnotation(RangeDate.class);
        propertyValidator.add(Rule.VALIDATE_RANGE);
        Date from = null;
        Date to = null;
        try {
            if (range.from().equals("today")) {
                from = new Date();
            } else {
                from = sdf.parse(range.from());
            }
            if (range.to().equals("today")) {
                to = new Date();
            } else {
                to = sdf.parse(range.to());
            }

            propertyValidator.setMinValue(from);
            propertyValidator.setMaxValue(to);
        } catch (ParseException e) {
            logger.error("Error execute parse from <" + range.from() + "> to <" + range.to() + ">");
        }
    }
    if (method.isAnnotationPresent(Past.class)) {
        propertyValidator.add(Rule.VALIDATE_LESS_THAN);
        propertyValidator.setMaxValue(new Date());
    }
    if (method.isAnnotationPresent(Future.class)) {
        propertyValidator.add(Rule.VALIDATE_GREATER_THAN);
        propertyValidator.setMinValue(new Date());
    }
    return propertyValidator;
}

From source file:java2typescript.jaxrs.ServiceDescriptorGenerator.java

private RestMethod generateMethod(Method method) {

    RestMethod restMethod = new RestMethod();
    Path pathAnnotation = method.getAnnotation(Path.class);

    restMethod.setPath(pathAnnotation == null ? "" : pathAnnotation.value());

    restMethod.setName(method.getName());

    if (method.getAnnotation(GET.class) != null) {
        restMethod.setHttpMethod(HttpMethod.GET);
    }/*from  www. j  a  v  a 2s  .  c  o m*/
    if (method.getAnnotation(POST.class) != null) {
        restMethod.setHttpMethod(HttpMethod.POST);
    }
    if (method.getAnnotation(PUT.class) != null) {
        restMethod.setHttpMethod(HttpMethod.PUT);
    }
    if (method.getAnnotation(DELETE.class) != null) {
        restMethod.setHttpMethod(HttpMethod.DELETE);
    }

    if (restMethod.getHttpMethod() == null) {
        throw new RuntimeException("No Http method defined for method : " + method.getName());
    }

    restMethod.setParams(generateParams(method));

    if (extras != null) {
        restMethod.setExtra(extras.getExtraForMethod(method));
    }

    return restMethod;
}

From source file:org.trpr.platform.servicefw.impl.spring.web.HomeController.java

private List<ResourceInfo> findMethods(Map<String, Object> handlerMap, Set<String> urls) {

    SortedSet<ResourceInfo> result = new TreeSet<ResourceInfo>();

    for (String key : urls) {

        Object handler = handlerMap.get(key);
        Class<?> handlerType = ClassUtils.getUserClass(handler);
        HandlerMethodResolver resolver = new HandlerMethodResolver();
        resolver.init(handlerType);/*from w  ww  . j a v a  2  s. co  m*/

        String[] typeMappings = null;
        RequestMapping typeMapping = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class);
        if (typeMapping != null) {
            typeMappings = typeMapping.value();
        }

        Set<Method> handlerMethods = resolver.getHandlerMethods();
        for (Method method : handlerMethods) {

            RequestMapping mapping = method.getAnnotation(RequestMapping.class);

            Collection<String> computedMappings = new HashSet<String>();
            if (typeMappings != null) {
                computedMappings.addAll(Arrays.asList(typeMappings));
            }

            for (String path : mapping.value()) {
                if (typeMappings != null) {
                    for (String parent : computedMappings) {
                        if (parent.endsWith("/")) {
                            parent = parent.substring(0, parent.length() - 1);
                        }
                        computedMappings.add(parent + path);
                    }
                } else {
                    computedMappings.add(path);
                }
            }

            logger.debug("Analysing mappings for method:" + method.getName() + ", key:" + key
                    + ", computed mappings: " + computedMappings);
            if (computedMappings.contains(key)) {
                RequestMethod[] methods = mapping.method();
                if (methods != null && methods.length > 0) {
                    for (RequestMethod requestMethod : methods) {
                        logger.debug(
                                "Added explicit mapping for path=" + key + "to RequestMethod=" + requestMethod);
                        result.add(new ResourceInfo(key, requestMethod));
                    }
                } else {
                    logger.debug("Added implicit mapping for path=" + key + "to RequestMethod=GET");
                    result.add(new ResourceInfo(key, RequestMethod.GET));
                }
            }

        }

        if (handlerMethods.isEmpty()) {
            result.add(new ResourceInfo(key, RequestMethod.GET));
        }

    }

    return new ArrayList<ResourceInfo>(result);

}

From source file:com.cuubez.visualizer.resource.ResourceMetaDataScanner.java

private boolean scanResponseType(SubResource subResource, Method method) {

    ResponseType responseType = method.getAnnotation(ResponseType.class);

    if (responseType != null) {
        subResource.setReturnType(responseType.value());
        return true;
    }/*from w w w  .  ja v  a  2s .c  o m*/

    return false;
}

From source file:com.dexcoder.dal.spring.mapper.JdbcRowMapper.java

/**
 * Initialize the mapping metadata for the given class.
 * @param mappedClass the mapped class/*from  www.  j  a  v a  2 s. com*/
 */
protected void initialize(Class<T> mappedClass) {
    this.mappedClass = mappedClass;
    this.mappedFields = new HashMap<String, PropertyDescriptor>();
    this.mappedProperties = new HashSet<String>();
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null) {

            Method readMethod = pd.getReadMethod();
            if (readMethod != null) {
                Column aColumn = readMethod.getAnnotation(Column.class);
                if (aColumn != null) {
                    String name = NameUtils.getLegalName(aColumn.value());
                    this.mappedFields.put(lowerCaseName(name), pd);
                }
            }

            this.mappedFields.put(lowerCaseName(pd.getName()), pd);
            String underscoredName = underscoreName(pd.getName());
            if (!lowerCaseName(pd.getName()).equals(underscoredName)) {
                this.mappedFields.put(underscoredName, pd);
            }
            this.mappedProperties.add(pd.getName());
        }
    }
}

From source file:net.sf.jabb.util.web.WebApplicationConfiguration.java

/**
 * Scan all the beans for menu items/*from  w  ww .j ava2s.c  o  m*/
 */
public void scanForMenuItems() {
    Map<String, Map<String, MenuItemExt>> allMenuItems = new PutIfAbsentMap<String, Map<String, MenuItemExt>>(
            new HashMap<String, Map<String, MenuItemExt>>(),
            new MapValueFactory<String, Map<String, MenuItemExt>>() {
                @Override
                public Map<String, MenuItemExt> createValue(String key) {
                    return new TreeMap<String, MenuItemExt>();
                }
            });
    //new HashMap<String, Map<String, MenuItemExt>>();   // <menuName, <path, MenuItemExt>>

    // Get all beans that may have menu items defined
    Map<String, Object> beans = appContext.getBeansWithAnnotation(WebMenu.class);
    beans.putAll(appContext.getBeansWithAnnotation(RequestMapping.class));

    // Find all menu items 
    for (Object bean : beans.values()) {
        Class<?> beanClass;
        if (bean instanceof Advised) { // if EnhancerBySpringCGLIB
            beanClass = ((Advised) bean).getTargetClass();
        } else {
            beanClass = bean.getClass();
        }

        // Check class level annotations first
        RequestMapping classRequestMapping = beanClass.getAnnotation(RequestMapping.class);
        WebMenu classWebMenu = beanClass.getAnnotation(WebMenu.class);
        if (true) {//classWebMenu != null && classWebMenu.value().length() != 0){   // not hidden
            MenuItemExt classMenuItem = new MenuItemExt(classWebMenu, classRequestMapping);

            String basePath = classMenuItem.path != null ? classMenuItem.path : "";
            if (classMenuItem.title != null && classMenuItem.title.length() > 0) { // it is also a visible menu item
                MenuItemExt existing = allMenuItems.get(classMenuItem.menuName).put(basePath, classMenuItem);
                if (existing != null) {
                    log.error("Duplicated web menu item definitions in " + beanClass.getName()
                            + ".\n\tExisting: " + existing + "\n\tCurrent: " + classMenuItem);
                }
            }

            // Then look into all the methods
            for (Method method : beanClass.getDeclaredMethods()) {
                RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class);
                WebMenu methodWebMenu = method.getAnnotation(WebMenu.class);
                if (methodWebMenu != null && methodWebMenu.value().length() != 0) { // not hidden
                    MenuItemExt methodMenuItem = new MenuItemExt(methodWebMenu, methodRequestMapping,
                            classMenuItem);

                    if (methodMenuItem.menuName != null) {
                        MenuItemExt existing = allMenuItems.get(methodMenuItem.menuName)
                                .put(methodMenuItem.path, methodMenuItem);
                        if (existing != null) {
                            log.error("Duplicated web menu item definitions in " + beanClass.getName() + "."
                                    + method.toGenericString() + ".\n\tExisting: " + existing + "\n\tCurrent: "
                                    + methodMenuItem);
                        }
                    }
                }
            }
        }
    }

    // construct menu trees
    menus = new HashMap<String, WebMenuItem>();
    menuItemPaths = new HashMap<String, Map<String, WebMenuItem>>();

    for (Map.Entry<String, Map<String, MenuItemExt>> menuItems : allMenuItems.entrySet()) {
        String menuName = menuItems.getKey();
        Map<String, MenuItemExt> items = menuItems.getValue();
        WebMenuItem root = new WebMenuItem();
        root.title = menuName; // for the root, set its title as menu name
        root.breadcrumbs = new ArrayList<WebMenuItem>(1);
        root.breadcrumbs.add(root); // root is the first in breadcrumbs
        menus.put(menuName, root);
        menuItemPaths.put(menuName, new HashMap<String, WebMenuItem>());
        for (MenuItemExt itemExt : items.values()) {
            String path = itemExt.path;
            WebMenuItem parent = null;
            do {
                path = StringUtils.substringBeforeLast(path, "/");
                if (path == null || path.indexOf('/') == -1) {
                    parent = root;
                    break;
                }
                parent = items.get(path);
            } while (parent == null);
            parent.addSubItem(itemExt);
        }

        // clean up the tree
        cleanUpMenuTree(root, menuName);
        log.info("Menu '" + menuName + "' loaded:\n" + root);
    }
}

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

private void doUpdate(final JoinPoint jp, final Object retVal) throws Throwable {
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return;//from  w  w w  . j  a va2 s .com
    }

    final Method methodToCache = getMethodToCache(jp);
    List<L2UpdateSingleCache> lAnnotations;

    //        if (methodToCache.getAnnotation(UpdateSingleCache.class) != null) {
    lAnnotations = Arrays.asList(methodToCache.getAnnotation(L2UpdateSingleCache.class));
    //        } else {
    //            lAnnotations = Arrays.asList(methodToCache.getAnnotation(UpdateSingleCaches.class).value());
    //        }

    for (int i = 0; i < lAnnotations.size(); i++) {
        // 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.
        try {
            final AnnotationInfo info = getAnnotationInfo(lAnnotations.get(i), methodToCache.getName());
            final String baseKey = CacheBase.getBaseKey(info.getAsString(AType.KEY_TEMPLATE),
                    info.getAsInteger(AType.KEY_INDEX, null), retVal, jp.getArgs(), methodToCache.toString(),
                    factory, methodStore);
            final String cacheKey = buildCacheKey(baseKey, info.getAsString(AType.NAMESPACE),
                    info.getAsString(AType.KEY_PREFIX));
            final Object dataObject = CacheBase.getIndexObject(info.getAsInteger(AType.DATA_INDEX, null),
                    retVal, jp.getArgs(), methodToCache.toString());
            final Object submission = (dataObject == null) ? new PertinentNegativeNull() : dataObject;
            boolean cacheable = true;
            if (submission instanceof CacheConditionally) {
                cacheable = ((CacheConditionally) submission).isCacheable();
            }
            if (cacheable) {
                getCache().setBulk(ImmutableMap.of(cacheKey, submission),
                        info.<Duration>getAsType(AType.WINDOW, null));
            }
        } 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:dk.statsbiblioteket.util.qa.PackageScanner.java

/**
 * <b>Beware:</b> This class may throw exotic exceptions since it deals with
 * binary class data.//w w w.  ja va  2  s .  c om
 *
 * @param classTarget The class to analyze.
 * @param filename    The file containing the class.
 * @return An array of ReportElements extracted from the members of the
 *         class and the class it self.
 */
@SuppressWarnings({ "unchecked" })
public final ReportElement[] analyzeClass(Class classTarget, String filename) {
    //FIXME: Filenames for internal classes does not refer to correct .java
    //file (it uses Foo$Bar.java)
    Class[] classes = classTarget.getDeclaredClasses();
    Constructor[] constructors = classTarget.getDeclaredConstructors();
    Method[] methods = classTarget.getDeclaredMethods();
    Field[] fields = classTarget.getDeclaredFields();

    List<ReportElement> elements = new ArrayList<ReportElement>();

    // Add the top level class
    ReportElement topLevel = new ReportElement(ReportElement.ElementType.CLASS, classTarget.getName(), null,
            baseSource.toString(), filename, (QAInfo) classTarget.getAnnotation(QAInfo.class));
    elements.add(topLevel);

    for (Class c : classes) {
        ReportElement classInfo = new ReportElement(ReportElement.ElementType.CLASS, c.getName(),
                classTarget.getName(), baseSource.toString(), filename, (QAInfo) c.getAnnotation(QAInfo.class));
        elements.add(classInfo);
    }

    for (Constructor c : constructors) {
        ReportElement conInfo = new ReportElement(ReportElement.ElementType.METHOD,
                c.getName().substring(c.getName().lastIndexOf(".") + 1), classTarget.getName(),
                baseSource.toString(), filename, (QAInfo) c.getAnnotation(QAInfo.class));
        elements.add(conInfo);
    }

    for (Method m : methods) {
        ReportElement metInfo = new ReportElement(ReportElement.ElementType.METHOD, m.getName(),
                classTarget.getName(), baseSource.toString(), filename, (QAInfo) m.getAnnotation(QAInfo.class));
        elements.add(metInfo);
    }

    for (Field f : fields) {
        ReportElement fInfo = new ReportElement(ReportElement.ElementType.FIELD, f.getName(),
                classTarget.getName(), baseSource.toString(), filename, (QAInfo) f.getAnnotation(QAInfo.class));
        elements.add(fInfo);
    }
    return elements.toArray(new ReportElement[elements.size()]);
}