Example usage for java.lang.reflect Method getAnnotations

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

Introduction

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

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:nz.co.senanque.validationengine.metadata.AnnotationsMetadataFactory.java

public EngineMetadata getObject() throws Exception {

    final Map<Class<? extends Annotation>, Class<? extends FieldValidator<Annotation>>> validatorMap = getValidatorMap();
    final Map<Class<?>, ClassMetadata> classMap = new HashMap<Class<?>, ClassMetadata>();

    for (Class<?> clazz : m_classes) {
        log.debug("class name {}", clazz);
        boolean classNeeded = true;
        final ClassMetadata classMetadata = new ClassMetadata();
        @SuppressWarnings("unchecked")
        Map<String, Property> propertyMap = ValidationUtils
                .getProperties((Class<? extends ValidationObject>) clazz);
        for (Property property : propertyMap.values()) {
            Method method = property.getGetter();
            log.debug("method.getName() {}", method.getName());
            String mname = method.getName();
            final String fieldName = property.getFieldName();
            final PropertyMetadataImpl fieldMetadata = new PropertyMetadataImpl(property, getMessageSource());
            boolean fieldNeeded = false;
            boolean foundDigits = false;
            boolean foundLength = false;
            int digitsLength = -1;
            for (Annotation fieldAnnotation : method.getAnnotations()) {
                log.debug("field annotation {}", fieldAnnotation);
                if (fieldAnnotation instanceof Label) {
                    fieldMetadata.setLabelName(((Label) fieldAnnotation).labelName());
                    fieldNeeded = true;/* w w w.j a  v a 2 s. c  o  m*/
                }
                if (fieldAnnotation instanceof Inactive) {
                    fieldMetadata.setInactive(true);
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof ReadOnly) {
                    fieldMetadata.setReadOnly(true);
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof Secret) {
                    fieldMetadata.setSecret(true);
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof Unknown) {
                    fieldMetadata.setUnknown(true);
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof Required) {
                    fieldMetadata.setRequired(true);
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof Digits) {
                    fieldMetadata.setFractionalDigits(((Digits) fieldAnnotation).fractionalDigits());
                    fieldNeeded = true;
                    foundDigits = true;
                    digitsLength = Integer.parseInt(((Digits) fieldAnnotation).integerDigits());
                    foundLength = true;
                }
                if (fieldAnnotation instanceof Range) {
                    fieldMetadata.setMinValue(((Range) fieldAnnotation).minInclusive());
                    fieldMetadata.setMaxValue(((Range) fieldAnnotation).maxInclusive());
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof Description) {
                    fieldMetadata.setDescription(((Description) fieldAnnotation).name());
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof History) {
                    fieldMetadata.setHistory(((History) fieldAnnotation).expire(),
                            ((History) fieldAnnotation).entries());
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof Id) {
                    fieldMetadata.setIdentifier(true);
                }
                if (fieldAnnotation instanceof Regex) {
                    fieldMetadata.setRegex(((Regex) fieldAnnotation).pattern());
                    fieldNeeded = true;
                }
                //                  if (fieldAnnotation instanceof BeanValidator)
                //                  {
                //                     fieldMetadata.setBean(((BeanValidator)fieldAnnotation).bean());
                //                     fieldMetadata.setParam(((BeanValidator)fieldAnnotation).param());
                //                     fieldNeeded = true;
                //                  }
                if (fieldAnnotation instanceof MapField) {
                    fieldMetadata.setMapField(((MapField) fieldAnnotation).name());
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof WritePermission) {
                    fieldMetadata.setPermission(((WritePermission) fieldAnnotation).name());
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof ReadPermission) {
                    fieldMetadata.setReadPermission(((ReadPermission) fieldAnnotation).name());
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof ChoiceList) {
                    final List<ChoiceBase> choiceList = m_choicesMap.get(((ChoiceList) fieldAnnotation).name());
                    fieldMetadata.setChoiceList(choiceList);
                    fieldNeeded = true;
                }
                if (fieldAnnotation instanceof Length) {
                    fieldMetadata.setMaxLength(((Length) fieldAnnotation).maxLength());
                    fieldNeeded = true;
                    foundLength = true;
                }
                Class<? extends FieldValidator<Annotation>> fvClass = validatorMap
                        .get(fieldAnnotation.annotationType());
                if (fvClass != null) {
                    final FieldValidator<Annotation> fv = fvClass.newInstance();
                    fv.init(fieldAnnotation, fieldMetadata);
                    fieldMetadata.addConstraintValidator(fv);
                    fieldNeeded = true;
                }
            }
            Column column = method.getAnnotation(Column.class);
            if (column != null) {
                int precision = column.precision();
                int fractional = column.scale();
                int length = column.length();
                if (!foundDigits) {
                    if (fractional > 0) {
                        fieldMetadata.setFractionalDigits(String.valueOf(fractional));
                    }
                }
                if (!foundLength) {
                    if (precision > 0 && length == 255) {
                        length = column.precision() + ((fractional > 0) ? 1 : 0);
                        fieldMetadata.setMaxLength(String.valueOf(length));
                    } else {
                        length = column.length();
                        fieldMetadata.setMaxLength(String.valueOf(length));
                    }
                }
            }

            Field field;
            try {
                field = clazz.getField(mname);
                for (Annotation fieldAnnotation : field.getAnnotations()) {
                    if (fieldAnnotation instanceof XmlElement) {
                        if (((XmlElement) fieldAnnotation).required()) {
                            fieldMetadata.setRequired(true);
                            fieldNeeded = true;
                        }
                    }
                }
            } catch (NoSuchFieldException e) {
                // ignore
            }
            Class<?> returnClass = method.getReturnType();
            Object[] t = returnClass.getEnumConstants();
            if (t != null) {
                fieldNeeded = true;
                fieldMetadata.setChoiceList(t);
            }
            if (!fieldNeeded) {
                if (m_classes.contains(returnClass) || returnClass.isAssignableFrom(List.class)) {
                    fieldNeeded = true;
                }
            }
            if (fieldNeeded) {
                log.debug("fieldName added to metadata {}.{}", clazz.getName(), fieldName);
                classMetadata.addField(fieldName, fieldMetadata);
                classNeeded = true;
            } else {
                log.debug("fieldName not needed {}.{}", clazz.getName(), fieldName);
            }
        }
        if (classNeeded) {
            log.debug("Class added to metadata {}", clazz.getName());
            classMap.put(clazz, classMetadata);
        }
    }
    return new EngineMetadata(classMap, m_choicesDoc);
}

