Example usage for java.lang Class getAnnotations

List of usage examples for java.lang Class getAnnotations

Introduction

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

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

public void scanEntityClass(Class entityClass, boolean selectiveRendering) {
    Class annClass = entityClass;
    while (annClass != null) {
        for (Annotation annotation : annClass.getAnnotations()) {
            if (COLLECT_ANNOTATIONS.contains(annotation.annotationType())
                    && !annotations.contains(annotation)) {
                putTableAnnotation(annotation);
            }//from  w  w w  . j av  a 2 s.  c o  m
        }
        if (baseClass.equals(getClassOfTableAnnotation(annClass))) {
            annClass = annClass.getSuperclass();
        } else {
            break;
        }
    }

    com.github.gekoh.yagen.api.Table addTblInfo = (com.github.gekoh.yagen.api.Table) entityClass
            .getAnnotation(com.github.gekoh.yagen.api.Table.class);
    if (addTblInfo != null && addTblInfo.additionalSequences().length > 0) {
        sequences.addAll(Arrays.asList(addTblInfo.additionalSequences()));
    }

    processTypeAnnotations(entityClass, selectiveRendering);

    addI18NInfo(entityClass.getDeclaredFields());
    addI18NInfo(entityClass.getDeclaredMethods());

    gatherPkColumn(entityClass);
    gatherEnumCheckConstraints(entityClass);
    gatherCascade(entityClass);
    gatherDeferrable(entityClass);
}

From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java

@SuppressWarnings("rawtypes")
private String getTableName(Class clazz) {
    for (Annotation a : clazz.getAnnotations()) {
        if (a instanceof javax.persistence.Table) {
            return ((javax.persistence.Table) a).name();
        }//from  w  ww  .java2  s. c o m
    }
    return null;
}

From source file:com.adaptris.core.runtime.AdapterRegistry.java

@Override
public String getClassDefinition(String className) throws CoreException {
    final ClassDescriptor classDescriptor = new ClassDescriptor(className);
    try {//w  w w . j  a  va2  s .c o  m
        Class<?> clazz = Class.forName(className);

        classDescriptor.setClassType(ClassDescriptor.ClassType.getTypeForClass(clazz).name().toLowerCase());

        List<String> displayOrder = new ArrayList<>();
        for (Annotation annotation : clazz.getAnnotations()) {
            if (XStreamAlias.class.isAssignableFrom(annotation.annotationType())) {
                classDescriptor.setAlias(((XStreamAlias) annotation).value());
            } else if (ComponentProfile.class.isAssignableFrom(annotation.annotationType())) {
                classDescriptor.setTags(((ComponentProfile) annotation).tag());
                classDescriptor.setSummary(((ComponentProfile) annotation).summary());
            } else if (DisplayOrder.class.isAssignableFrom(annotation.annotationType())) {
                displayOrder = Arrays.asList(((DisplayOrder) annotation).order());
            }
        }

        for (Field field : clazz.getDeclaredFields()) {
            if ((!Modifier.isStatic(field.getModifiers()))
                    && (field.getDeclaredAnnotation(Transient.class) == null)) { // if we're not transient
                ClassDescriptorProperty fieldProperty = new ClassDescriptorProperty();
                fieldProperty.setOrder(
                        displayOrder.contains(field.getName()) ? displayOrder.indexOf(field.getName()) + 1
                                : 999);
                fieldProperty.setAdvanced(false);
                fieldProperty.setClassName(field.getType().getName());
                fieldProperty.setType(field.getType().getSimpleName());
                fieldProperty.setName(field.getName());
                fieldProperty.setAutoPopulated(field.getDeclaredAnnotation(AutoPopulated.class) != null);
                fieldProperty.setNullAllowed(field.getDeclaredAnnotation(NotNull.class) != null);

                for (Annotation annotation : field.getDeclaredAnnotations()) {
                    if (AdvancedConfig.class.isAssignableFrom(annotation.annotationType())) {
                        fieldProperty.setAdvanced(true);
                    } else if (InputFieldDefault.class.isAssignableFrom(annotation.annotationType())) {
                        fieldProperty.setDefaultValue(((InputFieldDefault) annotation).value());
                    }
                }
                classDescriptor.getClassDescriptorProperties().add(fieldProperty);
            }
        }

        try (ScanResult result = new ClassGraph().enableAllInfo().blacklistPackages(FCS_BLACKLIST).scan()) {

            List<String> subclassNames = result.getSubclasses(className).getNames();

            for (String subclassName : subclassNames) {
                classDescriptor.getSubTypes().add(subclassName);
            }
        }

    } catch (ClassNotFoundException e) {
        throw new CoreException(e);
    }
    return new XStreamJsonMarshaller().marshal(classDescriptor);
}

