Java Code Examples for io.micronaut.core.annotation.AnnotationMetadata

The following examples show how to use io.micronaut.core.annotation.AnnotationMetadata. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: micronaut-kafka   Source File: KafkaHeaderBinder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public BindingResult<T> bind(ArgumentConversionContext<T> context, ConsumerRecord<?, ?> source) {
    Headers headers = source.headers();
    AnnotationMetadata annotationMetadata = context.getAnnotationMetadata();

    String name = annotationMetadata.getValue(Header.class, "name", String.class)
                                    .orElseGet(() -> annotationMetadata.getValue(Header.class, String.class)
                                                                       .orElse(context.getArgument().getName()));
    Iterable<org.apache.kafka.common.header.Header> value = headers.headers(name);

    if (value.iterator().hasNext()) {
        Optional<T> converted = ConversionService.SHARED.convert(value, context);
        return () -> converted;
    } else if (context.getArgument().getType() == Optional.class) {
        //noinspection unchecked
        return () -> (Optional<T>) Optional.of(Optional.empty());
    } else {
        //noinspection unchecked
        return BindingResult.EMPTY;
    }
}
 
Example 2
Source Project: micronaut-data   Source File: SourcePersistentProperty.java    License: Apache License 2.0 6 votes vote down vote up
private DataType computeDataType(PropertyElement propertyElement) {
    if (this instanceof Association) {
        return DataType.ENTITY;
    } else {
        AnnotationMetadata annotationMetadata = propertyElement.getAnnotationMetadata();
        return annotationMetadata.enumValue(MappedProperty.class, "type", DataType.class)
                .orElseGet(() -> {
                    DataType dt = annotationMetadata.getValue(TypeDef.class, "type", DataType.class).orElse(null);
                    if (dt != null) {
                        return dt;
                    } else {
                        if (isEnum()) {
                            return DataType.STRING;
                        } else {
                            return TypeUtils.resolveDataType(type, Collections.emptyMap());
                        }
                    }
                });
    }
}
 
Example 3
@Override
public QueryResult buildDelete(@NonNull AnnotationMetadata annotationMetadata, @NonNull QueryModel query) {
    PersistentEntity entity = query.getPersistentEntity();
    QueryState queryState = newQueryState(query, false);
    StringBuilder queryString = queryState.getQuery();
    String currentAlias = queryState.getCurrentAlias();
    if (!isAliasForBatch()) {
        currentAlias = null;
        queryState.setCurrentAlias(null);
    }
    StringBuilder buffer = appendDeleteClause(queryString);
    String tableName = getTableName(entity);
    buffer.append(tableName).append(SPACE);
    if (currentAlias != null) {
        buffer.append(getTableAsKeyword())
                .append(currentAlias);
    }
    buildWhereClause(annotationMetadata, query.getCriteria(), queryState);
    return QueryResult.of(
            queryString.toString(),
            queryState.getParameters(),
            queryState.getParameterTypes(),
            queryState.getAdditionalRequiredParameters()
    );
}
 
Example 4
Source Project: micronaut-data   Source File: QueryBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Build a query build from the configured annotation metadata.
 * @param annotationMetadata The annotation metadata.
 * @return The query builder
 */
static @NonNull QueryBuilder newQueryBuilder(@NonNull AnnotationMetadata annotationMetadata) {
    return annotationMetadata.stringValue(
            RepositoryConfiguration.class,
            DataMethod.META_MEMBER_QUERY_BUILDER
    ).flatMap(type -> BeanIntrospector.SHARED.findIntrospections(ref -> ref.isPresent() && ref.getBeanType().getName().equals(type))
            .stream().findFirst()
            .map(introspection -> {
                try {
                    Argument<?>[] constructorArguments = introspection.getConstructorArguments();
                    if (constructorArguments.length == 0) {
                        return (QueryBuilder) introspection.instantiate();
                    } else if (constructorArguments.length == 1 && constructorArguments[0].getType() == AnnotationMetadata.class) {
                        return (QueryBuilder) introspection.instantiate(annotationMetadata);
                    }
                } catch (InstantiationException e) {
                    return new JpaQueryBuilder();
                }
                return new JpaQueryBuilder();
            })).orElse(new JpaQueryBuilder());
}
 
