Example usage for java.lang.reflect Field isAnnotationPresent

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:net.ceos.project.poi.annotated.annotation.XlsFreeElementTest.java

/**
 * Test default configuration.// w  ww .  ja v  a 2s . c  om
 */
@Test
public void checkDefaultConfiguration() {
    Class<XMenFactory.ProfessorX> oC = XMenFactory.ProfessorX.class;

    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        // Process @XlsFreeElement
        if (f.isAnnotationPresent(XlsFreeElement.class)) {

            XlsFreeElement xlsFreeElement = (XlsFreeElement) f.getAnnotation(XlsFreeElement.class);

            if (f.getName().equals("stringFreeAttribute1")) {
                assertEquals(xlsFreeElement.showTitle(), false);
                assertEquals(xlsFreeElement.titleOrientation(), TitleOrientationType.TOP);
                assertEquals(xlsFreeElement.row(), 1);
                assertEquals(xlsFreeElement.cell(), 1);
                assertEquals(xlsFreeElement.comment(), "");
                assertEquals(xlsFreeElement.commentRules(), "");
                assertEquals(xlsFreeElement.decorator(), "");
                assertEquals(xlsFreeElement.formatMask(), "");
                assertEquals(xlsFreeElement.transformMask(), "");
                assertEquals(xlsFreeElement.isFormula(), false);
                assertEquals(xlsFreeElement.formula(), "");
                assertEquals(xlsFreeElement.customizedRules(), "");
                assertEquals(xlsFreeElement.columnWidthInUnits(), 0);
            }
        }
    }
}

From source file:com.ibm.amc.data.validation.ValidationEngine.java

/**
 * Validate the fields in an AbstractData according to the validation rules with which the
 * fields are annotated./*www . j  ava 2s . c o  m*/
 * 
 * @param resource
 *            The data object to validate
 * @throws AmcIllegalArgumentException
 *             if any field in the object contains data which is not valid according to its
 *             self-declared rules or the resource itself declares that it is not valid.
 */
public void validate(Object resource) throws AmcIllegalArgumentException {
    Field[] fields = resource.getClass().getDeclaredFields();

    nextField: for (Field field : fields) {
        if (field.isAnnotationPresent(JsonIgnore.class))
            continue nextField;
        if (field.getName().equals("this$0"))
            continue nextField; // Ignore parent instance
        // reference when resource
        // is an anonymous inner
        // class - only relevant for
        // unit tests.
        validate(field, resource);
    }

    if (resource instanceof SelfValidating) {
        ((SelfValidating) resource).validate();
    }

}

From source file:de.liedtke.format.JSONFormatter.java

@Override
public <T extends BasicEntity> String format(final T entity, final String... levels) throws FormatException {
    final JSONObject json = new JSONObject();
    boolean allAttributes = (levels == null || levels.length == 0);
    final List<String> levelList;
    if (levels == null || levels.length == 0) {
        levelList = new ArrayList<String>();
    } else {//from   ww  w . j  av a  2  s .co  m
        levelList = Arrays.asList(levels);
    }
    if (entity.getClass().isAnnotationPresent(Entity.class)) {
        final Field[] fields = entity.getClass().getDeclaredFields();
        for (final Field field : fields) {
            if (field.isAnnotationPresent(FormatPart.class)
                    && (allAttributes || levelList.contains(field.getAnnotation(FormatPart.class).level()))) {
                try {
                    final Method method = entity.getClass()
                            .getMethod(this.getGetter(field.getName(), field.getType()), (Class<?>[]) null);
                    final Object methodResult = method.invoke(entity);
                    if (methodResult != null) {
                        final String type = field.getType().toString();
                        if (type.equals("class com.google.appengine.api.datastore.Key")) {
                            json.put(field.getAnnotation(FormatPart.class).key(),
                                    KeyFactory.keyToString((Key) methodResult));
                        } else if (type.equals("class com.google.appengine.api.datastore.Text")) {
                            json.put(field.getAnnotation(FormatPart.class).key(),
                                    ((Text) methodResult).getValue());
                        } else {
                            json.put(field.getAnnotation(FormatPart.class).key(), methodResult.toString());
                        }
                    }
                } catch (IllegalAccessException e) {
                    logger.warning("IllegalAccessException occured: " + e.getMessage());
                    throw new FormatException();
                } catch (NoSuchMethodException e) {
                    logger.warning("NoSuchMethodException occured: " + e.getMessage());
                    throw new FormatException();
                } catch (SecurityException e) {
                    logger.warning("SecurityException occured: " + e.getMessage());
                    throw new FormatException();
                } catch (IllegalArgumentException e) {
                    logger.warning("IllegalArgumentException occured: " + e.getMessage());
                    throw new FormatException();
                } catch (InvocationTargetException e) {
                    logger.warning("InvocationTargetException occured: " + e.getMessage());
                    throw new FormatException();
                } catch (JSONException e) {
                    logger.warning("JSONException occured: " + e.getMessage());
                    throw new FormatException();
                }
            }
        }
    }

    return json.toString();
}

