Search in sources :

Example 1 with BasicTypeMetadataVisitor

use of org.mule.metadata.api.visitor.BasicTypeMetadataVisitor in project mule by mulesoft.

the class ExtensionDefinitionParser method parseCollectionParameter.

/**
 * Registers a definition for a {@link ParameterModel} which represents an {@link ArrayType}
 *
 * @param key               the key that the parsed value should have on the parsed parameter's map
 * @param name              the parameter's name
 * @param arrayType         the parameter's {@link ArrayType}
 * @param defaultValue      the parameter's default value
 * @param expressionSupport the parameter's {@link ExpressionSupport}
 * @param required          whether the parameter is required
 */
protected void parseCollectionParameter(String key, String name, ArrayType arrayType, Object defaultValue, ExpressionSupport expressionSupport, boolean required, DslElementSyntax parameterDsl, Set<ModelProperty> modelProperties) {
    parseAttributeParameter(key, name, arrayType, defaultValue, expressionSupport, required, modelProperties);
    Class<?> collectionType = ExtensionMetadataTypeUtils.getType(arrayType).orElse(null);
    if (Set.class.equals(collectionType)) {
        collectionType = HashSet.class;
    } else if (Collection.class.equals(collectionType) || Iterable.class.equals(collectionType) || collectionType == null) {
        collectionType = List.class;
    }
    final String collectionElementName = parameterDsl.getElementName();
    addParameter(getChildKey(key), fromChildConfiguration(collectionType).withWrapperIdentifier(collectionElementName));
    addDefinition(baseDefinitionBuilder.withIdentifier(collectionElementName).withTypeDefinition(fromType(collectionType)).build());
    Optional<DslElementSyntax> collectionItemDsl = parameterDsl.getGeneric(arrayType.getType());
    if (parameterDsl.supportsChildDeclaration() && collectionItemDsl.isPresent()) {
        String itemIdentifier = collectionItemDsl.get().getElementName();
        String itemNamespace = collectionItemDsl.get().getPrefix();
        arrayType.getType().accept(new BasicTypeMetadataVisitor() {

            private void addBasicTypeDefinition(MetadataType metadataType) {
                Builder itemDefinitionBuilder = baseDefinitionBuilder.withIdentifier(itemIdentifier).withNamespace(itemNamespace).withTypeDefinition(fromType(ExtensionMetadataTypeUtils.getType(metadataType).orElse(Object.class))).withTypeConverter(value -> resolverOf(name, metadataType, value, getDefaultValue(metadataType).orElse(null), getExpressionSupport(metadataType), false, emptySet()));
                addDefinition(itemDefinitionBuilder.build());
            }

            @Override
            protected void visitBasicType(MetadataType metadataType) {
                addBasicTypeDefinition(metadataType);
            }

            @Override
            public void visitDate(DateType dateType) {
                addBasicTypeDefinition(dateType);
            }

            @Override
            public void visitDateTime(DateTimeType dateTimeType) {
                addBasicTypeDefinition(dateTimeType);
            }

            @Override
            public void visitObject(ObjectType objectType) {
                if (isMap(objectType)) {
                    return;
                }
                DslElementSyntax itemDsl = collectionItemDsl.get();
                if ((itemDsl.supportsTopLevelDeclaration() || itemDsl.supportsChildDeclaration()) && !parsingContext.isRegistered(itemDsl.getElementName(), itemDsl.getPrefix())) {
                    try {
                        parsingContext.registerObjectType(itemDsl.getElementName(), itemDsl.getPrefix(), objectType);
                        new ObjectTypeParameterParser(baseDefinitionBuilder, objectType, getContextClassLoader(), dslResolver, parsingContext).parse().forEach(definition -> addDefinition(definition));
                    } catch (ConfigurationException e) {
                        throw new MuleRuntimeException(createStaticMessage("Could not create parser for collection complex type"), e);
                    }
                }
            }
        });
    }
}
Also used : InfrastructureTypeMapping.getNameMap(org.mule.runtime.module.extension.internal.loader.java.type.InfrastructureTypeMapping.getNameMap) ExpressionBasedParameterResolverValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ExpressionBasedParameterResolverValueResolver) StaticValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.StaticValueResolver) KeyAttributeDefinitionPair(org.mule.runtime.dsl.api.component.KeyAttributeDefinitionPair) InfrastructureParameterModelProperty(org.mule.runtime.extension.api.property.InfrastructureParameterModelProperty) BEHAVIOUR(org.mule.runtime.api.meta.model.parameter.ParameterRole.BEHAVIOUR) ParameterRole(org.mule.runtime.api.meta.model.parameter.ParameterRole) DateTimeType(org.mule.metadata.api.model.DateTimeType) RequiredParameterValueResolverWrapper(org.mule.runtime.module.extension.internal.runtime.resolver.RequiredParameterValueResolverWrapper) Builder.fromSimpleParameter(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromSimpleParameter) QueryParameterModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.QueryParameterModelProperty) Instant.ofEpochMilli(java.time.Instant.ofEpochMilli) ArrayType(org.mule.metadata.api.model.ArrayType) Map(java.util.Map) NestableElementModelVisitor(org.mule.runtime.api.meta.model.nested.NestableElementModelVisitor) ExpressionTypedValueValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ExpressionTypedValueValueResolver) ClassTypeLoader(org.mule.metadata.api.ClassTypeLoader) ModelProperty(org.mule.runtime.api.meta.model.ModelProperty) NestableElementModel(org.mule.runtime.api.meta.model.nested.NestableElementModel) ExtensionModelUtils.isContent(org.mule.runtime.extension.api.util.ExtensionModelUtils.isContent) SchedulingStrategyParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.SchedulingStrategyParsingDelegate) ExtensionMetadataTypeUtils.isMap(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isMap) IntrospectionUtils.isTargetParameter(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.isTargetParameter) ObjectType(org.mule.metadata.api.model.ObjectType) ParameterGroupDescriptor(org.mule.runtime.module.extension.internal.loader.ParameterGroupDescriptor) Set(java.util.Set) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) DateType(org.mule.metadata.api.model.DateType) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) ZoneId(java.time.ZoneId) ComponentBuildingDefinition(org.mule.runtime.dsl.api.component.ComponentBuildingDefinition) DefaultValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.DefaultValueResolverParsingDelegate) DateTimeParseException(java.time.format.DateTimeParseException) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) StringType(org.mule.metadata.api.model.StringType) MetadataType(org.mule.metadata.api.model.MetadataType) DslSyntaxResolver(org.mule.runtime.extension.api.dsl.syntax.resolver.DslSyntaxResolver) IntrospectionUtils.getContainerName(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getContainerName) ParameterResolverValueResolverWrapper(org.mule.runtime.module.extension.internal.runtime.resolver.ParameterResolverValueResolverWrapper) DefaultConversionService(org.springframework.core.convert.support.DefaultConversionService) StackedTypesModelProperty.getStackedTypesModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.stackabletypes.StackedTypesModelProperty.getStackedTypesModelProperty) NativeQueryParameterValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.NativeQueryParameterValueResolver) MetadataTypeUtils.getDefaultValue(org.mule.metadata.api.utils.MetadataTypeUtils.getDefaultValue) ExtensionsTypeLoaderFactory(org.mule.runtime.extension.api.declaration.type.ExtensionsTypeLoaderFactory) StackedTypesModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.stackabletypes.StackedTypesModelProperty) LocalDateTime(java.time.LocalDateTime) Builder.fromChildMapConfiguration(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromChildMapConfiguration) VALUE_ATTRIBUTE_NAME(org.mule.runtime.internal.dsl.DslConstants.VALUE_ATTRIBUTE_NAME) Supplier(java.util.function.Supplier) ObjectTypeParameterParser(org.mule.runtime.module.extension.internal.config.dsl.parameter.ObjectTypeParameterParser) ArrayList(java.util.ArrayList) TypeSafeValueResolverWrapper(org.mule.runtime.module.extension.internal.runtime.resolver.TypeSafeValueResolverWrapper) LinkedHashMap(java.util.LinkedHashMap) Calendar(java.util.Calendar) ExtensionMetadataTypeUtils.getExpressionSupport(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getExpressionSupport) TypedInlineParameterGroupParser(org.mule.runtime.module.extension.internal.config.dsl.parameter.TypedInlineParameterGroupParser) MediaTypeValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.MediaTypeValueResolverParsingDelegate) ConversionService(org.springframework.core.convert.ConversionService) TypeDefinition.fromType(org.mule.runtime.dsl.api.component.TypeDefinition.fromType) MuleExtensionUtils.isExpression(org.mule.runtime.module.extension.internal.util.MuleExtensionUtils.isExpression) ParameterizedModel(org.mule.runtime.api.meta.model.parameter.ParameterizedModel) ValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ValueResolver) ConfigurationException(org.mule.runtime.core.api.config.ConfigurationException) I18nMessageFactory.createStaticMessage(org.mule.runtime.api.i18n.I18nMessageFactory.createStaticMessage) ParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.ParsingDelegate) Builder.fromMultipleDefinitions(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromMultipleDefinitions) ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) Reference(org.mule.runtime.api.util.Reference) DefaultObjectParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.DefaultObjectParsingDelegate) NOT_SUPPORTED(org.mule.runtime.api.meta.ExpressionSupport.NOT_SUPPORTED) JavaTypeUtils.getType(org.mule.metadata.java.api.utils.JavaTypeUtils.getType) ExtensionMetadataTypeUtils.getId(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getId) TemplateParser(org.mule.runtime.core.privileged.util.TemplateParser) IntrospectionUtils.getMemberName(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getMemberName) Date(java.util.Date) Builder.fromChildConfiguration(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromChildConfiguration) TypeConverter(org.mule.runtime.dsl.api.component.TypeConverter) IntrospectionUtils.isLiteral(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.isLiteral) TypeDefinition.fromMapEntryType(org.mule.runtime.dsl.api.component.TypeDefinition.fromMapEntryType) ProcessorChainValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ProcessorChainValueResolver) IntrospectionUtils.isTypedValue(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.isTypedValue) TypedValueValueResolverWrapper(org.mule.runtime.module.extension.internal.runtime.resolver.TypedValueValueResolverWrapper) PoolingProfile(org.mule.runtime.api.config.PoolingProfile) ParameterGroupModel(org.mule.runtime.api.meta.model.parameter.ParameterGroupModel) Builder.fromChildCollectionConfiguration(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromChildCollectionConfiguration) ISODateTimeFormat(org.joda.time.format.ISODateTimeFormat) ObjectParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.ObjectParsingDelegate) Collection(java.util.Collection) REQUIRED(org.mule.runtime.api.meta.ExpressionSupport.REQUIRED) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Instant(java.time.Instant) String.format(java.lang.String.format) NestedRouteModel(org.mule.runtime.api.meta.model.nested.NestedRouteModel) List(java.util.List) DslElementSyntax(org.mule.runtime.extension.api.dsl.syntax.DslElementSyntax) LocalDate(java.time.LocalDate) Optional(java.util.Optional) Builder(org.mule.runtime.dsl.api.component.ComponentBuildingDefinition.Builder) CharsetValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.CharsetValueResolverParsingDelegate) TlsContextFactory(org.mule.runtime.api.tls.TlsContextFactory) ParameterModel(org.mule.runtime.api.meta.model.parameter.ParameterModel) RetryPolicyTemplate(org.mule.runtime.core.api.retry.policy.RetryPolicyTemplate) TypeSafeExpressionValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.TypeSafeExpressionValueResolver) KeyAttributeDefinitionPair.newBuilder(org.mule.runtime.dsl.api.component.KeyAttributeDefinitionPair.newBuilder) Builder.fromSimpleReferenceParameter(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromSimpleReferenceParameter) HashMap(java.util.HashMap) Processor(org.mule.runtime.core.api.processor.Processor) Builder.fromFixedValue(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromFixedValue) ConcurrentMap(java.util.concurrent.ConcurrentMap) ValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.ValueResolverParsingDelegate) HashSet(java.util.HashSet) ExtensionMetadataTypeUtils.isFlattenedParameterGroup(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isFlattenedParameterGroup) ImmutableList(com.google.common.collect.ImmutableList) Literal(org.mule.runtime.extension.api.runtime.parameter.Literal) BasicTypeMetadataVisitor(org.mule.metadata.api.visitor.BasicTypeMetadataVisitor) ParameterGroupModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ParameterGroupModelProperty) ExclusiveOptionalModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ExclusiveOptionalModelProperty) Collections.emptyMap(java.util.Collections.emptyMap) Collections.emptySet(java.util.Collections.emptySet) NameUtils.hyphenize(org.mule.runtime.extension.api.util.NameUtils.hyphenize) IntrospectionUtils.isParameterResolver(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.isParameterResolver) ExpressionSupport(org.mule.runtime.api.meta.ExpressionSupport) NestedChainModel(org.mule.runtime.api.meta.model.nested.NestedChainModel) DateTime(org.joda.time.DateTime) AttributeDefinition(org.mule.runtime.dsl.api.component.AttributeDefinition) AnonymousInlineParameterGroupParser(org.mule.runtime.module.extension.internal.config.dsl.parameter.AnonymousInlineParameterGroupParser) Collectors.toList(java.util.stream.Collectors.toList) ExtensionMetadataTypeUtils(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils) RouteComponentParser(org.mule.runtime.module.extension.internal.config.dsl.construct.RouteComponentParser) FixedTypeParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.FixedTypeParsingDelegate) NestedComponentModel(org.mule.runtime.api.meta.model.nested.NestedComponentModel) TopLevelParameterObjectFactory(org.mule.runtime.module.extension.internal.config.dsl.parameter.TopLevelParameterObjectFactory) ImplementingTypeModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ImplementingTypeModelProperty) StaticLiteralValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.StaticLiteralValueResolver) ObjectTypeParameterParser(org.mule.runtime.module.extension.internal.config.dsl.parameter.ObjectTypeParameterParser) Builder(org.mule.runtime.dsl.api.component.ComponentBuildingDefinition.Builder) KeyAttributeDefinitionPair.newBuilder(org.mule.runtime.dsl.api.component.KeyAttributeDefinitionPair.newBuilder) MetadataType(org.mule.metadata.api.model.MetadataType) BasicTypeMetadataVisitor(org.mule.metadata.api.visitor.BasicTypeMetadataVisitor) ObjectType(org.mule.metadata.api.model.ObjectType) DateTimeType(org.mule.metadata.api.model.DateTimeType) ConfigurationException(org.mule.runtime.core.api.config.ConfigurationException) DslElementSyntax(org.mule.runtime.extension.api.dsl.syntax.DslElementSyntax) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Collectors.toList(java.util.stream.Collectors.toList) DateType(org.mule.metadata.api.model.DateType)