Example 5
Source Project: micronaut-data   Source File: SqlQueryBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds the drop table statement. Designed for testing and not production usage. For production a
 * SQL migration tool such as Flyway or Liquibase is recommended.
 *
 * @param entity The entity
 * @return The tables for the give entity
 */
@Experimental
public @NonNull String[] buildDropTableStatements(@NonNull PersistentEntity entity) {
    String tableName = getTableName(entity);
    boolean escape = shouldEscape(entity);
    String sql = "DROP TABLE " + tableName + ";";
    Collection<Association> foreignKeyAssociations = getJoinTableAssociations(entity.getPersistentProperties());
    List<String> dropStatements = new ArrayList<>();
    for (Association association : foreignKeyAssociations) {
        AnnotationMetadata associationMetadata = association.getAnnotationMetadata();
        NamingStrategy namingStrategy = entity.getNamingStrategy();
        String joinTableName = associationMetadata
                .stringValue(ANN_JOIN_TABLE, "name")
                .orElseGet(() ->
                        namingStrategy.mappedName(association)
                );
        dropStatements.add("DROP TABLE " + (escape ? quote(joinTableName) : joinTableName) + ";");
    }

    dropStatements.add(sql);
    return dropStatements.toArray(new String[0]);
}
 
Example 6
Source Project: micronaut-data   Source File: PersistentProperty.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return The data type
 */
default DataType getDataType() {
    if (this instanceof Association) {
        return DataType.ENTITY;
    } else {
        AnnotationMetadata annotationMetadata = getAnnotationMetadata();
        return annotationMetadata.enumValue(MappedProperty.class, "type", DataType.class)
                .orElseGet(() -> {
                    DataType dt = annotationMetadata.enumValue(TypeDef.class, "type", DataType.class).orElse(null);
                    if (dt != null) {
                        return dt;
                    } else {
                        if (isEnum()) {
                            return DataType.STRING;
                        } else {
                            return DataType.OBJECT;
                        }
                    }
                });
    }
}
 
Example 7
/**
 * Resolve the INSERT for the given {@link EntityOperation}.
 *
 * @param operation The operation
 * @param <T>       The entity type
 * @return The insert
 */
@NonNull
protected final <T> StoredInsert resolveInsert(@NonNull EntityOperation<T> operation) {
    return storedInserts.computeIfAbsent(operation.getRootEntity(), aClass -> {
        AnnotationMetadata annotationMetadata = operation.getAnnotationMetadata();
        String insertStatement = annotationMetadata.stringValue(Query.class).orElse(null);
        if (insertStatement == null) {
            throw new IllegalStateException("No insert statement present in repository. Ensure it extends GenericRepository and is annotated with @JdbcRepository");
        }

        RuntimePersistentEntity<T> persistentEntity = getEntity(operation.getRootEntity());
        String[] parameterBinding = annotationMetadata.stringValues(DataMethod.class, DataMethod.META_MEMBER_PARAMETER_BINDING_PATHS);
        // MSSQL doesn't support RETURN_GENERATED_KEYS https://github.com/Microsoft/mssql-jdbc/issues/245 with BATCHi
        final Dialect dialect = annotationMetadata.enumValue(Repository.class, "dialect", Dialect.class)
                .orElse(Dialect.ANSI);
        boolean supportsBatch = dialect != Dialect.SQL_SERVER;
        return new StoredInsert<>(insertStatement, persistentEntity, parameterBinding, supportsBatch, dialect);
    });
}
 
Example 8
private <T> Map<String, Integer> buildSqlParameterBinding(AnnotationMetadata annotationMetadata) {
    AnnotationValue<DataMethod> annotation = annotationMetadata.getAnnotation(DataMethod.class);
    if (annotation == null) {
        return Collections.emptyMap();
    }
    String[] parameterData = annotationMetadata.stringValues(DataMethod.class, DataMethod.META_MEMBER_PARAMETER_BINDING_PATHS);
    Map<String, Integer> parameterValues;
    if (ArrayUtils.isNotEmpty(parameterData)) {
        parameterValues = new HashMap<>(parameterData.length);
        for (int i = 0; i < parameterData.length; i++) {
            String p = parameterData[i];
            parameterValues.put(p, i + 1);
        }
    } else {
        parameterValues = Collections.emptyMap();
    }
    return parameterValues;
}
 
