Example usage for java.lang.reflect Method isAnnotationPresent

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

Introduction

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

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:com.example.captain_miao.grantap.utils.PermissionUtils.java

public static <A extends Annotation> Method findMethodWithRequestCode(Class clazz, Class<A> annotation,
        int requestCode) {
    for (Method method : clazz.getDeclaredMethods()) {
        if (method.isAnnotationPresent(annotation)) {
            if (isEqualRequestCodeFromAnnotation(method, annotation, requestCode)) {
                return method;
            }//from   ww  w  .  ja v  a 2 s.  co m
        }
    }
    return null;
}

From source file:com.example.captain_miao.grantap.utils.PermissionUtils.java

public static <A extends Annotation> Method findMethodPermissionGrantedWithRequestCode(Class clazz,
        Class<A> permissionFailClass, int requestCode) {
    for (Method method : clazz.getDeclaredMethods()) {
        if (method.isAnnotationPresent(permissionFailClass)) {
            if (requestCode == method.getAnnotation(PermissionGranted.class).requestCode()) {
                return method;
            }/*from ww  w  . j  a v  a2s. c  o m*/
        }
    }
    return null;
}

From source file:nl.knaw.huygens.timbuctoo.rest.util.JAXUtils.java

/**
 * Returns an API description for each HTTP method in the specified
 * class if it has a <code>Path</code> annotation, or an empty list
 * if the <code>Path</code> annotation is missing.
 *//*from  w  w  w.j a  v  a  2  s  .co m*/
public static List<API> generateAPIs(Class<?> cls) {
    List<API> list = Lists.newArrayList();

    String basePath = pathValueOf(cls);
    if (!basePath.isEmpty()) {
        for (Method method : cls.getMethods()) {
            List<String> reqs = Lists.newArrayList();
            if (method.isAnnotationPresent(GET.class)) {
                reqs.add(HttpMethod.GET);
            }
            if (method.isAnnotationPresent(POST.class)) {
                reqs.add(HttpMethod.POST);
            }
            if (method.isAnnotationPresent(PUT.class)) {
                reqs.add(HttpMethod.PUT);
            }
            if (method.isAnnotationPresent(DELETE.class)) {
                reqs.add(HttpMethod.DELETE);
            }

            if (!reqs.isEmpty()) {
                String subPath = pathValueOf(method);
                String fullPath = subPath.isEmpty() ? basePath : basePath + "/" + subPath;
                fullPath = fullPath.replaceAll("\\{([^:]*):[^}]*\\}", "{$1}");
                list.add(new API(fullPath, reqs, mediaTypesOf(method), descriptionOf(method)));
            }
        }
    }

    return list;
}

From source file:no.met.jtimeseries.service.ServiceDescriptionGenerator.java

/**
 * @param c The class to search for methods in.
 * @return A list of method that is used to offer web services in the class.
 *///w ww. j a  v  a  2 s  . c o m
private static List<Method> getServiceMethods(Class<? extends Object> c) {

    List<Method> serviceMethods = new ArrayList<Method>();

    for (Method m : c.getMethods()) {

        logger.info(m.getName());
        if (m.isAnnotationPresent(Path.class)) {
            serviceMethods.add(m);
        }
    }

    return serviceMethods;
}

From source file:com.github.benmanes.caffeine.cache.testing.CacheValidationListener.java

/** Checks the statistics if {@link CheckNoStats} is found. */
private static void checkNoStats(ITestResult testResult, CacheContext context) {
    Method testMethod = testResult.getMethod().getConstructorOrMethod().getMethod();
    boolean checkNoStats = testMethod.isAnnotationPresent(CheckNoStats.class);
    if (!checkNoStats) {
        return;//from   ww w . j  a va  2  s  .com
    }

    assertThat("Test requires CacheContext param for validation", context, is(not(nullValue())));
    assertThat(context, hasHitCount(0));
    assertThat(context, hasMissCount(0));
    assertThat(context, hasLoadSuccessCount(0));
    assertThat(context, hasLoadFailureCount(0));
}

From source file:org.onehippo.forge.feed.util.ConversionUtil.java