From source file:org.LexGrid.LexBIG.caCore.client.proxy.LexEVSProxyHelperImpl.java

protected List<Field> getAnnotatedFields(Object obj, Class annotation) {
    List<Field> returnList = new ArrayList<Field>();
    for (Field field : obj.getClass().getDeclaredFields()) {
        if (field.isAnnotationPresent(annotation)) {
            returnList.add(field);//w  w w . ja  va  2  s  .  c om
        }
    }
    return returnList;
}

From source file:org.al.swagger.v2.AbstractSpecCollector.java

public Object createSchemaObject(Class<?> aClass) {
    if (aClass.isArray()) {
        GenericSwaggerSchema schema = new GenericSwaggerSchema();
        schema.setType("array");
        schema.setCollectionFormat("csv");
        schema.setItems(createSchemaObject(aClass.getComponentType()));
        return schema;

    } else if (JDKPrimitiveType.isPrimitiveType(aClass)) {

        SchemaGenerator generator = SimpleTypeFactory.getInstance().getSchemaGenerator(aClass);
        if (generator != null) {
            return generator.generateSchema(aClass);
        } else {//from w w w  .  ja  v a2  s .c o  m
            throw new RuntimeException("Type " + aClass + " not supporeted");

        }

    } else {

        Map<String, Object> schemaMap = new LinkedHashMap<>();

        Map<String, Object> properties = new LinkedHashMap<>();
        schemaMap.put("properties", properties);

        List<Field> fields = Stream.of(aClass.getDeclaredFields())
                .filter(f -> !f.isAnnotationPresent(JsonIgnore.class) && !Modifier.isStatic(f.getModifiers()))
                .collect(Collectors.toList());
        for (Field f : fields) {
            if (f.getName().equalsIgnoreCase("rowId")) {
                properties.put(f.getName(), SimpleTypeFactory.getInstance().getSchemaGenerator(String.class)
                        .generateSchema(String.class));
            } else {
                Object schemaObject = createSchemaObject(f.getType());
                properties.put(f.getName(), schemaObject);
            }

        }

        return schemaMap;
    }

}

From source file:de.taimos.dvalin.test.jaxrs.TestProxyBeanPostProcessor.java

private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {/* w  ww  .j  a v a 2 s.  c om*/
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(TestProxy.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException("@TestProxy annotation is not supported on static fields");
                }
                currElements.add(new TestProxyElement(field, null));
            }
        }
        for (Method method : targetClass.getDeclaredMethods()) {
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                continue;
            }
            if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (bridgedMethod.isAnnotationPresent(TestProxy.class)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException(
                                "@TestProxy annotation is not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException(
                                "@TestProxy annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new TestProxyElement(method, pd));
                }
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while ((targetClass != null) && (targetClass != Object.class));

    return new InjectionMetadata(clazz, elements);
}

From source file:com.higgses.griffin.annotation.app.GinInjector.java

/**
 * ??/*from w w w. j  a v a 2  s. c om*/
 * 
 * @param object
 * @param field
 */