Example 9
/**
 * Resolves a stored insert for the given entity.
 * @param annotationMetadata  The repository annotation metadata
 * @param repositoryType  The repository type
 * @param rootEntity The root entity
 * @param persistentEntity The persistent entity
 * @param <T> The generic type
 * @return The insert
 */
protected @NonNull <T> StoredInsert<T> resolveEntityInsert(
        AnnotationMetadata annotationMetadata,
        Class<?> repositoryType,
        @NonNull Class<?> rootEntity,
        @NonNull RuntimePersistentEntity<?> persistentEntity) {

    //noinspection unchecked
    return entityInserts.computeIfAbsent(new QueryKey(repositoryType, rootEntity), (queryKey) -> {
        final Dialect dialect = dialects.getOrDefault(queryKey.repositoryType, Dialect.ANSI);
        final SqlQueryBuilder queryBuilder = queryBuilders.getOrDefault(dialect, DEFAULT_SQL_BUILDER);
        final QueryResult queryResult = queryBuilder.buildInsert(annotationMetadata, persistentEntity);

        final String sql = queryResult.getQuery();
        final Map<String, String> parameters = queryResult.getParameters();
        return new StoredInsert<>(
                sql,
                persistentEntity,
                parameters.values().toArray(new String[0]),
                dialect != Dialect.SQL_SERVER,
                dialect
        );
    });
}
 
Example 10
Source Project: micronaut-data   Source File: HibernateJpaOperations.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ConstantConditions")
@NonNull
@Override
public <T> Iterable<T> persistAll(@NonNull BatchOperation<T> operation) {
    return transactionOperations.executeWrite(status -> {
        if (operation != null) {
            EntityManager entityManager = sessionFactory.getCurrentSession();
            for (T entity : operation) {
                entityManager.persist(entity);
            }
            AnnotationMetadata annotationMetadata =
                    operation.getAnnotationMetadata();
            flushIfNecessary(entityManager, annotationMetadata);
            return operation;
        } else {
            return Collections.emptyList();
        }
    });
}
 
Example 11
Source Project: micronaut-spring   Source File: TransactionInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param targetMethod           The target method
 * @param annotationMetadata     The annotation metadata
 * @param transactionManagerName The transaction manager
 * @return The {@link TransactionAttribute}
 */
protected TransactionAttribute resolveTransactionAttribute(
        ExecutableMethod<Object, Object> targetMethod,
        AnnotationMetadata annotationMetadata,
        String transactionManagerName) {
    return transactionDefinitionMap.computeIfAbsent(targetMethod, method -> {

        BindableRuleBasedTransactionAttribute attribute = new BindableRuleBasedTransactionAttribute();
        attribute.setReadOnly(annotationMetadata.isTrue(Transactional.class, "readOnly"));
        attribute.setTimeout(annotationMetadata.intValue(Transactional.class, "timeout").orElse(TransactionDefinition.TIMEOUT_DEFAULT));
        //noinspection unchecked
        attribute.setRollbackFor(annotationMetadata.classValues(Transactional.class, "rollbackFor"));
        //noinspection unchecked
        attribute.setNoRollbackFor(annotationMetadata.classValues(Transactional.class, "noRollbackFor"));
        int propagation = annotationMetadata
                .enumValue(Transactional.class, "propagation", Propagation.class)
                .orElse(Propagation.REQUIRED).value();
        attribute.setPropagationBehavior(propagation);
        int isolation = annotationMetadata
                .enumValue(Transactional.class, "isolation", Isolation.class)
                .orElse(Isolation.DEFAULT).value();
        attribute.setIsolationLevel(isolation);
        attribute.setQualifier(transactionManagerName);
        return attribute;
    });
}
 
Example 12
Source Project: micronaut-spring   Source File: MicronautBeanFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isPrototype(@Nonnull String name) throws NoSuchBeanDefinitionException {
    if (super.containsSingleton(name)) {
        return false;
    }

    final BeanDefinitionReference<?> definition = beanDefinitionMap.get(name);
    if (definition != null) {
        final AnnotationMetadata annotationMetadata = definition.getAnnotationMetadata();
        if (annotationMetadata.hasDeclaredStereotype(Prototype.class)) {
            return true;
        } else {
            final boolean hasScope = annotationMetadata.getAnnotationNamesByStereotype(Scope.class).isEmpty();
            return !hasScope;
        }
    }
    return false;
}
 