From source file:io.swagger.jaxrs.SynapseReader.java

public List<String> extractOperationMethods(ApiOperation apiOperation, Method method,
        Iterator<SwaggerExtension> chain) {
    ArrayList<String> a = new ArrayList<>();
    if (apiOperation != null && apiOperation.httpMethod() != null && !"".equals(apiOperation.httpMethod())) {
        a.add(apiOperation.httpMethod().toLowerCase());
        return a;
    } else if (method.getAnnotation(RequestMapping.class) != null) {
        List<String> l = Arrays.asList(method.getAnnotation(RequestMapping.class).method()).stream()
                .map((org.thingsplode.synapse.core.RequestMethod rm) -> rm.toString().toLowerCase())
                .collect(Collectors.toList());
        if (l.isEmpty()) {
            if (method.getParameterCount() > 0 && (method.getAnnotations().length == 0
                    || method.getAnnotation(RequestBody.class) != null)) {
                //if there are parameters but not annotated at all or the RequestBody annotation is used
                l.add("put");
            } else if (method.getParameterCount() == 0 && !method.getReturnType().equals(Void.TYPE)) {
                //if there are no parameters but there's a return type
                l.add("get");
            } else {
                //if there are no parameters and no return type (void method)
                l.add("post");
            }/*from   ww  w.  j a  v a  2s . c  om*/
        }
        return l;
    } else if (SynapseEndpointServiceMarker.class.isAssignableFrom(method.getDeclaringClass())
            || method.getDeclaringClass().getAnnotation(Service.class) != null) {
        if (method.getParameterCount() > 0) {
            a.add("post");
        } else {
            a.add("get");
        }
        //todo: enable this when the service registry will support this differentiation
        //if (method.getReturnType().equals(Void.TYPE)) {
        //    a.add("post");
        //} else {
        //    a.add("get");
        //}
        return a;
    } else if ((ReflectionUtils.getOverriddenMethod(method)) != null) {
        return extractOperationMethods(apiOperation, ReflectionUtils.getOverriddenMethod(method), chain);
    } else if (chain != null && chain.hasNext()) {
        a.add(chain.next().extractOperationMethod(apiOperation, method, chain));
        return a;
    } else {
        return a;
    }
}

