Search in sources :

Example 6 with ReflectionCache

use of org.mule.runtime.module.extension.internal.util.ReflectionCache in project mule by mulesoft.

the class NullSafeValueResolverWrapper method of.

/**
 * Creates a new instance
 *
 * @param delegate the {@link ValueResolver} to wrap
 * @param type the type of the value this resolver returns
 * @param reflectionCache the cache for expensive reflection lookups
 * @param muleContext the current {@link MuleContext}
 * @param <T> the generic type of the produced values
 * @return a new null safe {@link ValueResolver}
 * @throws IllegalParameterModelDefinitionException if used on parameters of not supported types
 */
public static <T> ValueResolver<T> of(ValueResolver<T> delegate, MetadataType type, ReflectionCache reflectionCache, MuleContext muleContext, ObjectTypeParametersResolver parametersResolver) {
    checkArgument(delegate != null, "delegate cannot be null");
    Reference<ValueResolver> wrappedResolver = new Reference<>();
    type.accept(new MetadataTypeVisitor() {

        @Override
        public void visitObject(ObjectType objectType) {
            Class clazz = getType(objectType);
            if (isMap(objectType)) {
                ValueResolver<?> fallback = MapValueResolver.of(clazz, emptyList(), emptyList(), reflectionCache, muleContext);
                wrappedResolver.set(new NullSafeValueResolverWrapper(delegate, fallback, muleContext));
                return;
            }
            String requiredFields = objectType.getFields().stream().filter(f -> f.isRequired() && !isFlattenedParameterGroup(f)).map(MetadataTypeUtils::getLocalPart).collect(joining(", "));
            if (!isBlank(requiredFields)) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(format("Class '%s' cannot be used with NullSafe Wrapper since it contains non optional fields: [%s]", clazz.getName(), requiredFields));
                }
                wrappedResolver.set(delegate);
                return;
            }
            ResolverSet resolverSet = new ResolverSet(muleContext);
            for (Field field : getFields(clazz)) {
                ValueResolver<?> fieldResolver = null;
                ObjectFieldType objectField = objectType.getFieldByName(getAlias(field)).orElse(null);
                if (objectField == null) {
                    continue;
                }
                Optional<String> defaultValue = getDefaultValue(objectField);
                // TODO MULE-13066 Extract ParameterResolver logic into a centralized resolver
                if (defaultValue.isPresent()) {
                    fieldResolver = getFieldDefaultValueValueResolver(objectField, muleContext);
                } else if (isFlattenedParameterGroup(objectField)) {
                    DefaultObjectBuilder groupBuilder = new DefaultObjectBuilder<>(getType(objectField.getValue()));
                    resolverSet.add(field.getName(), new ObjectBuilderValueResolver<T>(groupBuilder, muleContext));
                    ObjectType childGroup = (ObjectType) objectField.getValue();
                    parametersResolver.resolveParameters(childGroup, groupBuilder);
                    parametersResolver.resolveParameterGroups(childGroup, groupBuilder);
                } else {
                    NullSafe nullSafe = field.getAnnotation(NullSafe.class);
                    if (nullSafe != null) {
                        MetadataType nullSafeType;
                        if (Object.class.equals(nullSafe.defaultImplementingType())) {
                            nullSafeType = objectField.getValue();
                        } else {
                            nullSafeType = new BaseTypeBuilder(JAVA).objectType().with(new TypeIdAnnotation(nullSafe.defaultImplementingType().getName())).build();
                        }
                        fieldResolver = NullSafeValueResolverWrapper.of(new StaticValueResolver<>(null), nullSafeType, reflectionCache, muleContext, parametersResolver);
                    }
                    if (field.getAnnotation(ConfigOverride.class) != null) {
                        ValueResolver<?> fieldDelegate = fieldResolver != null ? fieldResolver : new StaticValueResolver<>(null);
                        fieldResolver = ConfigOverrideValueResolverWrapper.of(fieldDelegate, field.getName(), reflectionCache, muleContext);
                    }
                }
                if (fieldResolver != null) {
                    resolverSet.add(field.getName(), fieldResolver);
                }
            }
            ObjectBuilder<T> objectBuilder = new DefaultResolverSetBasedObjectBuilder<T>(clazz, resolverSet);
            wrappedResolver.set(new NullSafeValueResolverWrapper(delegate, new ObjectBuilderValueResolver(objectBuilder, muleContext), muleContext));
        }

        @Override
        public void visitArrayType(ArrayType arrayType) {
            Class collectionClass = getType(arrayType);
            ValueResolver<?> fallback = CollectionValueResolver.of(collectionClass, emptyList());
            wrappedResolver.set(new NullSafeValueResolverWrapper(delegate, fallback, muleContext));
        }

        @Override
        protected void defaultVisit(MetadataType metadataType) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(format("Class '%s' cannot be used with NullSafe Wrapper since it is of a simple type", getType(metadataType).getName()));
            }
            wrappedResolver.set(delegate);
        }
    });
    return wrappedResolver.get();
}
Also used : ConfigOverride(org.mule.runtime.extension.api.annotation.param.ConfigOverride) MetadataTypeUtils.getDefaultValue(org.mule.metadata.api.utils.MetadataTypeUtils.getDefaultValue) InitialisationException(org.mule.runtime.api.lifecycle.InitialisationException) LoggerFactory(org.slf4j.LoggerFactory) JAVA(org.mule.metadata.api.model.MetadataFormat.JAVA) Preconditions.checkArgument(org.mule.runtime.api.util.Preconditions.checkArgument) LifecycleUtils.initialiseIfNeeded(org.mule.runtime.core.api.lifecycle.LifecycleUtils.initialiseIfNeeded) BaseTypeBuilder(org.mule.metadata.api.builder.BaseTypeBuilder) IntrospectionUtils.getFields(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getFields) MetadataTypeUtils(org.mule.metadata.api.utils.MetadataTypeUtils) ExtensionMetadataTypeUtils.isFlattenedParameterGroup(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isFlattenedParameterGroup) ArrayType(org.mule.metadata.api.model.ArrayType) MuleContext(org.mule.runtime.core.api.MuleContext) DefaultObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder) DefaultResolverSetBasedObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultResolverSetBasedObjectBuilder) IntrospectionUtils.getAlias(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getAlias) MuleException(org.mule.runtime.api.exception.MuleException) TypeIdAnnotation(org.mule.metadata.api.annotation.TypeIdAnnotation) ResolverUtils.getFieldDefaultValueValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ResolverUtils.getFieldDefaultValueValueResolver) ExtensionMetadataTypeUtils.isMap(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isMap) IllegalParameterModelDefinitionException(org.mule.runtime.extension.api.exception.IllegalParameterModelDefinitionException) ObjectType(org.mule.metadata.api.model.ObjectType) Logger(org.slf4j.Logger) Collections.emptyList(java.util.Collections.emptyList) ReflectionCache(org.mule.runtime.module.extension.internal.util.ReflectionCache) Initialisable(org.mule.runtime.api.lifecycle.Initialisable) Field(java.lang.reflect.Field) String.format(java.lang.String.format) Collectors.joining(java.util.stream.Collectors.joining) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) ObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.ObjectBuilder) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) Reference(org.mule.runtime.api.util.Reference) NullSafe(org.mule.runtime.extension.api.annotation.param.NullSafe) MetadataType(org.mule.metadata.api.model.MetadataType) Optional(java.util.Optional) JavaTypeUtils.getType(org.mule.metadata.java.api.utils.JavaTypeUtils.getType) BaseTypeBuilder(org.mule.metadata.api.builder.BaseTypeBuilder) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) TypeIdAnnotation(org.mule.metadata.api.annotation.TypeIdAnnotation) ArrayType(org.mule.metadata.api.model.ArrayType) ObjectType(org.mule.metadata.api.model.ObjectType) Field(java.lang.reflect.Field) ResolverUtils.getFieldDefaultValueValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ResolverUtils.getFieldDefaultValueValueResolver) ConfigOverride(org.mule.runtime.extension.api.annotation.param.ConfigOverride) Optional(java.util.Optional) Reference(org.mule.runtime.api.util.Reference) ConfigOverride(org.mule.runtime.extension.api.annotation.param.ConfigOverride) MetadataType(org.mule.metadata.api.model.MetadataType) DefaultObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder) DefaultResolverSetBasedObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultResolverSetBasedObjectBuilder) ObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.ObjectBuilder) NullSafe(org.mule.runtime.extension.api.annotation.param.NullSafe) MetadataTypeUtils(org.mule.metadata.api.utils.MetadataTypeUtils) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) DefaultObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder)

