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:com.googlecode.wicketwebbeans.model.BeanMetaData.java

/**
 * Derive metadata from standard annotations such as JPA and FindBugs.
 * //from   w ww  .jav  a 2  s .  c om
 * @param descriptor
 * @param elementMetaData
 */
private void deriveElementFromAnnotations(PropertyDescriptor descriptor, ElementMetaData elementMetaData) {
    // NOTE: !!! The annotation classes must be present at runtime, otherwise getAnnotations() doesn't
    // return the annotation.
    Method readMethod = descriptor.getReadMethod();
    if (readMethod != null) {
        processElementAnnotations(elementMetaData, readMethod.getAnnotations());
    }

    Method writeMethod = descriptor.getWriteMethod();
    if (writeMethod != null) {
        processElementAnnotations(elementMetaData, writeMethod.getAnnotations());
    }

    // Collects annotations on fields
    // Patch submitted by Richard O'Sullivan, fixes issue 9
    try {
        java.lang.reflect.Field beanField = beanClass.getDeclaredField(descriptor.getName());
        processElementAnnotations(elementMetaData, beanField.getAnnotations());
    } catch (Exception e) {
        // no foul, no harm.
    }
}

From source file:org.compass.annotations.config.binding.AnnotationsMappingBinding.java

/**
 * Recursivly process the class to find all it's annotations. Lower level
 * class/interfaces with annotations will be added first.
 *///  w ww.  ja  v a2 s.  c o m
private void processAnnotatedClass(Class<?> clazz) {
    if (clazz.equals(Class.class)) {
        return;
    }
    Class<?> superClazz = clazz.getSuperclass();
    if (superClazz != null && !superClazz.equals(Object.class)) {
        processAnnotatedClass(superClazz);
    }
    Class<?>[] interfaces = clazz.getInterfaces();
    for (Class<?> anInterface : interfaces) {
        processAnnotatedClass(anInterface);
    }

    SearchableConstant searchableConstant = clazz.getAnnotation(SearchableConstant.class);
    if (searchableConstant != null) {
        bindConstantMetaData(searchableConstant);
    }

    SearchableConstants searchableConstants = clazz.getAnnotation(SearchableConstants.class);
    if (searchableConstants != null) {
        for (SearchableConstant metaData : searchableConstants.value()) {
            bindConstantMetaData(metaData);
        }
    }

    SearchableDynamicMetaData searchableDynamicMetaData = clazz.getAnnotation(SearchableDynamicMetaData.class);
    if (searchableDynamicMetaData != null) {
        bindDynamicMetaData(searchableDynamicMetaData);
    }
    SearchableDynamicMetaDatas searchableDynamicMetaDatas = clazz
            .getAnnotation(SearchableDynamicMetaDatas.class);
    if (searchableDynamicMetaDatas != null) {
        for (SearchableDynamicMetaData metaData : searchableDynamicMetaDatas.value()) {
            bindDynamicMetaData(metaData);
        }
    }

    // handles recursive extends and the original extend
    if (clazz.isAnnotationPresent(Searchable.class)) {
        Searchable searchable = clazz.getAnnotation(Searchable.class);
        String[] extend = searchable.extend();
        if (extend.length != 0) {
            ArrayList<String> extendedMappings = new ArrayList<String>();
            if (classMapping.getExtendedAliases() != null) {
                extendedMappings.addAll(Arrays.asList(classMapping.getExtendedAliases()));
            }
            for (String extendedAlias : extend) {
                Alias extendedAliasLookup = valueLookup.lookupAlias(extendedAlias);
                if (extendedAliasLookup == null) {
                    extendedMappings.add(extendedAlias);
                } else {
                    extendedMappings.add(extendedAliasLookup.getName());
                }
            }
            classMapping.setExtendedAliases(extendedMappings.toArray(new String[extendedMappings.size()]));
        }
    }

    // if the super class has Searchable annotation as well, add it to the list of extends
    ArrayList<Class> extendedClasses = new ArrayList<Class>();
    if (clazz.getSuperclass() != null) {
        extendedClasses.add(clazz.getSuperclass());
    }
    extendedClasses.addAll(Arrays.asList(clazz.getInterfaces()));
    for (Class<?> superClass : extendedClasses) {
        if (!superClass.isAnnotationPresent(Searchable.class)) {
            continue;
        }
        Searchable superSearchable = superClass.getAnnotation(Searchable.class);
        String alias = getAliasFromSearchableClass(superClass, superSearchable);
        HashSet<String> extendedMappings = new HashSet<String>();
        if (classMapping.getExtendedAliases() != null) {
            extendedMappings.addAll(Arrays.asList(classMapping.getExtendedAliases()));
        }
        extendedMappings.add(alias);
        classMapping.setExtendedAliases(extendedMappings.toArray(new String[extendedMappings.size()]));
    }

    for (Field field : clazz.getDeclaredFields()) {
        for (Annotation annotation : field.getAnnotations()) {
            processsAnnotatedElement(clazz, field.getName(), "field", field.getType(), field.getGenericType(),
                    annotation, field);
        }
    }
    for (Method method : clazz.getDeclaredMethods()) {
        if (!method.isSynthetic() && !method.isBridge() && !Modifier.isStatic(method.getModifiers())
                && method.getParameterTypes().length == 0 && method.getReturnType() != void.class
                && (method.getName().startsWith("get") || method.getName().startsWith("is"))) {

            for (Annotation annotation : method.getAnnotations()) {
                processsAnnotatedElement(clazz, ClassUtils.getShortNameForMethod(method), "property",
                        method.getReturnType(), method.getGenericReturnType(), annotation, method);
            }
        }
    }
}