From source file:com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl.java

/**
 * Determine if the specified {@link AnnotatedElement} is annotated with either {@link Cacheable} or {@link TriggersRemove}
 * //from   ww  w.  j  av a2  s . c  om
 * @param method The element to inspect
 * @return The advice attributes about the element, null if the element is not advised
 */
private MethodAttribute findMethodAttribute(Method method) {
    Cacheable cacheableAnnotation = method.getAnnotation(Cacheable.class);
    if (cacheableAnnotation != null) {
        final ParameterMask parameterMask = this.parsePartialCacheKeyAnnotations(method);
        return this.parseCacheableAnnotation(cacheableAnnotation, method, parameterMask);
    }

    TriggersRemove triggersRemove = method.getAnnotation(TriggersRemove.class);
    if (triggersRemove != null) {
        final ParameterMask parameterMask = this.parsePartialCacheKeyAnnotations(method);
        return this.parseTriggersRemoveAnnotation(triggersRemove, method, parameterMask);
    }

    for (final Annotation metaAnn : method.getAnnotations()) {
        final Class<? extends Annotation> annotationType = metaAnn.annotationType();
        cacheableAnnotation = annotationType.getAnnotation(Cacheable.class);
        if (cacheableAnnotation != null) {
            final ParameterMask parameterMask = this.parsePartialCacheKeyAnnotations(method);
            return this.parseCacheableAnnotation(cacheableAnnotation, method, parameterMask);
        }

        triggersRemove = annotationType.getAnnotation(TriggersRemove.class);
        if (triggersRemove != null) {
            final ParameterMask parameterMask = this.parsePartialCacheKeyAnnotations(method);
            return this.parseTriggersRemoveAnnotation(triggersRemove, method, parameterMask);
        }
    }

    return null;
}

From source file:net.mojodna.sprout.SproutAutoLoaderPlugIn.java

private void loadSprouts(final WebApplicationContext wac) throws BeansException {
    final String[] beanNames = wac.getBeanNamesForType(Sprout.class);

    // create a default actionform
    final FormBeanConfig fbc = new FormBeanConfig();
    fbc.setName(Sprout.SPROUT_DEFAULT_ACTION_FORM_NAME);
    fbc.setType(LazyValidatorForm.class.getName());
    getModuleConfig().addFormBeanConfig(fbc);

    for (int i = 0; i < beanNames.length; i++) {
        final Sprout bean = (Sprout) wac.getBean(beanNames[i]);
        final String[] aliases = wac.getAliases(beanNames[i]);
        for (int j = 0; j < aliases.length; j++) {
            final String name = aliases[j].substring(aliases[j].lastIndexOf('/') + 1);
            try {
                final Method method = findMethod(name, bean.getClass());
                log.debug(aliases[j] + " -> " + beanNames[i] + "." + name);

                final ActionMapping ac = new ActionMapping();
                ac.setParameter(method.getName());
                ac.setPath(aliases[j]);//from  w w w. jav  a 2s  . c  o  m

                // establish defaults
                String actionForm = bean.getClass().getSimpleName() + Sprout.DEFAULT_FORM_SUFFIX;
                String input = aliases[j] + Sprout.DEFAULT_VIEW_EXTENSION;
                String scope = Sprout.DEFAULT_SCOPE;
                boolean validate = false;
                ac.addForwardConfig(makeForward(Sprout.FWD_SUCCESS, aliases[j] + ".jsp"));

                // process annotations and override defaults where appropriate
                final Annotation[] annotations = method.getAnnotations();
                for (int k = 0; k < annotations.length; k++) {
                    final Annotation a = annotations[k];
                    final Class type = a.annotationType();
                    if (type.equals(Sprout.FormName.class))
                        actionForm = ((Sprout.FormName) a).value();
                    else if (type.equals(Sprout.Forward.class)) {
                        final Forward fwd = (Sprout.Forward) a;
                        for (int m = 0; m < fwd.path().length; m++) {
                            String fwdPath = fwd.path()[m];
                            String fwdName = Sprout.FWD_SUCCESS;
                            boolean fwdRedirect = false;
                            if (fwd.name().length - 1 >= m)
                                fwdName = fwd.name()[m];
                            if (fwd.redirect().length - 1 >= m)
                                fwdRedirect = fwd.redirect()[m];
                            ac.addForwardConfig(makeForward(fwdName, fwdPath, fwdRedirect, null));
                        }
                    } else if (type.equals(Sprout.Input.class))
                        input = ((Sprout.Input) a).value();
                    if (type.equals(Sprout.Scope.class))
                        scope = ((Sprout.Scope) a).value();
                    else if (type.equals(Sprout.Validate.class))
                        validate = ((Sprout.Validate) a).value();
                }

                // use values
                if (null != getModuleConfig().findFormBeanConfig(actionForm))
                    ac.setName(actionForm);
                else {
                    log.info("No ActionForm defined: " + actionForm + ". Using default.");
                    ac.setName(Sprout.SPROUT_DEFAULT_ACTION_FORM_NAME);
                }
                ac.setValidate(validate);
                ac.setInput(input);
                ac.setScope(scope);

                getModuleConfig().addActionConfig(ac);
            } catch (final NoSuchMethodException e) {
                log.warn("Could not register action; no such method: " + name, e);
            }
        }
    }

    /* Useful if you'd like a view into registered paths
     * TODO create a ServletFilter that displays these
    log.debug("Dumping action configs...");
    final ActionConfig[] configs = getModuleConfig().findActionConfigs();
    for ( int i = 0; i < configs.length; i++ ) {
    log.debug( configs[i].getPath() );
    }
    */
}