From source file:org.apache.hadoop.metrics2.lib.MetricsSourceBuilder.java

private MetricsRegistry initRegistry(Object source) {
    Class<?> cls = source.getClass();
    MetricsRegistry r = null;/*from  w w  w.j  av a  2  s . c om*/
    // Get the registry if it already exists.
    for (Field field : ReflectionUtils.getDeclaredFieldsIncludingInherited(cls)) {
        if (field.getType() != MetricsRegistry.class)
            continue;
        try {
            field.setAccessible(true);
            r = (MetricsRegistry) field.get(source);
            hasRegistry = r != null;
            break;
        } catch (Exception e) {
            LOG.warn("Error accessing field " + field, e);
            continue;
        }
    }
    // Create a new registry according to annotation
    for (Annotation annotation : cls.getAnnotations()) {
        if (annotation instanceof Metrics) {
            Metrics ma = (Metrics) annotation;
            info = factory.getInfo(cls, ma);
            if (r == null) {
                r = new MetricsRegistry(info);
            }
            r.setContext(ma.context());
        }
    }
    if (r == null)
        return new MetricsRegistry(cls.getSimpleName());
    return r;
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkConverter.java

/**
 * Looks for converter mappings for the specified class and adds it to an existing map.  Only new converters are
 * added.  If a converter is defined on a key that already exists, the converter is ignored.
 *
 * @param mapping an existing map to add new converter mappings to
 * @param clazz   class to look for converter mappings for
 *///from  w  w w. j  av a2 s.  c o  m
protected void addConverterMapping(Map<String, Object> mapping, Class clazz) {
    // Process <clazz>-conversion.properties file
    String converterFilename = buildConverterFilename(clazz);
    fileProcessor.process(mapping, clazz, converterFilename);

    // Process annotations
    Annotation[] annotations = clazz.getAnnotations();

    for (Annotation annotation : annotations) {
        if (annotation instanceof Conversion) {
            Conversion conversion = (Conversion) annotation;
            for (TypeConversion tc : conversion.conversions()) {
                if (mapping.containsKey(tc.key())) {
                    break;
                }
                if (LOG.isDebugEnabled()) {
                    if (StringUtils.isEmpty(tc.key())) {
                        LOG.debug("WARNING! key of @TypeConversion [#0] applied to [#1] is empty!",
                                tc.converter(), clazz.getName());
                    } else {
                        LOG.debug("TypeConversion [#0] with key: [#1]", tc.converter(), tc.key());
                    }
                }
                annotationProcessor.process(mapping, tc, tc.key());
            }
        }
    }

    // Process annotated methods
    for (Method method : clazz.getMethods()) {
        annotations = method.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof TypeConversion) {
                TypeConversion tc = (TypeConversion) annotation;
                if (mapping.containsKey(tc.key())) {
                    break;
                }
                String key = tc.key();
                // Default to the property name
                if (StringUtils.isEmpty(key)) {
                    key = AnnotationUtils.resolvePropertyName(method);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Retrieved key [#0] from method name [#1]", key, method.getName());
                    }
                }
                annotationProcessor.process(mapping, tc, key);
            }
        }
    }
}

From source file:com.opensymphony.xwork2.validator.AnnotationValidationConfigurationBuilder.java