Example 13
@Override
public BindingResult<Object> bind(ArgumentConversionContext<Object> context, HttpRequest<?> source) {
    final AnnotationMetadata annotationMetadata = context.getAnnotationMetadata();
    final boolean required = annotationMetadata.getValue("required", boolean.class).orElse(true);
    final String name = annotationMetadata.getValue(RequestAttribute.class, String.class).orElseGet(() ->
            annotationMetadata.getValue(RequestAttribute.class, "name", String.class).orElse(context.getArgument().getName())
    );

    return new BindingResult<Object>() {
        @Override
        public Optional<Object> getValue() {
            return source.getAttributes().get(name, context);
        }

        @Override
        public boolean isSatisfied() {
            return !required;
        }
    };
}
 
Example 14
@Override
public Object intercept(MethodInvocationContext<Object, Object> context) {
    final AnnotationMetadata annotationMetadata = context.getAnnotationMetadata();
    final boolean isSingleton = MicronautBeanFactory.isSingleton(annotationMetadata);
    if (isSingleton) {
        final ExecutableMethod<Object, Object> method = context.getExecutableMethod();
        synchronized (computedSingletons) {
            Object o = computedSingletons.get(method);
            if (o == null) {
                o = context.proceed();
                if (o == null) {
                    throw new BeanCreationException("Bean factor method [" + method + "] returned null");
                }
                computedSingletons.put(method, o);
            }
            return o;
        }
    }
    return context.proceed();
}
 
Example 15
Source Project: micronaut-aws   Source File: AnnotatedRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
default boolean canHandle(HandlerInput handlerInput) {
    final Class<? extends AnnotatedRequestHandler> type = getClass();
    final String annotationMetadata = type.getPackage().getName() + ".$" + type.getSimpleName() + "DefinitionClass";
    final AnnotationMetadata metadata = ClassUtils.forName(annotationMetadata, type.getClassLoader()).flatMap(aClass -> {
        final Object o = InstantiationUtils.tryInstantiate(aClass).orElse(null);
        if (o instanceof AnnotationMetadataProvider) {
            return Optional.of(((AnnotationMetadataProvider) o).getAnnotationMetadata());
        }
        return Optional.empty();
    }).orElse(AnnotationMetadata.EMPTY_METADATA);
    final String[] names = metadata.getValue(IntentHandler.class, String[].class).orElse(StringUtils.EMPTY_STRING_ARRAY);
    return Arrays.stream(names).anyMatch(n -> handlerInput.matches(intentName(n)));
}
 
Example 16
/**
 * Default constructor.
 *
 * @param hierarchy The annotation hierarchy
 */
public AnnotationMetadataHierarchy(AnnotationMetadata... hierarchy) {
    if (ArrayUtils.isNotEmpty(hierarchy)) {
        // place the first in the hierarchy first
        final List<AnnotationMetadata> list = Arrays.asList(hierarchy);
        Collections.reverse(list);
        this.hierarchy = list.toArray(new AnnotationMetadata[0]);
    } else {
        this.hierarchy = new AnnotationMetadata[] { AnnotationMetadata.EMPTY_METADATA };
    }
}
 
Example 17
@Nonnull
@Override
public OptionalDouble doubleValue(@Nonnull Class<? extends Annotation> annotation, @Nonnull String member) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final OptionalDouble o = annotationMetadata.doubleValue(annotation, member);
        if (o.isPresent()) {
            return o;
        }
    }
    return OptionalDouble.empty();
}
 
Example 18
@Override
public Optional<Boolean> booleanValue(@Nonnull String annotation, @Nonnull String member) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final Optional<Boolean> o = annotationMetadata.booleanValue(annotation, member);
        if (o.isPresent()) {
            return o;
        }
    }
    return Optional.empty();
}
 
Example 19
@Override
public OptionalLong longValue(@Nonnull String annotation, @Nonnull String member) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final OptionalLong o = annotationMetadata.longValue(annotation, member);
        if (o.isPresent()) {
            return o;
        }
    }
    return OptionalLong.empty();
}
 
