Example usage for java.lang Class getAnnotation

List of usage examples for java.lang Class getAnnotation

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) 

Source Link

Usage

From source file:fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzer.java

@PostConstruct
public void postConstruct() throws BeansException, NoSuchMethodException, IllegalAccessException,
        InvocationTargetException, InstantiationException {
    mappingTablesExpected = new ArrayList<>();
    nestedTables = new ArrayList<>();
    Reflections reflections = new Reflections(scanMapping);
    Set<Class<?>> types = reflections.getTypesAnnotatedWith(MysqlMapping.class);
    final Iterator<Class<?>> iterator = types.iterator();
    while (iterator.hasNext()) {
        Class classDomain = iterator.next();
        MysqlMapping mysqlMapping = (MysqlMapping) classDomain.getAnnotation(MysqlMapping.class);
        DomainClass domainClass = new DomainClass();
        domainClass.setDomainClass(classDomain);
        mappingTablesExpected.add(mysqlMapping.table());
        CrudRepository crudRepository = (CrudRepository) applicationContext.getBean(mysqlMapping.repository());
        domainClass.setCrudRepository(crudRepository);
        domainClass.setTable(mysqlMapping.table());
        Map<String, SQLRequester> nestedClassesMap = new HashMap<>();
        for (Field field : classDomain.getDeclaredFields()) {
            NestedMapping nestedMapping = field.getAnnotation(NestedMapping.class);
            if (nestedMapping != null) {
                Class sqlRequesterClass = nestedMapping.sqlAssociaton().getRequesterClass();
                Constructor sqlRequesterConstructor = sqlRequesterClass.getConstructor();
                SQLRequester sqlRequester = (SQLRequester) sqlRequesterConstructor.newInstance();
                sqlRequester.setDatabaseName(databaseName);
                sqlRequester.setEntryTableName(mysqlMapping.table());
                sqlRequester.setExitTableName(nestedMapping.table());
                sqlRequester.setForeignKey(nestedMapping.foreignKey());
                sqlRequester.setPrimaryKeyForeignEntity(nestedMapping.primaryKey());
                sqlRequester.setEntryType(classDomain);
                sqlRequester.setAssociatedField(field);
                Class foreignType = field.getType();
                if (field.getGenericType() instanceof ParameterizedType) {
                    ParameterizedType genericType = (ParameterizedType) field.getGenericType();
                    Class properType = (Class) genericType.getActualTypeArguments()[0];
                    foreignType = properType;
                }/*from   w  w w  .  j a v a 2 s .  com*/
                sqlRequester.setForeignType(foreignType);
                sqlRequester.setJdbcTemplate(jdbcTemplate);
                NestedRowMapper currentClassNestedRowMapper = new NestedRowMapper(classDomain, this,
                        mysqlMapping.table());
                NestedRowMapper foreignClassNestedRowMapper = new NestedRowMapper(foreignType, this,
                        mysqlMapping.table());
                sqlRequester.setRowMapper(currentClassNestedRowMapper);
                sqlRequester.setForeignRowMapper(foreignClassNestedRowMapper);
                nestedClassesMap.put(field.getName(), sqlRequester);
                nestedTables.add(nestedMapping.table());
                nestedDomainClassMap.put(nestedMapping.table(), domainClass);
            }
        }
        domainClass.setSqlRequesters(nestedClassesMap);
        domainClassMap.put(domainClass.getTable(), domainClass);
    }
    if (environment.getProperty("date.output") != null) {
        binlogOutputDateFormatter = new SimpleDateFormat(environment.getProperty("date.output"));
    }
}

From source file:com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBReflector.java

/**
 * Returns the {@link DynamoDBTable} annotation of the class given, throwing
 * a runtime exception if it isn't annotated.
 *//*from   www  . j  a va 2  s . co  m*/
<T> DynamoDBTable getTable(Class<T> clazz) {
    DynamoDBTable table = clazz.getAnnotation(DynamoDBTable.class);
    if (table == null)
        throw new DynamoDBMappingException("Class " + clazz + " must be annotated with " + DynamoDBTable.class);
    return table;
}

From source file:com.sixt.service.framework.injection.ServiceRegistryModule.java