Example 2 with BasicTypeMetadataVisitor

use of org.mule.metadata.api.visitor.BasicTypeMetadataVisitor in project mule by mulesoft.

the class ParameterModelsLoaderDelegate method parseNullSafe.

private void parseNullSafe(ExtensionParameter extensionParameter, ParameterDeclarer parameter) {
    if (extensionParameter.isAnnotatedWith(NullSafe.class)) {
        if (extensionParameter.isAnnotatedWith(ConfigOverride.class)) {
            throw new IllegalParameterModelDefinitionException(format("Parameter '%s' is annotated with '@%s' and also marked as a config override, which is redundant. " + "The default value for this parameter will come from the configuration parameter", extensionParameter.getName(), NullSafe.class.getSimpleName()));
        }
        if (extensionParameter.isRequired() && !extensionParameter.isAnnotatedWith(ParameterGroup.class)) {
            throw new IllegalParameterModelDefinitionException(format("Parameter '%s' is required but annotated with '@%s', which is redundant", extensionParameter.getName(), NullSafe.class.getSimpleName()));
        }
        Type nullSafeAnnotationType = extensionParameter.getValueFromAnnotation(NullSafe.class).get().getClassValue(NullSafe::defaultImplementingType);
        final boolean hasDefaultOverride = !nullSafeAnnotationType.isSameType(Object.class);
        MetadataType nullSafeType = hasDefaultOverride ? nullSafeAnnotationType.asMetadataType() : parameter.getDeclaration().getType();
        boolean isInstantiable = hasDefaultOverride ? nullSafeAnnotationType.isInstantiable() : extensionParameter.getType().isInstantiable();
        parameter.getDeclaration().getType().accept(new BasicTypeMetadataVisitor() {

            @Override
            protected void visitBasicType(MetadataType metadataType) {
                throw new IllegalParameterModelDefinitionException(format("Parameter '%s' is annotated with '@%s' but is of type '%s'. That annotation can only be " + "used with complex types (Pojos, Lists, Maps)", extensionParameter.getName(), NullSafe.class.getSimpleName(), extensionParameter.getType().getName()));
            }

            @Override
            public void visitArrayType(ArrayType arrayType) {
                if (hasDefaultOverride) {
                    throw new IllegalParameterModelDefinitionException(format("Parameter '%s' is annotated with '@%s' is of type '%s'" + " but a 'defaultImplementingType' was provided." + " Type override is not allowed for Collections", extensionParameter.getName(), NullSafe.class.getSimpleName(), extensionParameter.getType().getName()));
                }
            }

            @Override
            public void visitObject(ObjectType objectType) {
                if (hasDefaultOverride && isMap(objectType)) {
                    throw new IllegalParameterModelDefinitionException(format("Parameter '%s' is annotated with '@%s' is of type '%s'" + " but a 'defaultImplementingType' was provided." + " Type override is not allowed for Maps", extensionParameter.getName(), NullSafe.class.getSimpleName(), extensionParameter.getType().getName()));
                }
                if (hasDefaultOverride && extensionParameter.getType().isInstantiable()) {
                    throw new IllegalParameterModelDefinitionException(format("Parameter '%s' is annotated with '@%s' is of concrete type '%s'," + " but a 'defaultImplementingType' was provided." + " Type override is not allowed for concrete types", extensionParameter.getName(), NullSafe.class.getSimpleName(), extensionParameter.getType().getName()));
                }
                if (!isInstantiable && !isMap(nullSafeType)) {
                    throw new IllegalParameterModelDefinitionException(format("Parameter '%s' is annotated with '@%s' but is of type '%s'. That annotation can only be " + "used with complex instantiable types (Pojos, Lists, Maps)", extensionParameter.getName(), NullSafe.class.getSimpleName(), extensionParameter.getType().getName()));
                }
                if (hasDefaultOverride && !extensionParameter.getType().isAssignableFrom(nullSafeAnnotationType)) {
                    throw new IllegalParameterModelDefinitionException(format("Parameter '%s' is annotated with '@%s' of type '%s', but provided type '%s" + " is not a subtype of the parameter's type", extensionParameter.getName(), NullSafe.class.getSimpleName(), extensionParameter.getType().getName(), getType(nullSafeType).getName()));
                }
            }
        });
        parameter.withModelProperty(new NullSafeModelProperty(nullSafeType));
        if (hasDefaultOverride) {
            parameter.withModelProperty(new DefaultImplementingTypeModelProperty(nullSafeType));
        }
    }
}
Also used : BasicTypeMetadataVisitor(org.mule.metadata.api.visitor.BasicTypeMetadataVisitor) ArrayType(org.mule.metadata.api.model.ArrayType) ObjectType(org.mule.metadata.api.model.ObjectType) Type(org.mule.runtime.module.extension.api.loader.java.type.Type) ArrayType(org.mule.metadata.api.model.ArrayType) ObjectType(org.mule.metadata.api.model.ObjectType) MetadataType(org.mule.metadata.api.model.MetadataType) JavaTypeUtils.getType(org.mule.metadata.java.api.utils.JavaTypeUtils.getType) NullSafeModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.NullSafeModelProperty) MetadataType(org.mule.metadata.api.model.MetadataType) DefaultImplementingTypeModelProperty(org.mule.runtime.extension.api.property.DefaultImplementingTypeModelProperty) NullSafe(org.mule.runtime.extension.api.annotation.param.NullSafe) ConfigOverride(org.mule.runtime.extension.api.annotation.param.ConfigOverride) IllegalParameterModelDefinitionException(org.mule.runtime.extension.api.exception.IllegalParameterModelDefinitionException)