private List<ValidatorConfig> processAnnotations(Object o) {

    List<ValidatorConfig> result = new ArrayList<ValidatorConfig>();

    String fieldName = null;//from   w w w.ja v a 2 s  . co  m
    String methodName = null;

    Annotation[] annotations = null;

    if (o instanceof Class) {
        Class clazz = (Class) o;
        annotations = clazz.getAnnotations();
    }

    if (o instanceof Method) {
        Method method = (Method) o;
        fieldName = resolvePropertyName(method);
        methodName = method.getName();

        annotations = method.getAnnotations();
    }

    if (annotations != null) {
        for (Annotation a : annotations) {

            // Process collection of custom validations
            if (a instanceof Validations) {
                processValidationAnnotation(a, fieldName, methodName, result);

            }

            // Process single custom validator
            if (a instanceof Validation) {
                Validation v = (Validation) a;
                if (v.validations() != null) {
                    for (Validations val : v.validations()) {
                        processValidationAnnotation(val, fieldName, methodName, result);
                    }
                }
            }
            // Process single custom validator
            else if (a instanceof ExpressionValidator) {
                ExpressionValidator v = (ExpressionValidator) a;
                ValidatorConfig temp = processExpressionValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process single custom validator
            else if (a instanceof CustomValidator) {
                CustomValidator v = (CustomValidator) a;
                ValidatorConfig temp = processCustomValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process ConversionErrorFieldValidator
            else if (a instanceof ConversionErrorFieldValidator) {
                ConversionErrorFieldValidator v = (ConversionErrorFieldValidator) a;
                ValidatorConfig temp = processConversionErrorFieldValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }

            }
            // Process DateRangeFieldValidator
            else if (a instanceof DateRangeFieldValidator) {
                DateRangeFieldValidator v = (DateRangeFieldValidator) a;
                ValidatorConfig temp = processDateRangeFieldValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }

            }
            // Process EmailValidator
            else if (a instanceof EmailValidator) {
                EmailValidator v = (EmailValidator) a;
                ValidatorConfig temp = processEmailValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process FieldExpressionValidator
            else if (a instanceof FieldExpressionValidator) {
                FieldExpressionValidator v = (FieldExpressionValidator) a;
                ValidatorConfig temp = processFieldExpressionValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process IntRangeFieldValidator
            else if (a instanceof IntRangeFieldValidator) {
                IntRangeFieldValidator v = (IntRangeFieldValidator) a;
                ValidatorConfig temp = processIntRangeFieldValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process ShortRangeFieldValidator
            else if (a instanceof ShortRangeFieldValidator) {
                ShortRangeFieldValidator v = (ShortRangeFieldValidator) a;
                ValidatorConfig temp = processShortRangeFieldValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process DoubleRangeFieldValidator
            else if (a instanceof DoubleRangeFieldValidator) {
                DoubleRangeFieldValidator v = (DoubleRangeFieldValidator) a;
                ValidatorConfig temp = processDoubleRangeFieldValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process RequiredFieldValidator
            else if (a instanceof RequiredFieldValidator) {
                RequiredFieldValidator v = (RequiredFieldValidator) a;
                ValidatorConfig temp = processRequiredFieldValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process RequiredStringValidator
            else if (a instanceof RequiredStringValidator) {
                RequiredStringValidator v = (RequiredStringValidator) a;
                ValidatorConfig temp = processRequiredStringValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process StringLengthFieldValidator
            else if (a instanceof StringLengthFieldValidator) {
                StringLengthFieldValidator v = (StringLengthFieldValidator) a;
                ValidatorConfig temp = processStringLengthFieldValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process UrlValidator
            else if (a instanceof UrlValidator) {
                UrlValidator v = (UrlValidator) a;
                ValidatorConfig temp = processUrlValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }

            }
            // Process ConditionalVisitorFieldValidator
            else if (a instanceof ConditionalVisitorFieldValidator) {
                ConditionalVisitorFieldValidator v = (ConditionalVisitorFieldValidator) a;
                ValidatorConfig temp = processConditionalVisitorFieldValidatorAnnotation(v, fieldName,
                        methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process VisitorFieldValidator
            else if (a instanceof VisitorFieldValidator) {
                VisitorFieldValidator v = (VisitorFieldValidator) a;
                ValidatorConfig temp = processVisitorFieldValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
            // Process RegexFieldValidator
            else if (a instanceof RegexFieldValidator) {
                RegexFieldValidator v = (RegexFieldValidator) a;
                ValidatorConfig temp = processRegexFieldValidatorAnnotation(v, fieldName, methodName);
                if (temp != null) {
                    result.add(temp);
                }
            }
        }
    }
    return result;
}

From source file:org.kuali.rice.krad.data.provider.annotation.impl.AnnotationMetadataProviderImpl.java

/**
 * Handle annotations made at the class level and add their data to the given metadata object.
  *//from   www .j av a 2  s . co m
  * @param clazz the class to process.
 * @param metadata the metadata for the class.
 * @return <b>true</b> if any annotations are found.
 */
protected boolean processClassLevelAnnotations(Class<?> clazz, DataObjectMetadataImpl metadata) {
    boolean classAnnotationFound = false;
    boolean fieldAnnotationsFound = false;
    // get the class annotations
    List<DataObjectAttribute> attributes = new ArrayList<DataObjectAttribute>(metadata.getAttributes());
    Annotation[] classAnnotations = clazz.getAnnotations();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Class-level annotations: " + Arrays.asList(classAnnotations));
    }
    for (Annotation a : classAnnotations) {
        // check if it's one we can handle
        // do something with it
        if (processAnnotationsforCommonMetadata(a, metadata)) {
            classAnnotationFound = true;
            continue;
        }
        if (a instanceof MergeAction) {
            MetadataMergeAction mma = ((MergeAction) a).value();
            if (!(mma == MetadataMergeAction.MERGE || mma == MetadataMergeAction.REMOVE)) {
                throw new MetadataConfigurationException(
                        "Only the MERGE and REMOVE merge actions are supported since the annotation metadata provider can not specify all required properties and may only be used as an overlay.");
            }
            metadata.setMergeAction(mma);
            classAnnotationFound = true;
            continue;
        }
        if (a instanceof UifAutoCreateViews) {
            metadata.setAutoCreateUifViewTypes(Arrays.asList(((UifAutoCreateViews) a).value()));
            classAnnotationFound = true;
        }
    }
    if (fieldAnnotationsFound) {
        metadata.setAttributes(attributes);
    }
    return classAnnotationFound;
}

From source file:org.entando.entando.plugins.jpoauthclient.aps.system.services.client.ProviderConnectionManager.java

private Object unmarshallResponse(InputStream stream, Class expectedType, MediaType responseType) {
    Object bodyObject = null;/*ww  w . j  a  v  a 2s  .c  om*/
    try {
        if (responseType.equals(MediaType.APPLICATION_JSON_TYPE)) {
            JSONProvider jsonProvider = new JSONProvider();
            bodyObject = jsonProvider.readFrom(expectedType, expectedType.getGenericSuperclass(),
                    expectedType.getAnnotations(), MediaType.APPLICATION_JSON_TYPE, null, stream);
        } else {
            JAXBContext context = JAXBContext.newInstance(expectedType);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            bodyObject = (Object) unmarshaller.unmarshal(stream);
        }
    } catch (Throwable t) {
        _logger.error("Error unmarshalling response result", t);
    }
    return bodyObject;
}

From source file:adalid.core.AbstractArtifact.java

void annotate(Class<?> type) {
    if (type == null) {
        return;//from w  w w.ja  va 2  s  .  co m
    }
    Annotation[] annotations = type.getAnnotations();
    List<Class<? extends Annotation>> valid = getValidTypeAnnotations();
    checkAnnotations(type, annotations, valid);
}

From source file:org.springframework.context.annotation.ConfigurationClassParser.java

/**
 * Factory method to obtain a {@link SourceClass} from a {@link Class}.
 *//*  ww  w.j  a v a  2  s  .c o m*/
SourceClass asSourceClass(@Nullable Class<?> classType) throws IOException {
    if (classType == null) {
        return new SourceClass(Object.class);
    }
    try {
        // Sanity test that we can read annotations, if not fall back to ASM
        classType.getAnnotations();
        return new SourceClass(classType);
    } catch (Throwable ex) {
        // Enforce ASM via class name resolution
        return asSourceClass(classType.getName());
    }
}