From source file:org.springframework.core.annotation.AnnotationUtils.java

static boolean isInterfaceWithAnnotatedMethods(Class<?> iface) {
    Boolean found = annotatedInterfaceCache.get(iface);
    if (found != null) {
        return found;
    }// ww w  . j  av  a2 s  .co  m
    found = Boolean.FALSE;
    for (Method ifcMethod : iface.getMethods()) {
        try {
            if (ifcMethod.getAnnotations().length > 0) {
                found = Boolean.TRUE;
                break;
            }
        } catch (Throwable ex) {
            handleIntrospectionFailure(ifcMethod, ex);
        }
    }
    annotatedInterfaceCache.put(iface, found);
    return found;
}

From source file:com.chtr.tmoauto.webui.CommonFunctions.java

/**
 * This method build and return a webDriver instance by which one can use to control the automation of a specified
 * web browser and platform or Operating System.
 *
 * @param url - main test url/* w w w . j  av  a 2 s .  com*/
 * @param browserType - type of browser to automate
 * @param platform - operating system or platform type
 * @return
 * @return - Instance of WebBrowser
 */
@SuppressWarnings("resource")
public static CommonFunctions buildWebDriver(String url, String browserName, Method method) {
    Annotation[] a = method.getAnnotations();
    String description = null;
    try {
        description = a[0].toString().split("description=")[1].split(", retryAnalyzer=")[0];
    } catch (Exception e) {
    }
    System.gc();
    log.info("");
    log.info("=========================================================");
    log.info("Test: {}", method.getName());
    log.info("Test Description: {}", description);
    log.info("=========================================================");
    WebDriver wd = buildWebDriver(browserName);
    CommonFunctions wDriver = new CommonFunctions(wd);
    log.info("Starting WebDriver: { Browser: {} } { Version: {} } { Platform: {} } ",
            wDriver.getBrowserName().trim(), wDriver.getBrowserVersion().trim(),
            wDriver.discoverPlatform().toString());
    log.info("Navigating to: {}", url);
    wd.get(url);
    return new CommonFunctions(wd);
}

From source file:com.chtr.tmoauto.webui.CommonFunctions.java