Example 3 with BasicTypeMetadataVisitor

use of org.mule.metadata.api.visitor.BasicTypeMetadataVisitor in project mule by mulesoft.

the class ExtensionDefinitionParser method parseMapParameters.

/**
 * Registers a definition for a {@link ParameterModel} which represents an open {@link ObjectType}
 *
 * @param key               the key that the parsed value should have on the parsed parameter's map
 * @param name              the parameter's name
 * @param dictionaryType    the parameter's open {@link ObjectType}
 * @param defaultValue      the parameter's default value
 * @param expressionSupport the parameter's {@link ExpressionSupport}
 * @param required          whether the parameter is required
 */
protected void parseMapParameters(String key, String name, ObjectType dictionaryType, Object defaultValue, ExpressionSupport expressionSupport, boolean required, DslElementSyntax paramDsl, Set<ModelProperty> modelProperties) {
    parseAttributeParameter(key, name, dictionaryType, defaultValue, expressionSupport, required, modelProperties);
    Class<? extends Map> mapType = getType(dictionaryType);
    if (ConcurrentMap.class.equals(mapType)) {
        mapType = ConcurrentHashMap.class;
    } else if (Map.class.equals(mapType)) {
        mapType = LinkedHashMap.class;
    }
    final MetadataType valueType = dictionaryType.getOpenRestriction().orElse(typeLoader.load(Object.class));
    final Class<?> valueClass = getType(valueType);
    final MetadataType keyType = typeLoader.load(String.class);
    final Class<?> keyClass = String.class;
    final String mapElementName = paramDsl.getElementName();
    addParameter(getChildKey(key), fromChildMapConfiguration(String.class, valueClass).withWrapperIdentifier(mapElementName).withDefaultValue(defaultValue));
    addDefinition(baseDefinitionBuilder.withIdentifier(mapElementName).withTypeDefinition(fromType(mapType)).build());
    Optional<DslElementSyntax> mapValueChildDsl = paramDsl.getGeneric(valueType);
    if (!mapValueChildDsl.isPresent()) {
        return;
    }
    DslElementSyntax valueDsl = mapValueChildDsl.get();
    valueType.accept(new MetadataTypeVisitor() {

        @Override
        protected void defaultVisit(MetadataType metadataType) {
            String parameterName = paramDsl.getAttributeName();
            addDefinition(baseDefinitionBuilder.withIdentifier(valueDsl.getElementName()).withTypeDefinition(fromMapEntryType(keyClass, valueClass)).withKeyTypeConverter(value -> resolverOf(parameterName, keyType, value, null, expressionSupport, true, emptySet(), false)).withTypeConverter(value -> resolverOf(parameterName, valueType, value, null, expressionSupport, true, emptySet(), false)).build());
        }

        @Override
        public void visitObject(ObjectType objectType) {
            defaultVisit(objectType);
            Optional<DslElementSyntax> containedElement = valueDsl.getContainedElement(VALUE_ATTRIBUTE_NAME);
            if (isMap(objectType) || !containedElement.isPresent()) {
                return;
            }
            DslElementSyntax valueChild = containedElement.get();
            if ((valueChild.supportsTopLevelDeclaration() || (valueChild.supportsChildDeclaration() && !valueChild.isWrapped())) && !parsingContext.isRegistered(valueChild.getElementName(), valueChild.getPrefix())) {
                try {
                    parsingContext.registerObjectType(valueChild.getElementName(), valueChild.getPrefix(), objectType);
                    new ObjectTypeParameterParser(baseDefinitionBuilder, objectType, getContextClassLoader(), dslResolver, parsingContext).parse().forEach(definition -> addDefinition(definition));
                } catch (ConfigurationException e) {
                    throw new MuleRuntimeException(createStaticMessage("Could not create parser for map complex type"), e);
                }
            }
        }

        @Override
        public void visitArrayType(ArrayType arrayType) {
            defaultVisit(arrayType);
            Optional<DslElementSyntax> valueListGenericDsl = valueDsl.getGeneric(arrayType.getType());
            if (valueDsl.supportsChildDeclaration() && valueListGenericDsl.isPresent()) {
                arrayType.getType().accept(new BasicTypeMetadataVisitor() {

                    @Override
                    protected void visitBasicType(MetadataType metadataType) {
                        String parameterName = paramDsl.getAttributeName();
                        addDefinition(baseDefinitionBuilder.withIdentifier(valueListGenericDsl.get().getElementName()).withTypeDefinition(fromType(getType(metadataType))).withTypeConverter(value -> resolverOf(parameterName, metadataType, value, getDefaultValue(metadataType), getExpressionSupport(metadataType), false, emptySet())).build());
                    }

                    @Override
                    protected void defaultVisit(MetadataType metadataType) {
                        addDefinition(baseDefinitionBuilder.withIdentifier(valueListGenericDsl.get().getElementName()).withTypeDefinition(fromType(ValueResolver.class)).withObjectFactoryType(TopLevelParameterObjectFactory.class).withConstructorParameterDefinition(fromFixedValue(arrayType.getType()).build()).withConstructorParameterDefinition(fromFixedValue(getContextClassLoader()).build()).build());
                    }
                });
            }
        }
    });
}
Also used : InfrastructureTypeMapping.getNameMap(org.mule.runtime.module.extension.internal.loader.java.type.InfrastructureTypeMapping.getNameMap) ExpressionBasedParameterResolverValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ExpressionBasedParameterResolverValueResolver) StaticValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.StaticValueResolver) KeyAttributeDefinitionPair(org.mule.runtime.dsl.api.component.KeyAttributeDefinitionPair) InfrastructureParameterModelProperty(org.mule.runtime.extension.api.property.InfrastructureParameterModelProperty) BEHAVIOUR(org.mule.runtime.api.meta.model.parameter.ParameterRole.BEHAVIOUR) ParameterRole(org.mule.runtime.api.meta.model.parameter.ParameterRole) DateTimeType(org.mule.metadata.api.model.DateTimeType) RequiredParameterValueResolverWrapper(org.mule.runtime.module.extension.internal.runtime.resolver.RequiredParameterValueResolverWrapper) Builder.fromSimpleParameter(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromSimpleParameter) QueryParameterModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.QueryParameterModelProperty) Instant.ofEpochMilli(java.time.Instant.ofEpochMilli) ArrayType(org.mule.metadata.api.model.ArrayType) Map(java.util.Map) NestableElementModelVisitor(org.mule.runtime.api.meta.model.nested.NestableElementModelVisitor) ExpressionTypedValueValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ExpressionTypedValueValueResolver) ClassTypeLoader(org.mule.metadata.api.ClassTypeLoader) ModelProperty(org.mule.runtime.api.meta.model.ModelProperty) NestableElementModel(org.mule.runtime.api.meta.model.nested.NestableElementModel) ExtensionModelUtils.isContent(org.mule.runtime.extension.api.util.ExtensionModelUtils.isContent) SchedulingStrategyParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.SchedulingStrategyParsingDelegate) ExtensionMetadataTypeUtils.isMap(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isMap) IntrospectionUtils.isTargetParameter(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.isTargetParameter) ObjectType(org.mule.metadata.api.model.ObjectType) ParameterGroupDescriptor(org.mule.runtime.module.extension.internal.loader.ParameterGroupDescriptor) Set(java.util.Set) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) DateType(org.mule.metadata.api.model.DateType) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) ZoneId(java.time.ZoneId) ComponentBuildingDefinition(org.mule.runtime.dsl.api.component.ComponentBuildingDefinition) DefaultValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.DefaultValueResolverParsingDelegate) DateTimeParseException(java.time.format.DateTimeParseException) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) StringType(org.mule.metadata.api.model.StringType) MetadataType(org.mule.metadata.api.model.MetadataType) DslSyntaxResolver(org.mule.runtime.extension.api.dsl.syntax.resolver.DslSyntaxResolver) IntrospectionUtils.getContainerName(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getContainerName) ParameterResolverValueResolverWrapper(org.mule.runtime.module.extension.internal.runtime.resolver.ParameterResolverValueResolverWrapper) DefaultConversionService(org.springframework.core.convert.support.DefaultConversionService) StackedTypesModelProperty.getStackedTypesModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.stackabletypes.StackedTypesModelProperty.getStackedTypesModelProperty) NativeQueryParameterValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.NativeQueryParameterValueResolver) MetadataTypeUtils.getDefaultValue(org.mule.metadata.api.utils.MetadataTypeUtils.getDefaultValue) ExtensionsTypeLoaderFactory(org.mule.runtime.extension.api.declaration.type.ExtensionsTypeLoaderFactory) StackedTypesModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.stackabletypes.StackedTypesModelProperty) LocalDateTime(java.time.LocalDateTime) Builder.fromChildMapConfiguration(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromChildMapConfiguration) VALUE_ATTRIBUTE_NAME(org.mule.runtime.internal.dsl.DslConstants.VALUE_ATTRIBUTE_NAME) Supplier(java.util.function.Supplier) ObjectTypeParameterParser(org.mule.runtime.module.extension.internal.config.dsl.parameter.ObjectTypeParameterParser) ArrayList(java.util.ArrayList) TypeSafeValueResolverWrapper(org.mule.runtime.module.extension.internal.runtime.resolver.TypeSafeValueResolverWrapper) LinkedHashMap(java.util.LinkedHashMap) Calendar(java.util.Calendar) ExtensionMetadataTypeUtils.getExpressionSupport(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getExpressionSupport) TypedInlineParameterGroupParser(org.mule.runtime.module.extension.internal.config.dsl.parameter.TypedInlineParameterGroupParser) MediaTypeValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.MediaTypeValueResolverParsingDelegate) ConversionService(org.springframework.core.convert.ConversionService) TypeDefinition.fromType(org.mule.runtime.dsl.api.component.TypeDefinition.fromType) MuleExtensionUtils.isExpression(org.mule.runtime.module.extension.internal.util.MuleExtensionUtils.isExpression) ParameterizedModel(org.mule.runtime.api.meta.model.parameter.ParameterizedModel) ValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ValueResolver) ConfigurationException(org.mule.runtime.core.api.config.ConfigurationException) I18nMessageFactory.createStaticMessage(org.mule.runtime.api.i18n.I18nMessageFactory.createStaticMessage) ParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.ParsingDelegate) Builder.fromMultipleDefinitions(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromMultipleDefinitions) ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) Reference(org.mule.runtime.api.util.Reference) DefaultObjectParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.DefaultObjectParsingDelegate) NOT_SUPPORTED(org.mule.runtime.api.meta.ExpressionSupport.NOT_SUPPORTED) JavaTypeUtils.getType(org.mule.metadata.java.api.utils.JavaTypeUtils.getType) ExtensionMetadataTypeUtils.getId(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getId) TemplateParser(org.mule.runtime.core.privileged.util.TemplateParser) IntrospectionUtils.getMemberName(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getMemberName) Date(java.util.Date) Builder.fromChildConfiguration(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromChildConfiguration) TypeConverter(org.mule.runtime.dsl.api.component.TypeConverter) IntrospectionUtils.isLiteral(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.isLiteral) TypeDefinition.fromMapEntryType(org.mule.runtime.dsl.api.component.TypeDefinition.fromMapEntryType) ProcessorChainValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ProcessorChainValueResolver) IntrospectionUtils.isTypedValue(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.isTypedValue) TypedValueValueResolverWrapper(org.mule.runtime.module.extension.internal.runtime.resolver.TypedValueValueResolverWrapper) PoolingProfile(org.mule.runtime.api.config.PoolingProfile) ParameterGroupModel(org.mule.runtime.api.meta.model.parameter.ParameterGroupModel) Builder.fromChildCollectionConfiguration(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromChildCollectionConfiguration) ISODateTimeFormat(org.joda.time.format.ISODateTimeFormat) ObjectParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.ObjectParsingDelegate) Collection(java.util.Collection) REQUIRED(org.mule.runtime.api.meta.ExpressionSupport.REQUIRED) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Instant(java.time.Instant) String.format(java.lang.String.format) NestedRouteModel(org.mule.runtime.api.meta.model.nested.NestedRouteModel) List(java.util.List) DslElementSyntax(org.mule.runtime.extension.api.dsl.syntax.DslElementSyntax) LocalDate(java.time.LocalDate) Optional(java.util.Optional) Builder(org.mule.runtime.dsl.api.component.ComponentBuildingDefinition.Builder) CharsetValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.CharsetValueResolverParsingDelegate) TlsContextFactory(org.mule.runtime.api.tls.TlsContextFactory) ParameterModel(org.mule.runtime.api.meta.model.parameter.ParameterModel) RetryPolicyTemplate(org.mule.runtime.core.api.retry.policy.RetryPolicyTemplate) TypeSafeExpressionValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.TypeSafeExpressionValueResolver) KeyAttributeDefinitionPair.newBuilder(org.mule.runtime.dsl.api.component.KeyAttributeDefinitionPair.newBuilder) Builder.fromSimpleReferenceParameter(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromSimpleReferenceParameter) HashMap(java.util.HashMap) Processor(org.mule.runtime.core.api.processor.Processor) Builder.fromFixedValue(org.mule.runtime.dsl.api.component.AttributeDefinition.Builder.fromFixedValue) ConcurrentMap(java.util.concurrent.ConcurrentMap) ValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.ValueResolverParsingDelegate) HashSet(java.util.HashSet) ExtensionMetadataTypeUtils.isFlattenedParameterGroup(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isFlattenedParameterGroup) ImmutableList(com.google.common.collect.ImmutableList) Literal(org.mule.runtime.extension.api.runtime.parameter.Literal) BasicTypeMetadataVisitor(org.mule.metadata.api.visitor.BasicTypeMetadataVisitor) ParameterGroupModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ParameterGroupModelProperty) ExclusiveOptionalModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ExclusiveOptionalModelProperty) Collections.emptyMap(java.util.Collections.emptyMap) Collections.emptySet(java.util.Collections.emptySet) NameUtils.hyphenize(org.mule.runtime.extension.api.util.NameUtils.hyphenize) IntrospectionUtils.isParameterResolver(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.isParameterResolver) ExpressionSupport(org.mule.runtime.api.meta.ExpressionSupport) NestedChainModel(org.mule.runtime.api.meta.model.nested.NestedChainModel) DateTime(org.joda.time.DateTime) AttributeDefinition(org.mule.runtime.dsl.api.component.AttributeDefinition) AnonymousInlineParameterGroupParser(org.mule.runtime.module.extension.internal.config.dsl.parameter.AnonymousInlineParameterGroupParser) Collectors.toList(java.util.stream.Collectors.toList) ExtensionMetadataTypeUtils(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils) RouteComponentParser(org.mule.runtime.module.extension.internal.config.dsl.construct.RouteComponentParser) FixedTypeParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.FixedTypeParsingDelegate) NestedComponentModel(org.mule.runtime.api.meta.model.nested.NestedComponentModel) TopLevelParameterObjectFactory(org.mule.runtime.module.extension.internal.config.dsl.parameter.TopLevelParameterObjectFactory) ImplementingTypeModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ImplementingTypeModelProperty) StaticLiteralValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.StaticLiteralValueResolver) ObjectTypeParameterParser(org.mule.runtime.module.extension.internal.config.dsl.parameter.ObjectTypeParameterParser) Optional(java.util.Optional) MetadataType(org.mule.metadata.api.model.MetadataType) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) LinkedHashMap(java.util.LinkedHashMap) ArrayType(org.mule.metadata.api.model.ArrayType) BasicTypeMetadataVisitor(org.mule.metadata.api.visitor.BasicTypeMetadataVisitor) ObjectType(org.mule.metadata.api.model.ObjectType) ConfigurationException(org.mule.runtime.core.api.config.ConfigurationException) DslElementSyntax(org.mule.runtime.extension.api.dsl.syntax.DslElementSyntax) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) InfrastructureTypeMapping.getNameMap(org.mule.runtime.module.extension.internal.loader.java.type.InfrastructureTypeMapping.getNameMap) Map(java.util.Map) ExtensionMetadataTypeUtils.isMap(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isMap) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Collections.emptyMap(java.util.Collections.emptyMap)