Example 7 with ReflectionCache

use of org.mule.runtime.module.extension.internal.util.ReflectionCache in project mule by mulesoft.

the class MetadataKeyIdObjectResolverTestCase method setUp.

@Before
public void setUp() {
    mockMetadataKeyModelProp(continentParam, 1);
    mockMetadataKeyModelProp(countryParam, 2);
    mockMetadataKeyModelProp(cityParam, 3);
    ReflectionCache reflectionCache = new ReflectionCache();
    mockDeclaringMemberModelProp(continentParam, CONTINENT, reflectionCache);
    mockDeclaringMemberModelProp(countryParam, COUNTRY, reflectionCache);
    mockDeclaringMemberModelProp(cityParam, CITY, reflectionCache);
    mockQueryModelProp(continentParam);
    mockQueryModelProp(countryParam);
    mockQueryModelProp(cityParam);
    when(componentModel.getName()).thenReturn(OPERATION_NAME);
}
Also used : ReflectionCache(org.mule.runtime.module.extension.internal.util.ReflectionCache) Before(org.junit.Before)

Example 8 with ReflectionCache

use of org.mule.runtime.module.extension.internal.util.ReflectionCache in project mule by mulesoft.

the class ConfigurationInstanceFactoryTestCase method before.

@Before
public void before() throws Exception {
    mockConfigurationInstance(configurationModel, new TestConfig());
    mockInterceptors(configurationModel, asList(() -> interceptor1, () -> interceptor2));
    when(configurationModel.getOperationModels()).thenReturn(ImmutableList.of());
    when(configurationModel.getSourceModels()).thenReturn(ImmutableList.of());
    when(extensionModel.getOperationModels()).thenReturn(asList(operationModel));
    when(extensionModel.getSourceModels()).thenReturn(asList(sourceModel));
    when(operationModel.getModelProperty(ConnectivityModelProperty.class)).thenReturn(of(new ConnectivityModelProperty(Banana.class)));
    when(sourceModel.getModelProperty(ConnectivityModelProperty.class)).thenReturn(of(new ConnectivityModelProperty(Banana.class)));
    when(sourceModel.getErrorCallback()).thenReturn(of(sourceCallbackModel));
    when(sourceModel.getSuccessCallback()).thenReturn(of(sourceCallbackModel));
    when(muleContext.getConfiguration().getDefaultEncoding()).thenReturn(ENCODING);
    resolverSet = ConfigurationObjectBuilderTestCase.createResolverSet();
    factory = new ConfigurationInstanceFactory<>(extensionModel, configurationModel, resolverSet, new ReflectionCache(), muleContext);
}
Also used : ConnectivityModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ConnectivityModelProperty) TestConfig(org.mule.runtime.module.extension.internal.runtime.execution.ConfigurationObjectBuilderTestCase.TestConfig) ReflectionCache(org.mule.runtime.module.extension.internal.util.ReflectionCache) Before(org.junit.Before)