private Object findServiceRegistryPlugin(Injector injector) {
    Object retval = null;/*from  www .  j a v a2  s.c om*/
    String pluginName = serviceProperties.getProperty("registry");
    if (StringUtils.isBlank(pluginName)) {
        return null;
    }
    if (serviceRegistryPlugins == null) { // only scan if not already set
        serviceRegistryPlugins = new FastClasspathScanner().scan()
                .getNamesOfClassesWithAnnotation(ServiceRegistryPlugin.class);
    }
    boolean found = false;
    for (String plugin : serviceRegistryPlugins) {
        try {
            @SuppressWarnings("unchecked")
            Class<? extends ServiceRegistryPlugin> pluginClass = (Class<? extends ServiceRegistryPlugin>) Class
                    .forName(plugin);
            ServiceRegistryPlugin anno = pluginClass.getAnnotation(ServiceRegistryPlugin.class);
            if (anno != null && pluginName.equals(anno.name())) {
                retval = injector.getInstance(pluginClass);
                found = true;
                break;
            }
        } catch (ClassNotFoundException e) {
            logger.error("ServiceRegistryPlugin not found", e);
        }
    }
    if (!found) {
        logger.warn("Registry plugin '{}' was not found in the class path", pluginName);
    }
    return retval;
}

From source file:com.proteanplatform.protean.entity.EntityTableCellMetadata.java

/**
 * <p>The representative of the an object cell must be a string or a number.  We let the
 * admin annotation argument "cellMethod" determine which method should return a 
 * legal represenation.  If this is itself an object, we repeat the procedure. </p>
 * //  w w  w.  j av  a2  s  . c  o m
 * @param cell
 * @param method
 * @throws NoSuchMethodException
 */
private void calculateObjectCell(Method method) throws NoSuchMethodException {
    methods.add(method);
    Class<?> rtype = method.getReturnType();

    while (Object.class.isAssignableFrom(rtype)) {

        if (rtype.isAnnotationPresent(Protean.class)) {
            Protean adm = rtype.getAnnotation(Protean.class);

            // we must insist that the method supplied must exist and must take no arguments
            try {
                method = rtype.getMethod(adm.cellMethod(), new Class[0]);
            } catch (Exception e) {
                method = null;
            }

            if (method == null) {
                method = rtype.getMethod("toString", new Class[0]);
            }
        }

        else {
            method = rtype.getMethod("toString", new Class[0]);
        }

        rtype = method.getReturnType();
        methods.add(method);

        if (String.class.isAssignableFrom(rtype)) {
            break; // Otherwise, the loop might never end.
        }
    }
}

From source file:com.github.reinert.jjschema.v1.CustomSchemaWrapper.java

protected void processAttributes(ObjectNode node, Class<?> type) {
    final Attributes attributes = type.getAnnotation(Attributes.class);
    if (attributes != null) {
        //node.put("$schema", SchemaVersion.DRAFTV4.getLocation().toString());
        if (!attributes.id().isEmpty()) {
            node.put("id", attributes.id());
        }//from ww  w  . j  av  a2  s .  c  o m
        if (!attributes.description().isEmpty()) {
            node.put("description", attributes.description());
        }
        if (!attributes.pattern().isEmpty()) {
            node.put("pattern", attributes.pattern());
        }
        if (!attributes.title().isEmpty()) {
            node.put("title", attributes.title());
        }
        if (attributes.maximum() > -1) {
            node.put("maximum", attributes.maximum());
        }
        if (attributes.exclusiveMaximum()) {
            node.put("exclusiveMaximum", true);
        }
        if (attributes.minimum() > -1) {
            node.put("minimum", attributes.minimum());
        }
        if (attributes.exclusiveMinimum()) {
            node.put("exclusiveMinimum", true);
        }
        if (attributes.enums().length > 0) {
            ArrayNode enumArray = node.putArray("enum");
            String[] enums = attributes.enums();
            for (String v : enums) {
                enumArray.add(v);
            }
        }
        if (attributes.uniqueItems()) {
            node.put("uniqueItems", true);
        }
        if (attributes.minItems() > 0) {
            node.put("minItems", attributes.minItems());
        }
        if (attributes.maxItems() > -1) {
            node.put("maxItems", attributes.maxItems());
        }
        if (attributes.multipleOf() > 0) {
            node.put("multipleOf", attributes.multipleOf());
        }
        if (attributes.minLength() > 0) {
            node.put("minLength", attributes.minItems());
        }
        if (attributes.maxLength() > -1) {
            node.put("maxLength", attributes.maxItems());
        }
        if (attributes.required()) {
            setRequired(true);
        }
        if (attributes.readonly()) {
            node.put("readonly", attributes.readonly());
        }
    }
}

From source file:de.Keyle.MyPet.api.util.service.ServiceManager.java

/**
 * register new services here. A service needs the {@link ServiceName} annotation to be accepted.
 *
 * @param serviceClass the service class
 *///from   w  ww. j  a va  2 s . c o  m
