io.micronaut.core.type.Argument Java Examples

The following examples show how to use io.micronaut.core.type.Argument. 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 File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T decode(Argument<T> type, byte[] bytes) throws CodecException {
    try {
        if (type.getType() == byte[].class) {
            return (T) bytes;
        } else {
            Message.Builder builder = getBuilder(type)
                    .orElseThrow(() -> new CodecException("Unable to create builder"));
            if (type.hasTypeVariables()) {
                throw new IllegalStateException("Generic type arguments are not supported");
            } else {
                builder.mergeFrom(bytes, extensionRegistry);
                return type.getType().cast(builder.build());
            }
        }
    } catch (Exception e) {
        throw new CodecException("Error decoding Protobuff bytes for type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
 
Example #2
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T decode(Argument<T> type, ByteBuffer<?> buffer) throws CodecException {
    try {
        if (type.getType() == byte[].class) {
            return (T) buffer.toByteArray();
        } else {
            Message.Builder builder = getBuilder(type)
                    .orElseThrow(() -> new CodecException("Unable to create builder"));
            if (type.hasTypeVariables()) {
                throw new IllegalStateException("Generic type arguments are not supported");
            } else {
                builder.mergeFrom(buffer.toByteArray(), extensionRegistry);
                return type.getType().cast(builder.build());
            }
        }
    } catch (Exception e) {
        throw new CodecException("Error decoding Protobuff bytes for type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
 
Example #3
Source File: QueryBuilder.java    From micronaut-data with 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 #4
Source File: RuntimeAssociation.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@NonNull
@Override
public RuntimePersistentEntity<?> getAssociatedEntity() {
    switch (getKind()) {
        case ONE_TO_MANY:
        case MANY_TO_MANY:
            Argument<?> typeArg = getProperty().asArgument().getFirstTypeVariable().orElse(null);
            if (typeArg  != null) {
                //noinspection unchecked
                return getOwner().getEntity((Class<T>) typeArg.getType());
            } else {
                throw new MappingException("Collection association [" + getName() + "] of entity [" + getOwner().getName() + "] does not specify a generic type argument");
            }
        default:
            //noinspection unchecked
            return getOwner().getEntity((Class<T>) getProperty().getType());
    }
}
 
Example #5
Source File: MicronautSpockExtension.java    From micronaut-test with Apache License 2.0 6 votes vote down vote up
@Override
protected void alignMocks(IMethodInvocation context, Object instance) {
    for (MethodInjectionPoint injectedMethod : specDefinition.getInjectedMethods()) {
        final Argument<?>[] args = injectedMethod.getArguments();
        if (args.length == 1) {
            final Optional<FieldInfo> fld = context.getSpec().getFields().stream().filter(f -> f.getName().equals(args[0].getName())).findFirst();
            if (fld.isPresent()) {
                final FieldInfo fieldInfo = fld.get();
                final Object fieldInstance = fieldInfo.readValue(
                        instance
                );
                if (fieldInstance instanceof InterceptedProxy) {
                    Object interceptedTarget = ((InterceptedProxy) fieldInstance).interceptedTarget();
                    if (mockUtil.isMock(interceptedTarget)) {
                        fieldInfo.writeValue(instance, interceptedTarget);
                    }
                }
            }
        }
    }
}
 
Example #6
Source File: ConsumerRecordBinderRegistry.java    From micronaut-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Optional<ArgumentBinder<T, ConsumerRecord<?, ?>>> findArgumentBinder(Argument<T> argument, ConsumerRecord<?, ?> source) {
    Optional<Class<? extends Annotation>> annotationType = argument.getAnnotationMetadata().getAnnotationTypeByStereotype(Bindable.class);
    if (annotationType.isPresent()) {
        @SuppressWarnings("unchecked") ConsumerRecordBinder<T> consumerRecordBinder =
                (ConsumerRecordBinder<T>) byAnnotation.get(annotationType.get());

        return Optional.ofNullable(consumerRecordBinder);
    } else {
        @SuppressWarnings("unchecked")
        ConsumerRecordBinder<T> binder = (ConsumerRecordBinder<T>) byType.get(argument.typeHashCode());
        if (binder != null) {
            return Optional.of(binder);
        } else {
            return Optional.of(new KafkaDefaultBinder<>());
        }
    }
}
 
Example #7
Source File: SqlResultEntityTypeMapper.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public Object read(@NonNull RS resultSet, @NonNull Argument<?> argument) {
    RuntimePersistentProperty<R> property = entity.getPropertyByName(argument.getName());
    DataType dataType;
    String columnName;
    if (property == null) {
        dataType = argument.getAnnotationMetadata()
                .enumValue(TypeDef.class, "type", DataType.class)
                .orElseGet(() -> DataType.forType(argument.getType()));
        columnName = argument.getName();
    } else {
        dataType = property.getDataType();
        columnName = property.getPersistedName();
    }

    return resultReader.readDynamic(
            resultSet,
            columnName,
            dataType
    );
}
 
Example #8
Source File: SerdeRegistry.java    From micronaut-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Picks the most appropriate {@link Deserializer} for the given argument.
 *
 * @param argument The argument
 * @param <T> The generic type
 * @return The {@link Deserializer}
 */
@SuppressWarnings("unchecked")
default <T> Deserializer<T> pickDeserializer(Argument<T> argument) {
    Class<T> type = argument.getType();

    if (Publishers.isConvertibleToPublisher(type) || Future.class.isAssignableFrom(type)) {
        Optional<Argument<?>> typeArg = argument.getFirstTypeVariable();

        if (typeArg.isPresent()) {
            type = (Class<T>) typeArg.get().getType();
        } else {
            return (Deserializer<T>) new ByteArrayDeserializer();
        }
    }

    return getDeserializer(type);
}
 
Example #9
Source File: SerdeRegistry.java    From micronaut-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Picks the most appropriate {@link Deserializer} for the given argument.
 *
 * @param argument The argument
 * @param <T> The generic type
 * @return The {@link Deserializer}
 */
@SuppressWarnings("unchecked")
default <T> Serializer<T> pickSerializer(Argument<T> argument) {
    Class<T> type = argument.getType();

    if (Publishers.isConvertibleToPublisher(type) || Future.class.isAssignableFrom(type)) {
        Optional<Argument<?>> typeArg = argument.getFirstTypeVariable();

        if (typeArg.isPresent()) {
            type = (Class<T>) typeArg.get().getType();
        } else {
            return (Serializer<T>) new ByteArrayDeserializer();
        }
    }

    return getSerializer(type);
}
 
Example #10
Source File: DefaultFindAllAsyncInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public CompletionStage<Iterable<Object>> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Iterable<Object>>> context) {
    CompletionStage<? extends Iterable<?>> future;
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context);
        future = asyncDatastoreOperations.findAll(preparedQuery);

    } else {
        future = asyncDatastoreOperations.findAll(getPagedQuery(context));
    }
    return future.thenApply((Function<Iterable<?>, Iterable<Object>>) iterable -> {
        Argument<CompletionStage<Iterable<Object>>> targetType = context.getReturnType().asArgument();
        Argument<?> argument = targetType.getFirstTypeVariable().orElse(Argument.listOf(Object.class));
        Iterable<Object> result = (Iterable<Object>) ConversionService.SHARED.convert(
                iterable,
                argument
        ).orElse(null);
        return result == null ? Collections.emptyList() : result;
    });
}
 
Example #11
Source File: AbstractQueryInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a number argument if necessary.
 * @param number The number
 * @param argument The argument
 * @return The result
 */
protected @Nullable Number convertNumberArgumentIfNecessary(Number number, Argument<?> argument) {
    Argument<?> firstTypeVar = argument.getFirstTypeVariable().orElse(Argument.of(Long.class));
    Class<?> type = firstTypeVar.getType();
    if (type == Object.class || type == Void.class) {
        return null;
    }
    if (number == null) {
        number = 0;
    }
    if (!type.isInstance(number)) {
        return (Number) ConversionService.SHARED.convert(number, firstTypeVar)
                .orElseThrow(() -> new IllegalStateException("Unsupported number type for return type: " + firstTypeVar));
    } else {
        return number;
    }
}
 
Example #12
Source File: DefaultUpdateInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, Object> context) {
    PreparedQuery<?, Number> preparedQuery = (PreparedQuery<?, Number>) prepareQuery(methodKey, context);
    Number number = operations.executeUpdate(preparedQuery).orElse(null);
    final Argument<Object> returnType = context.getReturnType().asArgument();
    final Class<Object> type = ReflectionUtils.getWrapperType(returnType.getType());
    if (Number.class.isAssignableFrom(type)) {
        if (type.isInstance(number)) {
            return number;
        } else {
            return ConversionService.SHARED.
                    convert(number, returnType)
                    .orElse(0);
        }
    } else if (Boolean.class.isAssignableFrom(type)) {
        return number == null || number.longValue() < 0;
    } else {
        return null;
    }
}
 
Example #13
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T decode(Argument<T> type, ByteBuffer<?> buffer) throws CodecException {
    try {
        if (type.getType() == byte[].class) {
            return (T) buffer.toByteArray();
        } else {
            Message.Builder builder = getBuilder(type)
                    .orElseThrow(() -> new CodecException("Unable to create builder"));
            if (type.hasTypeVariables()) {
                throw new IllegalStateException("Generic type arguments are not supported");
            } else {
                builder.mergeFrom(buffer.toByteArray(), extensionRegistry);
                return type.getType().cast(builder.build());
            }
        }
    } catch (Exception e) {
        throw new CodecException("Error decoding Protobuff bytes for type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
 
Example #14
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T decode(Argument<T> type, byte[] bytes) throws CodecException {
    try {
        if (type.getType() == byte[].class) {
            return (T) bytes;
        } else {
            Message.Builder builder = getBuilder(type)
                    .orElseThrow(() -> new CodecException("Unable to create builder"));
            if (type.hasTypeVariables()) {
                throw new IllegalStateException("Generic type arguments are not supported");
            } else {
                builder.mergeFrom(bytes, extensionRegistry);
                return type.getType().cast(builder.build());
            }
        }
    } catch (Exception e) {
        throw new CodecException("Error decoding Protobuff bytes for type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
 
Example #15
Source File: OwnerControllerTest.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Test
void testListInitialOwners() {

    List<Owner> results = client.retrieve(HttpRequest.GET("/"), Argument.listOf(Owner.class)).blockingFirst();

    Assertions.assertEquals(
            2,
            results.size()
    );
}
 
Example #16
Source File: KafkaConsumerProcessor.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
private Argument findBodyArgument(ExecutableMethod<?, ?> method) {
    return Arrays.stream(method.getArguments())
            .filter(arg -> arg.getType() == ConsumerRecord.class || arg.getAnnotationMetadata().hasAnnotation(Body.class))
            .findFirst()
            .orElseGet(() ->
                    Arrays.stream(method.getArguments())
                            .filter(arg -> !arg.getAnnotationMetadata().hasStereotype(Bindable.class))
                            .findFirst()
                            .orElse(null)
            );
}
 
Example #17
Source File: OwnerControllerTest.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Test
void testListInitialOwners() {

    List<Owner> results = client.retrieve(HttpRequest.GET("/"), Argument.listOf(Owner.class)).blockingFirst();

    Assertions.assertEquals(
            2,
            results.size()
    );
}
 
Example #18
Source File: AnnotationMetadataHierarchy.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: KafkaClientIntroductionAdvice.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
private Flowable buildSendFlowable(
        MethodInvocationContext<Object, Object> context,
        String topic,
        Argument bodyArgument,
        Producer kafkaProducer,
        List<Header> kafkaHeaders,
        ReturnType<Object> returnType,
        Object key,
        Object value,
        Long timestamp) {
    Flowable returnFlowable;
    ProducerRecord record = buildProducerRecord(topic, kafkaHeaders, key, value, timestamp);
    Optional<Argument<?>> firstTypeVariable = returnType.getFirstTypeVariable();
    returnFlowable = Flowable.create(emitter -> kafkaProducer.send(record, (metadata, exception) -> {
        if (exception != null) {
            emitter.onError(wrapException(context, exception));
        } else {
            if (firstTypeVariable.isPresent()) {
                Argument<?> argument = firstTypeVariable.get();
                Optional<?> converted = conversionService.convert(metadata, argument);

                if (converted.isPresent()) {
                    emitter.onNext(converted.get());
                } else if (argument.getType() == bodyArgument.getType()) {
                    emitter.onNext(value);
                }
            }
            emitter.onComplete();
        }
    }), BackpressureStrategy.ERROR);
    return returnFlowable;
}
 
Example #20
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T decode(Argument<T> type, InputStream inputStream) throws CodecException {
    try {
        Message.Builder builder = getBuilder(type)
                .orElseThrow(() -> new CodecException("Unable to create builder"));
        if (type.hasTypeVariables()) {
            throw new IllegalStateException("Generic type arguments are not supported");
        } else {
            builder.mergeFrom(inputStream, extensionRegistry);
            return type.getType().cast(builder.build());
        }
    } catch (Exception e) {
        throw new CodecException("Error decoding Protobuff stream for type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
 
Example #21
Source File: OwnerControllerTest.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Test
void testListInitialOwners() {

    List<Owner> results = client.retrieve(HttpRequest.GET("/"), Argument.listOf(Owner.class)).blockingFirst();

    Assertions.assertEquals(
            2,
            results.size()
    );
}
 
Example #22
Source File: OwnerControllerTest.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Test
void testListInitialOwners() {

    List<Owner> results = client.retrieve(HttpRequest.GET("/"), Argument.listOf(Owner.class)).blockingFirst();

    Assertions.assertEquals(
            2,
            results.size()
    );
}
 
Example #23
Source File: DefaultFindOneReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    PreparedQuery<Object, Object> preparedQuery = (PreparedQuery<Object, Object>) prepareQuery(methodKey, context);
    Publisher<Object> publisher = reactiveOperations.findOptional(preparedQuery);
    Argument<Object> returnType = context.getReturnType().asArgument();
    Argument<?> type = returnType.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
    Publisher<Object> mappedPublisher = Publishers.map(publisher, o -> {
        if (!type.getType().isInstance(o)) {
            return ConversionService.SHARED.convert(o, type)
                    .orElseThrow(() -> new IllegalStateException("Unexpected return type: " + o));
        }
        return o;
    });
    return Publishers.convertPublisher(mappedPublisher, returnType.getType());
}
 
Example #24
Source File: DefaultDeleteAllInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
private Number convertIfNecessary(Argument<Number> resultType, Number result) {
    if (!resultType.getType().isInstance(result)) {
        return ConversionService.SHARED.convert(result, resultType).orElse(0);
    } else {
        return result;
    }
}
 
Example #25
Source File: DefaultFindOneAsyncInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public CompletionStage<Object> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Object>> context) {
    PreparedQuery<Object, Object> preparedQuery = (PreparedQuery<Object, Object>) prepareQuery(methodKey, context);
    CompletionStage<Object> future = asyncDatastoreOperations.findOne(preparedQuery);
    Argument<?> type = context.getReturnType().asArgument().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
    return future.thenApply(o -> {
        if (!type.getType().isInstance(o)) {
            return ConversionService.SHARED.convert(o, type)
                    .orElseThrow(() -> new IllegalStateException("Unexpected return type: " + o));
        }
        return o;
    });
}
 
Example #26
Source File: ResultReader.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the value to the given type.
 * @param value The value
 * @param type The type
 * @param <T> The generic type
 * @return The converted value
 * @throws DataAccessException if the value cannot be converted
 */
default <T> T convertRequired(Object value, Argument<T> type) {

    return ConversionService.SHARED.convert(
            value,
            type
    ).orElseThrow(() ->
            new DataAccessException("Cannot convert type [" + value.getClass() + "] with value [" + value + "] to target type: " + type + ". Consider defining a TypeConverter bean to handle this case.")
    );
}
 
Example #27
Source File: DTOMapper.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Object read(@NonNull S object, @NonNull Argument<?> argument) {
    RuntimePersistentProperty<T> pp = persistentEntity.getPropertyByName(argument.getName());
    if (pp == null) {
        DataType type = argument.getAnnotationMetadata()
                .enumValue(TypeDef.class, "type", DataType.class)
                .orElseGet(() -> DataType.forType(argument.getType()));
        return read(object, argument.getName(), type);
    } else {
        return read(object, pp);
    }
}
 
Example #28
Source File: GrpcChannelScope.java    From micronaut-grpc with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(
        BeanResolutionContext resolutionContext,
        BeanDefinition<T> beanDefinition,
        BeanIdentifier identifier,
        Provider<T> provider) {
    BeanResolutionContext.Segment segment = resolutionContext.getPath().currentSegment().orElseThrow(() ->
            new IllegalStateException("@GrpcChannel used in invalid location")
    );
    Argument argument = segment.getArgument();
    String value = argument.getAnnotationMetadata().getValue(GrpcChannel.class, String.class).orElse(null);
    if (StringUtils.isEmpty(value)) {
        throw new DependencyInjectionException(resolutionContext, argument, "No value specified to @GrpcChannel annotation");
    }
    if (!Channel.class.isAssignableFrom(argument.getType())) {
        throw new DependencyInjectionException(resolutionContext, argument, "@GrpcChannel used on type that is not a Channel");
    }

    if ("grpc-server".equalsIgnoreCase(value)) {
        return (T) applicationContext.getBean(ManagedChannel.class, Qualifiers.byName("grpc-server"));
    }

    if (!(provider instanceof ParametrizedProvider)) {
        throw new DependencyInjectionException(resolutionContext, argument, "GrpcChannelScope called with invalid bean provider");
    }
    value = applicationContext.resolveRequiredPlaceholders(value);
    String finalValue = value;
    return (T) channels.computeIfAbsent(new ChannelKey(identifier, value), channelKey ->
            (ManagedChannel) ((ParametrizedProvider<T>) provider).get(finalValue)
    );
}
 
Example #29
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T decode(Argument<T> type, InputStream inputStream) throws CodecException {
    try {
        Message.Builder builder = getBuilder(type)
                .orElseThrow(() -> new CodecException("Unable to create builder"));
        if (type.hasTypeVariables()) {
            throw new IllegalStateException("Generic type arguments are not supported");
        } else {
            builder.mergeFrom(inputStream, extensionRegistry);
            return type.getType().cast(builder.build());
        }
    } catch (Exception e) {
        throw new CodecException("Error decoding Protobuff stream for type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
 
Example #30
Source File: OwnerControllerTest.java    From database-rider with Apache License 2.0 5 votes vote down vote up
@Test
void testListInitialOwners() {

    List<Owner> results = client.retrieve(HttpRequest.GET("/"), Argument.listOf(Owner.class)).blockingFirst();

    Assertions.assertEquals(
            2,
            results.size()
    );
}