Example 9 with ReflectionCache

use of org.mule.runtime.module.extension.internal.util.ReflectionCache in project mule by mulesoft.

the class ConfigOverrideValueResolverWrapper method getParameterValueFromConfigField.

private Function<Object, Object> getParameterValueFromConfigField(ConfigurationInstance config, String fieldName) {
    Field parameterField = getField(config.getValue().getClass(), fieldName, reflectionCache).orElseThrow(() -> new IllegalArgumentException("Missing field with name [" + fieldName + "] in config [" + config.getName() + "]"));
    parameterField.setAccessible(true);
    return (target) -> {
        try {
            return parameterField.get(target);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException("Failed to read field with name [" + parameterField.getName() + " in config [" + config.getName() + "]: " + e.getMessage());
        }
    };
}
Also used : ParameterGroupDescriptor(org.mule.runtime.module.extension.internal.loader.ParameterGroupDescriptor) I18nMessageFactory.createStaticMessage(org.mule.runtime.api.i18n.I18nMessageFactory.createStaticMessage) IntrospectionUtils.getField(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getField) InitialisationException(org.mule.runtime.api.lifecycle.InitialisationException) Preconditions.checkArgument(org.mule.runtime.api.util.Preconditions.checkArgument) ReflectionCache(org.mule.runtime.module.extension.internal.util.ReflectionCache) LifecycleUtils.initialiseIfNeeded(org.mule.runtime.core.api.lifecycle.LifecycleUtils.initialiseIfNeeded) ConfigurationInstance(org.mule.runtime.extension.api.runtime.config.ConfigurationInstance) Initialisable(org.mule.runtime.api.lifecycle.Initialisable) Field(java.lang.reflect.Field) Function(java.util.function.Function) String.format(java.lang.String.format) DeclaringMemberModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.DeclaringMemberModelProperty) DefaultMuleException(org.mule.runtime.api.exception.DefaultMuleException) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) MuleContext(org.mule.runtime.core.api.MuleContext) MuleException(org.mule.runtime.api.exception.MuleException) Optional(java.util.Optional) DEFAULT_GROUP_NAME(org.mule.runtime.api.meta.model.parameter.ParameterGroupModel.DEFAULT_GROUP_NAME) ParameterGroupModel(org.mule.runtime.api.meta.model.parameter.ParameterGroupModel) ParameterGroupModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ParameterGroupModelProperty) IntrospectionUtils.getField(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getField) Field(java.lang.reflect.Field)