From source file:org.batoo.jpa.parser.impl.metadata.type.ManagedTypeMetadatImpl.java

/**
 * Infers and returns the access type based on all persistence annotations being on fields or methods and parent parent access type.
 * /*from w w w  .  jav a  2  s.co m*/
 * @param parentAccessType
 *            the parent access type
 * @return the inferred access type
 * 
 * @since 2.0.0
 */
private AccessType inferAccessType(AccessType parentAccessType) {
    boolean methodsHasAnnotations = false;
    boolean fieldsHasAnnotations = false;

    final List<String> alternated = Lists.newArrayList();

    final Field[] fields = this.clazz.getDeclaredFields();
    final Method[] methods = this.clazz.getDeclaredMethods();

    // find the alternated ones with @Access
    for (final Method m : methods) {
        // skip static and private methods.
        final int mods = m.getModifiers();
        if (Modifier.isStatic(mods) || !Modifier.isPublic(mods) || m.isBridge() || m.isSynthetic()) {
            continue;
        }

        if ((m.getParameterTypes().length != 0) || (m.getReturnType() == null)) {
            continue;
        }

        final Access access = m.getAnnotation(Access.class);
        if (access != null) {
            final String name = m.getName();
            if ((m.getReturnType() == boolean.class) && name.startsWith("is")) {
                alternated.add(StringUtils.capitalize(name.substring(2)));
            } else if (name.startsWith("get")) {
                alternated.add(StringUtils.capitalize(name.substring(3)));
            }
        }
    }

    for (final Field f : fields) {
        final Access access = f.getAnnotation(Access.class);

        if (access != null) {
            alternated.add(StringUtils.capitalize(f.getName()));
        }
    }

    // check methods
    for (final Method m : methods) {
        for (final Annotation a : m.getAnnotations()) {
            // ignore @Access(PROPERTY)
            if (a instanceof Access) {
                if (((Access) a).value() != AccessType.PROPERTY) {
                    continue;
                }
            }

            // ignore @Transient
            if (a instanceof Transient) {
                continue;
            }

            if ((m.getReturnType() == null) || (m.getParameterTypes().length > 0)) {
                continue;
            }

            String name = a.annotationType().getName();
            // ignore the listener annotations
            if (name.startsWith("javax.persistence.Post") || name.startsWith("javax.persistence.Pre")) {
                continue;
            }

            if (name.startsWith("javax.persistence") || name.startsWith("org.batoo.jpa.annotation")) {
                name = m.getName();

                if ((boolean.class == m.getReturnType()) || name.startsWith("is")) {
                    name = name.substring(2);
                } else if (name.startsWith("get")) {
                    name = name.substring(3);
                }

                if (alternated.contains(StringUtils.capitalize(name))) {
                    continue;
                }

                methodsHasAnnotations = true;
                break;
            }
        }
    }

    // check fields
    for (final Field f : fields) {
        for (final Annotation a : f.getAnnotations()) {
            // ignore @Access(FIELD)
            if (a instanceof Access) {
                if (((Access) a).value() != AccessType.FIELD) {
                    continue;
                }
            }

            // ignore @Transient
            if (a instanceof Transient) {
                continue;
            }

            final String name = a.annotationType().getName();
            if (name.startsWith("javax.persistence") || name.startsWith("org.batoo.jpa.annotation")) {
                if (alternated.contains(StringUtils.capitalize(f.getName()))) {
                    continue;
                }

                fieldsHasAnnotations = true;
                break;
            }
        }
    }

    if (fieldsHasAnnotations && methodsHasAnnotations) {
        throw new PersistenceException(
                "At least one field and one method has persistence annotations: " + this.clazz.getName());
    }

    if (methodsHasAnnotations) {
        return AccessType.PROPERTY;
    }

    if (fieldsHasAnnotations) {
        return AccessType.FIELD;
    }

    if (parentAccessType != null) {
        return parentAccessType;
    }

    return AccessType.FIELD;
}