/**
 * This method build and return a webDriver instance by which one can use to control the automation of a specified
 * web browser and platform or Operating System.
 *
 * @param url - main test url/*from  ww  w . j  ava  2 s.c  o m*/
 * @param browserType - type of browser to automate
 * @param platform - operating system or platform type
 * @param seleniumGridUrl - selenium Grid Url
 * @return
 * @return - Instance of WebBrowser
 */
@SuppressWarnings("resource")
public static CommonFunctions buildRemoteWebDriver(String url, String browserName, Method method) {
    Annotation[] a = method.getAnnotations();
    String description = null;
    try {
        description = a[0].toString().split("description=")[1].split(", retryAnalyzer=")[0];
    } catch (Exception e) {
    }
    System.gc();
    log.info("");
    log.info("=========================================================");
    log.info("Test: {}", method.getName());
    log.info("Test Description: {}", description);
    log.info("=========================================================");
    WebDriver wd = buildRemoteWebDriver(browserName);
    CommonFunctions wDriver = new CommonFunctions(wd);
    log.info("Starting Remote WebDriver: { Browser: {} } { Version: {} } { Platform: {} } ",
            wDriver.getBrowserName().trim(), wDriver.getBrowserVersion().trim(),
            wDriver.discoverPlatform().toString());
    log.info("Navigating to: {}", url);
    wd.get(url);
    return new CommonFunctions(wd);
}

From source file:com.laxser.blitz.web.ControllerInterceptorAdapter.java

/**
 * true??/* w w  w  . j  a v  a  2  s  .  co  m*/
 * 
 * @param controllerClazz
 * @param actionMethod
 * @return
 */
protected final boolean checkDenyAnnotations(Class<?> controllerClazz, Method actionMethod) {
    List<Class<? extends Annotation>> denyAnnotations = getDenyAnnotationClasses();
    if (denyAnnotations == null || denyAnnotations.size() == 0) {
        return false;
    }
    for (Class<? extends Annotation> denyAnnotation : denyAnnotations) {
        if (denyAnnotation == null) {
            continue;
        }
        BitSet scopeSet = getAnnotationScope(denyAnnotation);
        if (scopeSet.get(AnnotationScope.METHOD.ordinal())) {
            if (actionMethod.isAnnotationPresent(denyAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.CLASS.ordinal())) {
            if (controllerClazz.isAnnotationPresent(denyAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.ANNOTATION.ordinal())) {
            for (Annotation annotation : actionMethod.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(denyAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
                }
            }
            for (Annotation annotation : controllerClazz.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(denyAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
                }
            }
        }
    }
    return false;
}

From source file:io.sinistral.proteus.server.tools.swagger.Reader.java

private String getHttpMethodFromCustomAnnotations(Method method) {
    for (Annotation methodAnnotation : method.getAnnotations()) {
        HttpMethod httpMethod = methodAnnotation.annotationType().getAnnotation(HttpMethod.class);
        if (httpMethod != null) {
            return httpMethod.value().toLowerCase();
        }/*  w  w  w .j av a 2s . c o  m*/
    }
    return null;
}

From source file:com.laxser.blitz.web.ControllerInterceptorAdapter.java

/**
 * false?/*  w  w  w .j av a  2s.com*/
 * 
 * @param controllerClazz
 *            
 * @param actionMethod
 *            ?
 * @return
 */
protected final boolean checkRequiredAnnotations(Class<?> controllerClazz, Method actionMethod) {
    List<Class<? extends Annotation>> requiredAnnotations = getRequiredAnnotationClasses();
    if (requiredAnnotations == null || requiredAnnotations.size() == 0) {
        return true;
    }
    for (Class<? extends Annotation> requiredAnnotation : requiredAnnotations) {
        if (requiredAnnotation == null) {
            continue;
        }
        BitSet scopeSet = getAnnotationScope(requiredAnnotation);
        if (scopeSet.get(AnnotationScope.METHOD.ordinal())) {
            if (actionMethod.isAnnotationPresent(requiredAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.CLASS.ordinal())) {
            if (controllerClazz.isAnnotationPresent(requiredAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.ANNOTATION.ordinal())) {
            for (Annotation annotation : actionMethod.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(requiredAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
                }
            }
            for (Annotation annotation : controllerClazz.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(requiredAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
                }
            }
        }
    }
    return false;
}