Example 10 with ReflectionCache

use of org.mule.runtime.module.extension.internal.util.ReflectionCache in project mule by mulesoft.

the class InputParametersTypeModelValidator method validateType.

private void validateType(String message, NamedObject namedObject, MetadataType type, ProblemsReporter problems, Set<Class<?>> validatedTypes) {
    ReflectionCache reflectionCache = new ReflectionCache();
    getClassForValidation(type).ifPresent(parameterType -> type.accept(new MetadataTypeVisitor() {

        @Override
        public void visitObject(ObjectType objectType) {
            if (validatedTypes.add(parameterType)) {
                Collection<ObjectFieldType> parameters = objectType.getFields();
                Set<String> fieldsWithGetters = getFieldsWithGetters(parameterType, reflectionCache).stream().map(TypeUtils::getAlias).map(String::toLowerCase).collect(toSet());
                Set<String> parameterWithoutGetters = parameters.stream().filter(p -> {
                    StereotypeTypeAnnotation stereotypes = p.getAnnotation(StereotypeTypeAnnotation.class).orElse(null);
                    return stereotypes != null ? stereotypes.getAllowedStereotypes().isEmpty() : true;
                }).map(f -> f.getKey().getName().getLocalPart()).filter(fieldName -> !fieldsWithGetters.contains(fieldName.toLowerCase())).collect(toSet());
                if (!parameterWithoutGetters.isEmpty()) {
                    problems.addError(new Problem(namedObject, format("%s of type '%s' which contains fields (%s) that doesn't have the corresponding getter methods or getter methods that doesn't correspond to any of the present fields", message, parameterType.getName(), parameterWithoutGetters.stream().collect(joining(", ")))));
                }
            }
        }

        @Override
        public void visitArrayType(ArrayType arrayType) {
            validateType(message, namedObject, arrayType.getType(), problems, validatedTypes);
        }
    }));
}
Also used : Optional.empty(java.util.Optional.empty) StereotypeTypeAnnotation(org.mule.runtime.extension.api.declaration.type.annotation.StereotypeTypeAnnotation) OperationModel(org.mule.runtime.api.meta.model.operation.OperationModel) NamedObject(org.mule.runtime.api.meta.NamedObject) ComponentModel(org.mule.runtime.api.meta.model.ComponentModel) JAVA(org.mule.metadata.api.model.MetadataFormat.JAVA) HashSet(java.util.HashSet) SourceModel(org.mule.runtime.api.meta.model.source.SourceModel) ArrayType(org.mule.metadata.api.model.ArrayType) IdempotentExtensionWalker(org.mule.runtime.api.meta.model.util.IdempotentExtensionWalker) Problem(org.mule.runtime.extension.api.loader.Problem) Collectors.toSet(java.util.stream.Collectors.toSet) IntrospectionUtils.getFieldsWithGetters(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getFieldsWithGetters) TypeUtils(org.mule.runtime.extension.api.declaration.type.TypeUtils) ExtensionModelValidator(org.mule.runtime.extension.api.loader.ExtensionModelValidator) ObjectType(org.mule.metadata.api.model.ObjectType) ProblemsReporter(org.mule.runtime.extension.api.loader.ProblemsReporter) Collection(java.util.Collection) Set(java.util.Set) ReflectionCache(org.mule.runtime.module.extension.internal.util.ReflectionCache) String.format(java.lang.String.format) Collectors.joining(java.util.stream.Collectors.joining) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) ExtensionMetadataTypeUtils.getType(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getType) SourceCallbackModel(org.mule.runtime.api.meta.model.source.SourceCallbackModel) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) NameUtils.getComponentModelTypeName(org.mule.runtime.extension.api.util.NameUtils.getComponentModelTypeName) MetadataType(org.mule.metadata.api.model.MetadataType) Optional(java.util.Optional) ArrayType(org.mule.metadata.api.model.ArrayType) ObjectType(org.mule.metadata.api.model.ObjectType) ReflectionCache(org.mule.runtime.module.extension.internal.util.ReflectionCache) StereotypeTypeAnnotation(org.mule.runtime.extension.api.declaration.type.annotation.StereotypeTypeAnnotation) Problem(org.mule.runtime.extension.api.loader.Problem) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) TypeUtils(org.mule.runtime.extension.api.declaration.type.TypeUtils) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor)