From source file:de.terrestris.shogun.dao.DatabaseDao.java

private Criteria setEagerFetchModeForCollections(Criteria criteria, Class<?> clazz) {

    List<Field> fields = getAllFields(new ArrayList<Field>(), clazz);

    for (Field field : fields) {

        boolean isJsonIgnore = false;

        Method getterMethod;
        try {//from   w ww  . j  a  v a2 s  . c o  m
            getterMethod = new PropertyDescriptor(field.getName(), clazz).getReadMethod();
            Annotation[] anoArr = getterMethod.getAnnotations();
            for (Annotation annotation : anoArr) {
                if (annotation instanceof JsonIgnore) {
                    isJsonIgnore = true;
                }
            }
        } catch (IntrospectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (!isJsonIgnore && field.getType().isAssignableFrom(Set.class)) {
            // yes, we have to set the fetch mode
            criteria.setFetchMode(field.getName(), FetchMode.JOIN);
        }
    }

    return criteria;
}

From source file:ca.sqlpower.testutil.TestUtils.java

/**
 * Returns the set of property names which have both a getter and a setter
 * method and are annotated to be persisted through the {@link SPPersister}
 * classes.//  www. ja  v a  2  s .com
 * 
 * @param objectUnderTest
 *            The object that contains the persistable properties we want to
 *            find.
 * @param includeTransient
 *            If true the properties marked as transient will also be
 *            included. If false only the properties that are persisted and
 *            not transient are returned.
 * @param includeConstructorMutators
 *            If true the properties that have getters but can only be set
 *            through a constructor due to being final will be included. If
 *            false the persisted properties provided must have a setter.
 */
public static Set<String> findPersistableBeanProperties(SPObject objectUnderTest, boolean includeTransient,
        boolean includeConstructorMutators) throws Exception {
    Set<String> getters = new HashSet<String>();
    Set<String> setters = new HashSet<String>();
    for (Method m : objectUnderTest.getClass().getMethods()) {
        if (m.getName().equals("getClass"))
            continue;

        //skip non-public methods as they are not visible for persisting anyways.
        if (!Modifier.isPublic(m.getModifiers()))
            continue;
        //skip static methods
        if (Modifier.isStatic(m.getModifiers()))
            continue;

        if (m.getName().startsWith("get") || m.getName().startsWith("is")) {
            Class<?> parentClass = objectUnderTest.getClass();
            boolean accessor = false;
            boolean ignored = false;
            boolean isTransient = false;
            parentClass.getMethod(m.getName(), m.getParameterTypes());//test
            while (parentClass != null) {
                Method parentMethod;
                try {
                    parentMethod = parentClass.getMethod(m.getName(), m.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    parentClass = parentClass.getSuperclass();
                    continue;
                }
                if (parentMethod.getAnnotation(Accessor.class) != null) {
                    accessor = true;
                    if (parentMethod.getAnnotation(Transient.class) != null) {
                        isTransient = true;
                    }
                    break;
                } else if (parentMethod.getAnnotation(NonProperty.class) != null
                        || parentMethod.getAnnotation(NonBound.class) != null) {
                    ignored = true;
                    break;
                }
                parentClass = parentClass.getSuperclass();
            }
            if (accessor) {
                if (includeTransient || !isTransient) {
                    if (m.getName().startsWith("get")) {
                        getters.add(m.getName().substring(3));
                    } else if (m.getName().startsWith("is")) {
                        getters.add(m.getName().substring(2));
                    }
                }
            } else if (ignored) {
                //ignored so skip
            } else {
                fail("The method " + m.getName() + " of " + objectUnderTest.toString()
                        + " is a getter that is not annotated "
                        + "to be an accessor or transient. The exiting annotations are "
                        + Arrays.toString(m.getAnnotations()));
            }
        } else if (m.getName().startsWith("set")) {
            if (m.getAnnotation(Mutator.class) != null) {
                if ((includeTransient || m.getAnnotation(Transient.class) == null)
                        && (includeConstructorMutators
                                || !m.getAnnotation(Mutator.class).constructorMutator())) {
                    setters.add(m.getName().substring(3));
                }
            } else if (m.getAnnotation(NonProperty.class) != null || m.getAnnotation(NonBound.class) != null) {
                //ignored so skip and pass
            } else {
                fail("The method " + m.getName() + " is a setter that is not annotated "
                        + "to be a mutator or transient.");
            }
        }
    }

    Set<String> beanNames = new HashSet<String>();
    for (String beanName : getters) {
        if (setters.contains(beanName)) {
            String firstLetter = new String(new char[] { beanName.charAt(0) });
            beanNames.add(beanName.replaceFirst(firstLetter, firstLetter.toLowerCase()));
        }
    }
    return beanNames;
}

From source file:org.qifu.base.interceptor.LoginHandlerInterceptor.java

private boolean redirectLogin(HttpServletRequest request, HttpServletResponse response, Method method,
        String currentId, String accountId) throws Exception {
    if (request.getSession() != null && request.getSession().getAttribute(Constants.SESS_ACCOUNT) != null) {
        UserAccountHttpSessionSupport.remove(request);
        if (!Constants.getSystem().equals(Constants.getMainSystem())) { // for gsbsc-web, qcharts-web
            if (SecurityUtils.getSubject().isAuthenticated()) {
                SecurityUtils.getSubject().logout();
            }//from  w ww.j  a  v a  2 s.  co m
        }
    }
    String header = request.getHeader("X-Requested-With");
    String isQifuPageChange = request.getParameter(Constants.QIFU_PAGE_IN_TAB_IFRAME);
    if ("XMLHttpRequest".equalsIgnoreCase(header) && !YesNo.YES.equals(isQifuPageChange)) {
        response.getWriter().print(Constants.NO_LOGIN_JSON_DATA);
        response.getWriter().flush();
        response.getWriter().close();
        return false;
    }
    if (!Constants.getSystem().equals(Constants.getMainSystem())) { // for gsbsc-web, qcharts-web
        if (!StringUtils.isBlank(accountId) && !StringUtils.isBlank(currentId)
                && this.uSessLogHelper.countByCurrent(accountId, currentId) > 0) {
            /**
             * 
             *  CORE-WEB , ""  "" ??
             *  shiroFilter ?? , ??? refreshDojoContentPane
             * 
             * :
             * 1.  admin   
             * 2.   core-web  session ,  gsbsc-web 
             * 3.  tester  ,  gsbsc-web  qcharts-web  shiroFilter ?
             * 
             */
            Annotation[] actionMethodAnnotations = method.getAnnotations();
            String progId = this.getProgramId(request, actionMethodAnnotations);
            if (!StringUtils.isBlank(progId)) {
                //request.setAttribute("progId", progId);
                logger.warn("do page call refresTab event = " + progId);
                //return "refreshDojoContentPane"; // ? url ,  shiroFilter ?
                response.sendRedirect(
                        "./pages/system/refresPage.jsp?progId=" + progId + "&n=" + java.util.UUID.randomUUID());
                return false;
            } else {
                String url = SimpleUtils.getHttpRequestUrl(request);
                logger.warn("redirect URL = " + url);
                response.sendRedirect(url);
                return false;
            }

        }
    }
    if (YesNo.YES.equals(isQifuPageChange)) {
        response.sendRedirect("./pages/system/login_again.jsp");
        return false;
    }
    response.sendRedirect("logout.do");
    ; // ?logout ,  logout action  SecurityUtils.getSubject().logout()
    return false;
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

private Annotation[] getAnnotations(final PropertyDescriptor ppropertyDescription, final boolean useField) {
    final Class<?> clazz = this.beanHelper.getClazz();
    if (useField) {
        try {//from  ww w.j  a v a  2 s .c o m
            final Field field = clazz.getDeclaredField(ppropertyDescription.getPropertyName());
            return field.getAnnotations();
        } catch (final NoSuchFieldException ignore) { // NOPMD
            // Expected Case
        }
    } else {
        try {
            final Method method = clazz.getMethod(asGetter(ppropertyDescription));
            return method.getAnnotations();
        } catch (final NoSuchMethodException ignore) { // NOPMD
            // Expected Case
        }
    }
    return NO_ANNOTATIONS;
}

From source file:org.richfaces.tests.metamer.ftest.MatrixConfigurator.java

public int createConfiguration(Class<?> realClass, Method realMethod) {

    Map<Field, List<? extends Object>> parameters = new LinkedHashMap<Field, List<? extends Object>>();

    List<Field> unsatisfied = new LinkedList<Field>();

    // get a list of satisfied and unsatisfied parameters/injections
    Field[] allFields = getAllFields(realClass);
    for (Field field : allFields) {
        if (field.getAnnotation(Inject.class) != null) {
            if (field.getAnnotation(Use.class) != null) {
                parameters.put(field,// ww  w. j  av  a 2s.  c  o  m
                        getUseParameter(realClass, field.getType(), field.getAnnotation(Use.class)));
            } else if (field.getAnnotation(Templates.class) != null) {
                parameters.put(field, getTemplatesParameter(realClass, field.getType(),
                        field.getAnnotation(Templates.class), parameters));
                templatesField = field;
            } else {
                parameters.put(field, null);
                unsatisfied.add(field);
            }
        }
    }

    if (templatesField == null) {
        throw new IllegalStateException("there is no field annotated @Templates in " + realClass.getName());
    }

    try {
        // fulfill parameters by super classes' annotations
        fulfillParametersFromAnnotations(realClass, parameters, unsatisfied,
                getAnnotationsForAllSuperClasses(realClass));

        // fulfill parameters by method annotations
        fulfillParametersFromAnnotations(realClass, parameters, unsatisfied, realMethod.getAnnotations());
    } finally {
        templatesField = null;
    }

    if (!unsatisfied.isEmpty()) {
        throw new IllegalStateException("cannot satisfy following injection points: " + unsatisfied.toString());
    }

    Configuration configuration = new Configuration(parameters);

    int count = 0;
    while (configuration.hasNext()) {
        configuration.next();
        count += 1;
    }
    configuration.reset();

    getClassConfigurations(realClass).put(realMethod, configuration);

    if (parameters.size() == 0) {
        return 1;
    }

    return count;
}