private void injectResource(Object object, Field field) {
    if (field.isAnnotationPresent(GinInjectResource.class)) {
        GinInjectResource resourceJect = field.getAnnotation(GinInjectResource.class);
        int resourceID = resourceJect.id();
        try {
            Activity activity = null;
            if (object instanceof Activity) {
                activity = (Activity) object;
            } else if (object instanceof Fragment) {
                activity = ((Fragment) object).getActivity();
            }
            field.setAccessible(true);
            Resources resources = activity.getResources();
            String type = resources.getResourceTypeName(resourceID);
            if (type.equalsIgnoreCase("string")) {
                field.set(activity, activity.getResources().getString(resourceID));
            } else if (type.equalsIgnoreCase("drawable")) {
                field.set(activity, activity.getResources().getDrawable(resourceID));
            } else if (type.equalsIgnoreCase("layout")) {
                field.set(activity, activity.getResources().getLayout(resourceID));
            } else if (type.equalsIgnoreCase("array")) {
                if (field.getType().equals(int[].class)) {
                    field.set(activity, activity.getResources().getIntArray(resourceID));
                } else if (field.getType().equals(String[].class)) {
                    field.set(activity, activity.getResources().getStringArray(resourceID));
                } else {
                    field.set(activity, activity.getResources().getStringArray(resourceID));
                }

            } else if (type.equalsIgnoreCase("color")) {
                if (field.getType().equals(Integer.TYPE)) {
                    field.set(activity, activity.getResources().getColor(resourceID));
                } else {
                    field.set(activity, activity.getResources().getColorStateList(resourceID));
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Builds the enum dict.//from w  w w . ja  v  a 2 s  .  com
 *
 * @param <E> the element type
 * @param c   the c
 * @return the map
 */
private static <E extends Enum<E>> Map<String, ExchangeVersion> buildEnumDict(Class<E> c) {
    Map<String, ExchangeVersion> dict = new HashMap<String, ExchangeVersion>();
    Field[] fields = c.getDeclaredFields();
    for (Field f : fields) {
        if (f.isEnumConstant() && f.isAnnotationPresent(RequiredServerVersion.class)) {
            RequiredServerVersion ewsEnum = f.getAnnotation(RequiredServerVersion.class);
            String fieldName = f.getName();
            ExchangeVersion exchangeVersion = ewsEnum.version();
            dict.put(fieldName, exchangeVersion);
        }
    }
    return dict;
}

From source file:net.ceos.project.poi.annotated.annotation.XlsFreeElementTest.java

/**
 * Test initialization of the title attribute according
 * <ul>//from   w ww.ja va 2  s  .  c  o  m
 * <li>the title
 * <li>is title visible
 * <li>title orientation
 * <li>start row and cell
 * </ul>
 */
@Test
public void checkTitleAttribute() {
    Class<XMenFactory.ProfessorX> oC = XMenFactory.ProfessorX.class;

    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        // Process @XlsFreeElement
        if (f.isAnnotationPresent(XlsFreeElement.class)) {

            XlsFreeElement xlsFreeElement = (XlsFreeElement) f.getAnnotation(XlsFreeElement.class);

            if (f.getName().equals("stringFreeAttribute1")) {
                assertEquals(xlsFreeElement.showTitle(), false);
                assertEquals(xlsFreeElement.title(), "String free element 1");
                assertEquals(xlsFreeElement.row(), 1);
                assertEquals(xlsFreeElement.cell(), 1);

            } else if (f.getName().equals("stringFreeAttribute2")) {
                assertEquals(xlsFreeElement.showTitle(), true);
                assertEquals(xlsFreeElement.titleOrientation(), TitleOrientationType.BOTTOM);
                assertEquals(xlsFreeElement.title(), "String free element 2");
                assertEquals(xlsFreeElement.row(), 1);
                assertEquals(xlsFreeElement.cell(), 2);

            } else if (f.getName().equals("stringFreeAttribute3")) {
                assertEquals(xlsFreeElement.showTitle(), false);
                assertEquals(xlsFreeElement.title(), "String free element 3");
                assertEquals(xlsFreeElement.row(), 1);
                assertEquals(xlsFreeElement.cell(), 3);

            } else if (f.getName().equals("stringFreeAttribute4")) {
                assertEquals(xlsFreeElement.showTitle(), true);
                assertEquals(xlsFreeElement.titleOrientation(), TitleOrientationType.RIGHT);
                assertEquals(xlsFreeElement.title(), "String free element 4");
                assertEquals(xlsFreeElement.row(), 1);
                assertEquals(xlsFreeElement.cell(), 4);
            }
        }
    }
}

From source file:de.taimos.dvalin.jaxrs.remote.RemoteServiceBeanPostProcessor.java

private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {//w  w  w.  j a va2  s  . c o m
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(RemoteService.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException(
                            "@RemoteService annotation is not supported on static fields");
                }
                currElements.add(new RemoteServiceElement(field, field, null));
            }
        }
        for (Method method : targetClass.getDeclaredMethods()) {
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                continue;
            }
            if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (bridgedMethod.isAnnotationPresent(RemoteService.class)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException(
                                "@RemoteService annotation is not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException(
                                "@RemoteService annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new RemoteServiceElement(method, bridgedMethod, pd));
                }
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while ((targetClass != null) && (targetClass != Object.class));

    return new InjectionMetadata(clazz, elements);
}