Aggregations

ReflectionCache (org.mule.runtime.module.extension.internal.util.ReflectionCache)13 String.format (java.lang.String.format)5 MetadataType (org.mule.metadata.api.model.MetadataType)5 ObjectType (org.mule.metadata.api.model.ObjectType)5 Optional (java.util.Optional)4 ArrayType (org.mule.metadata.api.model.ArrayType)4 MetadataTypeVisitor (org.mule.metadata.api.visitor.MetadataTypeVisitor)4 OperationModel (org.mule.runtime.api.meta.model.operation.OperationModel)4 ParameterGroupModel (org.mule.runtime.api.meta.model.parameter.ParameterGroupModel)4 ParameterModel (org.mule.runtime.api.meta.model.parameter.ParameterModel)4 SourceModel (org.mule.runtime.api.meta.model.source.SourceModel)4 IdempotentExtensionWalker (org.mule.runtime.api.meta.model.util.IdempotentExtensionWalker)4 Set (java.util.Set)3 Collectors.joining (java.util.stream.Collectors.joining)3 StringUtils.isBlank (org.apache.commons.lang3.StringUtils.isBlank)3 Before (org.junit.Before)3 ExtensionModel (org.mule.runtime.api.meta.model.ExtensionModel)3 ExtensionModelValidator (org.mule.runtime.extension.api.loader.ExtensionModelValidator)3 Problem (org.mule.runtime.extension.api.loader.Problem)3 ProblemsReporter (org.mule.runtime.extension.api.loader.ProblemsReporter)3