public void registerService(Class<? extends ServiceContainer> serviceClass) {
    Load.State loadingState = Load.State.OnEnable;
    if (serviceClass.isAnnotationPresent(Load.class)) {
        loadingState = serviceClass.getAnnotation(Load.class).value();
    }
    try {
        ServiceContainer service = serviceClass.newInstance();
        registeredServices.put(loadingState, service);
    } catch (Throwable e) {
        MyPetApi.getLogger()
                .warning("Error occured while creating the " + serviceClass.getName() + " service.");
        e.printStackTrace();
    }
}

From source file:de.extra.client.core.annotation.PropertyPlaceholderPluginConfigurer.java

private void setPluginProperties(final ConfigurableListableBeanFactory beanFactory, final Properties properties,
        final String beanName, final Class<?> clazz) {
    final PluginConfiguration annotationConfigutation = clazz.getAnnotation(PluginConfiguration.class);
    final MutablePropertyValues mutablePropertyValues = beanFactory.getBeanDefinition(beanName)
            .getPropertyValues();/*  w w w .  j a  v  a2s . com*/

    for (final PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
        final Method setter = property.getWriteMethod();
        PluginValue valueAnnotation = null;
        if (setter != null && setter.isAnnotationPresent(PluginValue.class)) {
            valueAnnotation = setter.getAnnotation(PluginValue.class);
        }
        if (valueAnnotation != null) {
            final String key = extractKey(annotationConfigutation, valueAnnotation, clazz);
            final String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
            if (StringUtils.isEmpty(value)) {
                throw new BeanCreationException(beanName,
                        "No such property=[" + key + "] found in properties.");
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("setting property=[" + clazz.getName() + "." + property.getName() + "] value=[" + key
                        + "=" + value + "]");
            }
            mutablePropertyValues.addPropertyValue(property.getName(), value);
        }
    }

    for (final Field field : clazz.getDeclaredFields()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("examining field=[" + clazz.getName() + "." + field.getName() + "]");
        }
        if (field.isAnnotationPresent(PluginValue.class)) {
            final PluginValue valueAnnotation = field.getAnnotation(PluginValue.class);
            final PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

            if (property == null || property.getWriteMethod() == null) {
                throw new BeanCreationException(beanName,
                        "setter for property=[" + clazz.getName() + "." + field.getName() + "] not available.");
            }
            final String key = extractKey(annotationConfigutation, valueAnnotation, clazz);
            String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
            if (value == null) {
                // DEFAULT Value suchen
                final int separatorIndex = key.indexOf(VALUE_SEPARATOR);
                if (separatorIndex != -1) {
                    final String actualPlaceholder = key.substring(0, separatorIndex);
                    final String defaultValue = key.substring(separatorIndex + VALUE_SEPARATOR.length());
                    value = resolvePlaceholder(actualPlaceholder, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                    if (value == null) {
                        value = defaultValue;
                    }
                }
            }

            if (value != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("setting property=[" + clazz.getName() + "." + field.getName() + "] value=[" + key
                            + "=" + value + "]");
                }
                mutablePropertyValues.addPropertyValue(field.getName(), value);
            } else if (!ignoreNullValues) {
                throw new BeanCreationException(beanName,
                        "No such property=[" + key + "] found in properties.");
            }
        }
    }
}

From source file:com.braffdev.server.core.module.containerhandler.mapper.clazz.ClassMapper.java

/**
 * @param clazz/* w w w  .j  a  v a 2  s.  co m*/
 * @param container
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
private void mapComponent(Class<?> clazz, Container container)
        throws InstantiationException, IllegalAccessException {
    if (this.isComponent(clazz)) {
        Object instance = this.getInstance(clazz, container);

        String name = clazz.getAnnotation(Component.class).value();
        if (StringUtils.isBlank(name)) {
            // use the default name if no other name is provided
            name = DependencyInjectionUtils.getDefaultName(clazz);
        }
        container.getDependencyRegistry().put(name, instance);
    }
}

From source file:me.bayes.vertx.vest.VestApplication.java

public void addEndpointClasses(Class<?>... endpointClasses) {
    for (Class<?> clazz : endpointClasses) {
        if (clazz.getAnnotation(Path.class) != null) {
            this.endpointClasses.add(clazz);
        }/*w  w  w  .j  ava  2s  .  co  m*/
    }
}

From source file:me.bayes.vertx.vest.VestApplication.java

/**
 * @param endpointClasses/*from   w  w  w. ja  v  a  2  s  . co  m*/
 *            to add to the classes annotated with {@link Path}. If not
 *            annotated with {@link Path} it will be ignored.
 */
public void addEndpointClasses(Collection<Class<?>> endpointClasses) {
    for (Class<?> clazz : endpointClasses) {
        if (clazz.getAnnotation(Path.class) != null) {
            this.endpointClasses.add(clazz);
        }
    }
}