Example 4 with BasicTypeMetadataVisitor

use of org.mule.metadata.api.visitor.BasicTypeMetadataVisitor in project mule by mulesoft.

the class ExtensionDefinitionParser method getValueResolverFromMetadataType.

private ValueResolver getValueResolverFromMetadataType(final String parameterName, MetadataType expectedType, final Object value, final Object defaultValue, final boolean acceptsReferences, final Class<?> expectedClass) {
    final Reference<ValueResolver> resolverValueHolder = new Reference<>();
    expectedType.accept(new BasicTypeMetadataVisitor() {

        @Override
        protected void visitBasicType(MetadataType metadataType) {
            if (conversionService.canConvert(value.getClass(), expectedClass)) {
                resolverValueHolder.set(new StaticValueResolver<>(convertSimpleValue(value, expectedClass, parameterName)));
            } else {
                defaultVisit(metadataType);
            }
        }

        @Override
        public void visitDateTime(DateTimeType dateTimeType) {
            resolverValueHolder.set(parseDate(value, dateTimeType, defaultValue));
        }

        @Override
        public void visitDate(DateType dateType) {
            resolverValueHolder.set(parseDate(value, dateType, defaultValue));
        }

        @Override
        public void visitObject(ObjectType objectType) {
            if (isMap(objectType)) {
                defaultVisit(objectType);
                return;
            }
            ValueResolver valueResolver;
            Optional<? extends ParsingDelegate> delegate = locateParsingDelegate(valueResolverParsingDelegates, objectType);
            Optional<DslElementSyntax> typeDsl = dslResolver.resolve(objectType);
            if (delegate.isPresent() && typeDsl.isPresent()) {
                valueResolver = (ValueResolver) delegate.get().parse(value.toString(), objectType, typeDsl.get());
            } else {
                valueResolver = acceptsReferences ? defaultValueResolverParsingDelegate.parse(value.toString(), objectType, null) : new StaticValueResolver<>(value);
            }
            resolverValueHolder.set(valueResolver);
        }

        @Override
        protected void defaultVisit(MetadataType metadataType) {
            ValueResolver delegateResolver = locateParsingDelegate(valueResolverParsingDelegates, metadataType).map(delegate -> delegate.parse(value.toString(), metadataType, null)).orElseGet(() -> acceptsReferences ? defaultValueResolverParsingDelegate.parse(value.toString(), metadataType, null) : new TypeSafeValueResolverWrapper(new StaticValueResolver<>(value), expectedClass));
            resolverValueHolder.set(delegateResolver);
        }
    });
    return resolverValueHolder.get();
}
Also used : SchedulingStrategyParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.SchedulingStrategyParsingDelegate) DefaultValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.DefaultValueResolverParsingDelegate) MediaTypeValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.MediaTypeValueResolverParsingDelegate) ParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.ParsingDelegate) DefaultObjectParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.DefaultObjectParsingDelegate) ObjectParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.ObjectParsingDelegate) CharsetValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.CharsetValueResolverParsingDelegate) ValueResolverParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.ValueResolverParsingDelegate) FixedTypeParsingDelegate(org.mule.runtime.module.extension.internal.config.dsl.object.FixedTypeParsingDelegate) Optional(java.util.Optional) Reference(org.mule.runtime.api.util.Reference) MetadataType(org.mule.metadata.api.model.MetadataType) BasicTypeMetadataVisitor(org.mule.metadata.api.visitor.BasicTypeMetadataVisitor) ObjectType(org.mule.metadata.api.model.ObjectType) DateTimeType(org.mule.metadata.api.model.DateTimeType) TypeSafeValueResolverWrapper(org.mule.runtime.module.extension.internal.runtime.resolver.TypeSafeValueResolverWrapper) ExpressionBasedParameterResolverValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ExpressionBasedParameterResolverValueResolver) StaticValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.StaticValueResolver) ExpressionTypedValueValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ExpressionTypedValueValueResolver) NativeQueryParameterValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.NativeQueryParameterValueResolver) ValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ValueResolver) ProcessorChainValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ProcessorChainValueResolver) TypeSafeExpressionValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.TypeSafeExpressionValueResolver) StaticLiteralValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.StaticLiteralValueResolver) StaticValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.StaticValueResolver) DateType(org.mule.metadata.api.model.DateType)