/**
 * TODO refactor complexity and enable caching
 *
 * @param destination// ww w.j  a  va2s  . co m
 * @param source
 * @param type
 * @param context
 * @param <T>
 * @return
 */
private static <T> T convertObject(final T destination, final Object source, FeedType type, Object... context) {
    final Method[] methods = source.getClass().getMethods();
    for (Method method : methods) {
        final boolean refPresent = method.isAnnotationPresent(SyndicationRefs.class);
        if (refPresent || (method.isAnnotationPresent(SyndicationElement.class)
                && method.getAnnotation(SyndicationElement.class).type().equals(type))) {
            SyndicationElement annotation = null;
            if (refPresent) {
                final SyndicationElement[] value = method.getAnnotation(SyndicationRefs.class).value();
                for (SyndicationElement element : value) {
                    if (element.type().equals(type)) {
                        annotation = element;
                        break;
                    }
                }
                if (annotation == null) {
                    continue;
                }
            } else {
                annotation = method.getAnnotation(SyndicationElement.class);
            }
            final String name = annotation.name();
            try {
                final Object initValue = method.invoke(source);
                Object value = initValue;
                if (!(annotation.converter().isAssignableFrom(NoopConverter.class))) {
                    final Converter converter = annotation.converter().newInstance();
                    value = converter.convert(initValue);
                }
                if (!(annotation.transformer().isAssignableFrom(NoopTransformer.class)) && initValue != null) {
                    Map<Class, Object> contentMap = new HashMap<>();
                    for (Object o : context) {
                        contentMap.put(o.getClass(), o);
                    }
                    contentMap.put(initValue.getClass(), initValue);
                    final Class<?> transformer = annotation.transformer();
                    final Method[] transformerMethods = transformer.getMethods();
                    for (Method transformerMethod : transformerMethods) {
                        if (transformerMethod.isAnnotationPresent(ContextTransformable.class)) {
                            final Class<?>[] parameterTypes = transformerMethod.getParameterTypes();
                            List<Object> parameters = new ArrayList<>();
                            for (Class clazz : parameterTypes) {
                                if (contentMap.containsKey(clazz)) {
                                    parameters.add(contentMap.get(clazz));
                                } else {
                                    boolean found = false;
                                    for (Object obj : contentMap.values()) {
                                        if (clazz.isInstance(obj)) {
                                            parameters.add(obj);
                                            found = true;
                                            break;
                                        }
                                    }
                                    if (!found) {
                                        parameters.add(null);
                                    }
                                }
                            }
                            if (Modifier.isStatic(transformerMethod.getModifiers())) {
                                value = transformerMethod.invoke(null, parameters.toArray());
                            } else {
                                value = transformerMethod.invoke(transformer.newInstance(),
                                        parameters.toArray());
                            }
                            break;
                        }
                    }

                }
                if (value != null) {
                    BeanUtils.setProperty(destination, name, value);
                }
            } catch (Exception e) {
                log.error(String.format("exception happened while trying to revolve syndication %s", name), e);
            }

        }
    }
    return destination;
}

From source file:elaborate.jaxrs.JAXUtils.java

/**
 * Returns an API description for each HTTP method in the specified
 * class if it has a <code>Path</code> annotation, or an empty list
 * if the <code>Path</code> annotation is missing.
 *//*from   ww  w .j  a va  2 s.c  o  m*/
public static List<API> generateAPIs(Class<?> cls) {
    List<API> list = Lists.newArrayList();

    String basePath = pathValueOf(cls);
    if (!basePath.isEmpty()) {
        for (Method method : cls.getMethods()) {
            Builder<String> builder = ImmutableList.<String>builder();
            if (method.isAnnotationPresent(GET.class)) {
                builder.add(HttpMethod.GET);
            }
            if (method.isAnnotationPresent(POST.class)) {
                builder.add(HttpMethod.POST);
            }
            if (method.isAnnotationPresent(PUT.class)) {
                builder.add(HttpMethod.PUT);
            }
            if (method.isAnnotationPresent(DELETE.class)) {
                builder.add(HttpMethod.DELETE);
            }

            ImmutableList<String> reqs = builder.build();
            if (!reqs.isEmpty()) {
                String subPath = pathValueOf(method);
                String fullPath = subPath.isEmpty() ? basePath : basePath + "/" + subPath;
                fullPath = fullPath.replaceAll("\\{([^:]*):[^}]*\\}", "{$1}");
                list.add(new API(fullPath, reqs, requestContentTypesOf(method), responseContentTypesOf(method),
                        descriptionOf(method)));
            }
        }
    }

    return list;
}