Example 20
@Override
public Optional<String> stringValue(@Nonnull String annotation, @Nonnull String member) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final Optional<String> o = annotationMetadata.stringValue(annotation, member);
        if (o.isPresent()) {
            return o;
        }
    }
    return Optional.empty();
}
 
Example 21
@Override
public OptionalInt intValue(@Nonnull String annotation, @Nonnull String member) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final OptionalInt o = annotationMetadata.intValue(annotation, member);
        if (o.isPresent()) {
            return o;
        }
    }
    return OptionalInt.empty();
}
 
Example 22
@Nonnull
@Override
public OptionalDouble doubleValue(@Nonnull String annotation, @Nonnull String member) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final OptionalDouble o = annotationMetadata.doubleValue(annotation, member);
        if (o.isPresent()) {
            return o;
        }
    }
    return OptionalDouble.empty();
}
 
Example 23
@Override
public <E extends Enum> Optional<E> enumValue(@Nonnull Class<? extends Annotation> annotation, @Nonnull String member, Class<E> enumType) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final Optional<E> o = annotationMetadata.enumValue(annotation, member, enumType);
        if (o.isPresent()) {
            return o;
        }
    }
    return Optional.empty();
}
 
Example 24
@Override
public Optional<Class> classValue(@Nonnull String annotation, @Nonnull String member) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final Optional<Class> o = annotationMetadata.classValue(annotation, member);
        if (o.isPresent()) {
            return o;
        }
    }
    return Optional.empty();
}
 
Example 25
@Nonnull
@Override
public <T> OptionalValues<T> getValues(@Nonnull String annotation, @Nonnull Class<T> valueType) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final OptionalValues<T> values = annotationMetadata.getValues(annotation, valueType);
        if (!values.isEmpty()) {
            return values;
        }
    }
    return OptionalValues.empty();
}
 
Example 26
@Override
public <T> Optional<T> getDefaultValue(@Nonnull String annotation, @Nonnull String member, @Nonnull Argument<T> requiredType) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final Optional<T> defaultValue = annotationMetadata.getDefaultValue(annotation, member, requiredType);
        if (defaultValue.isPresent()) {
            return defaultValue;
        }
    }
    return Optional.empty();
}
 
Example 27
@Override
public boolean hasAnnotation(@Nullable String annotation) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        if (annotationMetadata.hasDeclaredAnnotation(annotation)) {
            return true;
        }
    }
    return false;
}
 
Example 28
@Override
public boolean hasStereotype(@Nullable String annotation) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        if (annotationMetadata.hasDeclaredStereotype(annotation)) {
            return true;
        }
    }
    return false;
}
 
Example 29
@Nonnull
@Override
public Map<String, Object> getDefaultValues(@Nonnull String annotation) {
    for (AnnotationMetadata annotationMetadata : hierarchy) {
        final Map<String, Object> defaultValues = annotationMetadata.getDefaultValues(annotation);
        if (!defaultValues.isEmpty()) {
            return defaultValues;
        }
    }
    return Collections.emptyMap();
}
 
Example 30
@Override
public QueryResult buildQuery(@NonNull AnnotationMetadata annotationMetadata, @NonNull QueryModel query) {
    ArgumentUtils.requireNonNull("annotationMetadata", annotationMetadata);
    ArgumentUtils.requireNonNull("query", query);
    QueryState queryState = newQueryState(query, true);

    Collection<JoinPath> joinPaths = query.getJoinPaths();
    for (JoinPath joinPath : joinPaths) {
        queryState.applyJoin(joinPath);
    }

    StringBuilder select = new StringBuilder(SELECT_CLAUSE);
    buildSelectClause(query, queryState, select);
    queryState.getQuery().insert(0, select.toString());

    QueryModel.Junction criteria = query.getCriteria();

    Map<String, String> parameters = null;
    if (!criteria.isEmpty() || annotationMetadata.hasStereotype(WhereSpecifications.class) || queryState.getEntity().getAnnotationMetadata().hasStereotype(WhereSpecifications.class)) {
        parameters = buildWhereClause(annotationMetadata, criteria, queryState);
    }

    appendOrder(query, queryState);
    return QueryResult.of(
            queryState.getQuery().toString(),
            parameters,
            queryState.getParameterTypes(),
            queryState.getAdditionalRequiredParameters()
    );
}