Example 5 with BasicTypeMetadataVisitor

use of org.mule.metadata.api.visitor.BasicTypeMetadataVisitor in project mule by mulesoft.

the class NullSafeModelValidator method validate.

@Override
public void validate(ExtensionModel extensionModel, ProblemsReporter problemsReporter) {
    ReflectionCache reflectionCache = new ReflectionCache();
    TypeLoader typeLoader = ExtensionsTypeLoaderFactory.getDefault().createTypeLoader();
    new ExtensionWalker() {

        @Override
        public void onParameter(ParameterizedModel owner, ParameterGroupModel groupModel, ParameterModel model) {
            model.getType().accept(new MetadataTypeVisitor() {

                @Override
                public void visitObject(ObjectType objectType) {
                    if (objectType.getMetadataFormat().equals(JAVA) && !isMap(objectType)) {
                        objectType.getAnnotation(TypeIdAnnotation.class).map(TypeIdAnnotation::getValue).ifPresent(typeId -> typeLoader.load(typeId).ifPresent(fieldMetadataType -> objectType.getFields().stream().filter(f -> f.getAnnotation(NullSafeTypeAnnotation.class).isPresent()).forEach(f -> validateField(getLocalPart(f), f, getType(fieldMetadataType), f.getAnnotation(NullSafeTypeAnnotation.class).get()))));
                    }
                }

                private void validateField(String fieldName, ObjectFieldType field, Class<?> declaringClass, NullSafeTypeAnnotation nullSafeTypeAnnotation) {
                    Class<?> nullSafeType = nullSafeTypeAnnotation.getType();
                    Class<?> fieldType = getType(field.getValue());
                    boolean hasDefaultOverride = nullSafeTypeAnnotation.hasDefaultOverride();
                    field.getValue().accept(new BasicTypeMetadataVisitor() {

                        @Override
                        protected void visitBasicType(MetadataType metadataType) {
                            problemsReporter.addError(new Problem(extensionModel, format("Field '%s' in class '%s' is annotated with '@%s' but is of type '%s'. That annotation can only be " + "used with complex types (Pojos, Lists, Maps)", fieldName, declaringClass.getName(), NullSafe.class.getSimpleName(), fieldType.getName())));
                        }

                        @Override
                        public void visitArrayType(ArrayType arrayType) {
                            if (hasDefaultOverride) {
                                problemsReporter.addError(new Problem(extensionModel, format("Field '%s' in class '%s' is annotated with '@%s' is of type '%s'" + " but a 'defaultImplementingType' was provided." + " Type override is not allowed for Collections", fieldName, declaringClass.getName(), NullSafe.class.getSimpleName(), fieldType.getName())));
                            }
                        }

                        @Override
                        public void visitObject(ObjectType objectType) {
                            String requiredFields = objectType.getFields().stream().filter(f -> f.isRequired() && !isFlattenedParameterGroup(f)).map(MetadataTypeUtils::getLocalPart).collect(joining(", "));
                            if (!isBlank(requiredFields) && isCompiletime(extensionModel)) {
                                problemsReporter.addError(new Problem(model, format("Class '%s' cannot be used with '@%s' parameter since it contains non optional fields: [%s]", getId(objectType).orElse(""), NullSafe.class.getSimpleName(), requiredFields)));
                            }
                            if (objectType.isOpen()) {
                                if (hasDefaultOverride) {
                                    problemsReporter.addError(new Problem(model, format("Field '%s' in class '%s' is annotated with '@%s' is of type '%s'" + " but a 'defaultImplementingType' was provided." + " Type override is not allowed for Maps", fieldName, declaringClass.getName(), NullSafe.class.getSimpleName(), fieldType.getName())));
                                }
                                return;
                            }
                            if (hasDefaultOverride && isInstantiable(fieldType, reflectionCache)) {
                                problemsReporter.addError(new Problem(model, format("Field '%s' in class '%s' is annotated with '@%s' is of concrete type '%s'," + " but a 'defaultImplementingType' was provided." + " Type override is not allowed for concrete types", fieldName, declaringClass.getName(), NullSafe.class.getSimpleName(), fieldType.getName())));
                            }
                            if (!isInstantiable(nullSafeType, reflectionCache)) {
                                problemsReporter.addError(new Problem(model, format("Field '%s' in class '%s' is annotated with '@%s' but is of type '%s'. That annotation can only be " + "used with complex instantiable types (Pojos, Lists, Maps)", fieldName, declaringClass.getName(), NullSafe.class.getSimpleName(), nullSafeType.getName())));
                            }
                            if (hasDefaultOverride && !fieldType.isAssignableFrom(nullSafeType)) {
                                problemsReporter.addError(new Problem(model, format("Field '%s' in class '%s' is annotated with '@%s' of type '%s', but provided type '%s" + " is not a subtype of the parameter's type", fieldName, declaringClass.getName(), NullSafe.class.getSimpleName(), fieldType.getName(), nullSafeType.getName())));
                            }
                        }
                    });
                }
            });
        }
    }.walk(extensionModel);
}
Also used : ExtensionMetadataTypeUtils.getId(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getId) ParameterModel(org.mule.runtime.api.meta.model.parameter.ParameterModel) ExtensionsTypeLoaderFactory(org.mule.runtime.extension.api.declaration.type.ExtensionsTypeLoaderFactory) JAVA(org.mule.metadata.api.model.MetadataFormat.JAVA) MetadataTypeUtils(org.mule.metadata.api.utils.MetadataTypeUtils) ExtensionMetadataTypeUtils.isFlattenedParameterGroup(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isFlattenedParameterGroup) ModelValidationUtils.isCompiletime(org.mule.runtime.module.extension.internal.loader.validation.ModelValidationUtils.isCompiletime) ArrayType(org.mule.metadata.api.model.ArrayType) BasicTypeMetadataVisitor(org.mule.metadata.api.visitor.BasicTypeMetadataVisitor) ParameterGroupModel(org.mule.runtime.api.meta.model.parameter.ParameterGroupModel) IntrospectionUtils.isInstantiable(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.isInstantiable) Problem(org.mule.runtime.extension.api.loader.Problem) MetadataTypeUtils.getLocalPart(org.mule.metadata.api.utils.MetadataTypeUtils.getLocalPart) TypeIdAnnotation(org.mule.metadata.api.annotation.TypeIdAnnotation) ExtensionModelValidator(org.mule.runtime.extension.api.loader.ExtensionModelValidator) ExtensionMetadataTypeUtils.isMap(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isMap) ObjectType(org.mule.metadata.api.model.ObjectType) ParameterizedModel(org.mule.runtime.api.meta.model.parameter.ParameterizedModel) ProblemsReporter(org.mule.runtime.extension.api.loader.ProblemsReporter) NullSafeTypeAnnotation(org.mule.runtime.extension.api.declaration.type.annotation.NullSafeTypeAnnotation) 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) TypeLoader(org.mule.metadata.api.TypeLoader) ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) ExtensionWalker(org.mule.runtime.api.meta.model.util.ExtensionWalker) NullSafe(org.mule.runtime.extension.api.annotation.param.NullSafe) MetadataType(org.mule.metadata.api.model.MetadataType) JavaTypeUtils.getType(org.mule.metadata.java.api.utils.JavaTypeUtils.getType) ReflectionCache(org.mule.runtime.module.extension.internal.util.ReflectionCache) ExtensionWalker(org.mule.runtime.api.meta.model.util.ExtensionWalker) MetadataType(org.mule.metadata.api.model.MetadataType) TypeLoader(org.mule.metadata.api.TypeLoader) NullSafeTypeAnnotation(org.mule.runtime.extension.api.declaration.type.annotation.NullSafeTypeAnnotation) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) MetadataTypeUtils(org.mule.metadata.api.utils.MetadataTypeUtils) BasicTypeMetadataVisitor(org.mule.metadata.api.visitor.BasicTypeMetadataVisitor) ArrayType(org.mule.metadata.api.model.ArrayType) ObjectType(org.mule.metadata.api.model.ObjectType) ParameterModel(org.mule.runtime.api.meta.model.parameter.ParameterModel) ParameterizedModel(org.mule.runtime.api.meta.model.parameter.ParameterizedModel) ParameterGroupModel(org.mule.runtime.api.meta.model.parameter.ParameterGroupModel) Problem(org.mule.runtime.extension.api.loader.Problem) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType)