From source file:com.mycomm.dao.mydao.base.MyDaoSupport.java

/**
 * ?,hibernate???select count(o) from Xxx
 * o?BUG,hibernatejpql??sqlselect/*from   w  w  w.j  ava 2s. com*/
 * count(field1,field2,...),count()
 *
 * @param <E>
 * @param clazz
 * @return
 */
protected static <E> String getCountField(Class<E> clazz) {
    String out = "o";
    try {
        PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
        for (PropertyDescriptor propertydesc : propertyDescriptors) {
            Method method = propertydesc.getReadMethod();
            if (method != null && method.isAnnotationPresent(EmbeddedId.class)) {
                PropertyDescriptor[] ps = Introspector.getBeanInfo(propertydesc.getPropertyType())
                        .getPropertyDescriptors();
                out = "o." + propertydesc.getName() + "."
                        + (!ps[1].getName().equals("class") ? ps[1].getName() : ps[0].getName());
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return out;
}

From source file:org.jspare.jsdbc.stereotype.EntityUtils.java

/**
 * Find key by entity./* www . jav a  2s . c  om*/
 *
 * @param entity
 *            the entity
 * @param data
 *            the data
 * @return the string
 * @throws JsdbcException
 *             the jsdbc exception
 */
public static String findKeyByEntity(Entity entity, Object data) throws JsdbcException {
    try {

        if (entity.autoGenerateKey()) {

            return UUID.randomUUID().toString();
        }

        String findKeyByColumn = entity.key();
        for (Field field : data.getClass().getDeclaredFields()) {

            if (field.isAnnotationPresent(Key.class)
                    || (!StringUtils.isEmpty(findKeyByColumn) && field.getName().equals(findKeyByColumn))) {

                field.setAccessible(true);

                String value = field.get(data).toString();
                if (field.isAnnotationPresent(Cleaner.class)) {

                    Class<?> fieldCleanerClazz = field.getAnnotation(Cleaner.class).value();
                    Optional<FieldCleaner<?>> fieldCleaner = retrieveFieldCleanerInstance(fieldCleanerClazz);
                    if (fieldCleaner.isPresent()) {

                        value = (String) fieldCleaner.get().clean(field.get(data));
                    }
                }

                return value;
            }
        }
        for (Method method : data.getClass().getDeclaredMethods()) {

            if (method.isAnnotationPresent(Key.class)) {

                method.setAccessible(true);

                return method.invoke(data).toString();
            }
        }
    } catch (Exception e) {

        throw new JsdbcException(e.getMessage(), e);
    }
    throw new JsdbcException(String.format("Not found Key for entity class %s", data.getClass().getName()));
}

From source file:me.Laubi.MineMaze.SubCommands.java

private static boolean validateRegion(Region r, Method subCmd) {
    int maxHeight = -1, maxLength = -1, maxWidth = -1, minHeight = 1, minWidth = 5, minLength = 5;

    if (subCmd.isAnnotationPresent(SizeValidation.class)) {
        SizeValidation sizev = subCmd.getAnnotation(SizeValidation.class);
        maxHeight = sizev.maxHeight();/*w  ww. ja v a2  s  . c  o m*/
        maxLength = sizev.maxLength();
        maxWidth = sizev.maxWidth();
        minHeight = sizev.minHeight();
        minWidth = sizev.minWidth();
        minLength = sizev.minLength();
    }

    return !((r.getWidth() < minWidth) || (r.getHeight() < minHeight) || (r.getLength() < minLength) ||

            (maxWidth < 0 ? false : r.getWidth() > maxWidth)
            || (maxHeight < 0 ? false : r.getHeight() > maxHeight)
            || (maxLength < 0 ? false : r.getLength() > maxLength));
}