Aggregations

MetadataType (org.mule.metadata.api.model.MetadataType)5 ObjectType (org.mule.metadata.api.model.ObjectType)5 BasicTypeMetadataVisitor (org.mule.metadata.api.visitor.BasicTypeMetadataVisitor)5 ArrayType (org.mule.metadata.api.model.ArrayType)4 JavaTypeUtils.getType (org.mule.metadata.java.api.utils.JavaTypeUtils.getType)4 String.format (java.lang.String.format)3 Optional (java.util.Optional)3 DateTimeType (org.mule.metadata.api.model.DateTimeType)3 DateType (org.mule.metadata.api.model.DateType)3 ObjectFieldType (org.mule.metadata.api.model.ObjectFieldType)3 MetadataTypeVisitor (org.mule.metadata.api.visitor.MetadataTypeVisitor)3 ImmutableList (com.google.common.collect.ImmutableList)2 Instant (java.time.Instant)2 ExtensionModel (org.mule.runtime.api.meta.model.ExtensionModel)2 ParameterGroupModel (org.mule.runtime.api.meta.model.parameter.ParameterGroupModel)2 ParameterModel (org.mule.runtime.api.meta.model.parameter.ParameterModel)2 ParameterizedModel (org.mule.runtime.api.meta.model.parameter.ParameterizedModel)2 Reference (org.mule.runtime.api.util.Reference)2 ExtensionsTypeLoaderFactory (org.mule.runtime.extension.api.declaration.type.ExtensionsTypeLoaderFactory)2 ExtensionMetadataTypeUtils.getId (org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getId)2