Search in sources :

Example 11 with ArrayType

use of org.mule.metadata.api.model.ArrayType 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 12 with ArrayType

use of org.mule.metadata.api.model.ArrayType in project mule by mulesoft.

the class IntrospectionUtilsTestCase method listWithNoGenerics.

@Test
public void listWithNoGenerics() throws Exception {
    MetadataType returnType = IntrospectionUtils.getMethodReturnType(getMethod("listNoGenerics"));
    assertThat(returnType, instanceOf(ArrayType.class));
    assertThat(((ArrayType) returnType).getType(), instanceOf(ObjectType.class));
}
Also used : ArrayType(org.mule.metadata.api.model.ArrayType) ObjectType(org.mule.metadata.api.model.ObjectType) IntrospectionUtils.getFieldMetadataType(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getFieldMetadataType) MetadataType(org.mule.metadata.api.model.MetadataType) MessageMetadataType(org.mule.metadata.message.api.MessageMetadataType) SmallTest(org.mule.tck.size.SmallTest) Test(org.junit.Test)

Example 13 with ArrayType

use of org.mule.metadata.api.model.ArrayType in project mule by mulesoft.

the class ConfigurationBasedElementModelFactory method getComponentChildVisitor.

private MetadataTypeVisitor getComponentChildVisitor(final DslElementModel.Builder typeBuilder, final ComponentConfiguration configuration, final MetadataType model, final String name, final DslElementSyntax modelDsl, final Optional<String> defaultValue, Deque<String> typeResolvingStack) {
    final Map<String, String> parameters = configuration.getParameters();
    return new MetadataTypeVisitor() {

        @Override
        protected void defaultVisit(MetadataType metadataType) {
            DslElementModel.Builder<MetadataType> elementBuilder = DslElementModel.<MetadataType>builder().withModel(model).withDsl(modelDsl);
            Optional<ComponentIdentifier> identifier = getIdentifier(modelDsl);
            String value = parameters.get(name);
            if (isBlank(value)) {
                if (identifier.isPresent()) {
                    ComponentConfiguration nested = getSingleComponentConfiguration(getNestedComponents(configuration), identifier);
                    if (nested != null && nested.getValue().isPresent() && !isBlank(nested.getValue().get())) {
                        value = nested.getValue().get().trim();
                    }
                } else if (defaultValue.isPresent()) {
                    value = defaultValue.get();
                    elementBuilder.isExplicitInDsl(false);
                }
            }
            if (!isBlank(value)) {
                typeBuilder.containing(elementBuilder.withValue(value).build());
            }
        }

        @Override
        public void visitArrayType(ArrayType arrayType) {
            Optional<ComponentIdentifier> identifier = getIdentifier(modelDsl);
            if (identifier.isPresent()) {
                ComponentConfiguration fieldComponent = getSingleComponentConfiguration(getNestedComponents(configuration), identifier);
                if (fieldComponent != null) {
                    DslElementModel.Builder<Object> list = DslElementModel.builder().withModel(model).withDsl(modelDsl).withConfig(fieldComponent);
                    modelDsl.getGeneric(arrayType.getType()).ifPresent(itemdsl -> {
                        ComponentIdentifier itemIdentifier = getIdentifier(itemdsl).get();
                        fieldComponent.getNestedComponents().forEach(c -> {
                            if (c.getIdentifier().equals(itemIdentifier)) {
                                getComponentChildVisitor(list, c, arrayType.getType(), VALUE_ATTRIBUTE_NAME, itemdsl, defaultValue, typeResolvingStack);
                            }
                        });
                    });
                    typeBuilder.containing(list.build());
                    return;
                }
            }
            defaultValue.ifPresent(s -> typeBuilder.containing(DslElementModel.builder().withModel(model).withDsl(modelDsl).withValue(defaultValue.get()).isExplicitInDsl(false).build()));
        }

        @Override
        public void visitObject(ObjectType objectType) {
            Optional<ComponentIdentifier> identifier = getIdentifier(modelDsl);
            if (identifier.isPresent()) {
                if (isMap(objectType)) {
                    typeBuilder.containing(createMapElement(objectType, modelDsl, configuration));
                    return;
                }
                Multimap<ComponentIdentifier, ComponentConfiguration> nestedComponents = getNestedComponents(configuration);
                ComponentConfiguration fieldComponent = nestedComponents.containsKey(identifier.get()) ? nestedComponents.get(identifier.get()).iterator().next() : null;
                fieldComponent = fieldComponent == null ? configuration : fieldComponent;
                String value = fieldComponent.getParameters().get(modelDsl.getAttributeName());
                if (!isBlank(value)) {
                    typeBuilder.containing(DslElementModel.builder().withModel(model).withDsl(modelDsl).withValue(value).build());
                } else {
                    resolveBasedOnType(objectType, fieldComponent, typeResolvingStack).ifPresent(typeBuilder::containing);
                }
                return;
            }
            defaultValue.ifPresent(s -> typeBuilder.containing(DslElementModel.builder().withModel(model).withDsl(modelDsl).withValue(defaultValue.get()).isExplicitInDsl(false).build()));
        }
    };
}
Also used : MetadataType(org.mule.metadata.api.model.MetadataType) ComponentIdentifier(org.mule.runtime.api.component.ComponentIdentifier) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) InternalComponentConfiguration(org.mule.runtime.dsl.internal.component.config.InternalComponentConfiguration) ComponentConfiguration(org.mule.runtime.dsl.api.component.config.ComponentConfiguration) ArrayType(org.mule.metadata.api.model.ArrayType) ObjectType(org.mule.metadata.api.model.ObjectType) DslElementModel(org.mule.runtime.config.api.dsl.model.DslElementModel)

Example 14 with ArrayType

use of org.mule.metadata.api.model.ArrayType in project mule by mulesoft.

the class DeclarationBasedElementModelFactory method createMapParameter.

private void createMapParameter(ParameterObjectValue objectValue, DslElementSyntax paramDsl, Object model, ObjectType mapType, InternalComponentConfiguration.Builder parentConfig, DslElementModel.Builder parentElement) {
    InternalComponentConfiguration.Builder mapConfig = InternalComponentConfiguration.builder().withIdentifier(asIdentifier(paramDsl));
    DslElementModel.Builder mapElement = DslElementModel.builder().withModel(model).withDsl(paramDsl);
    MetadataType valueType = mapType.getOpenRestriction().get();
    paramDsl.getGeneric(valueType).ifPresent(entryDsl -> objectValue.getParameters().forEach((key, value) -> {
        InternalComponentConfiguration.Builder entryConfigBuilder = InternalComponentConfiguration.builder().withIdentifier(asIdentifier(entryDsl));
        DslElementModel.Builder<MetadataType> entryElement = DslElementModel.<MetadataType>builder().withModel(valueType).withDsl(entryDsl);
        entryDsl.getAttribute(KEY_ATTRIBUTE_NAME).ifPresent(keyDsl -> {
            entryConfigBuilder.withParameter(KEY_ATTRIBUTE_NAME, key);
            entryElement.containing(DslElementModel.builder().withModel(typeLoader.load(String.class)).withDsl(keyDsl).withValue(key).build());
        });
        entryDsl.getAttribute(VALUE_ATTRIBUTE_NAME).ifPresent(valueDsl -> value.accept(new ParameterValueVisitor() {

            @Override
            public void visitSimpleValue(ParameterSimpleValue text) {
                entryConfigBuilder.withParameter(VALUE_ATTRIBUTE_NAME, text.getValue());
                entryElement.containing(DslElementModel.builder().withModel(valueType).withDsl(valueDsl).withValue(text.getValue()).build());
            }

            @Override
            public void visitListValue(ParameterListValue list) {
                createList(list, valueDsl, valueType, (ArrayType) valueType, entryConfigBuilder, entryElement);
            }

            @Override
            public void visitObjectValue(ParameterObjectValue objectValue) {
                if (isMap(valueType)) {
                    createMapParameter(objectValue, valueDsl, valueType, (ObjectType) valueType, entryConfigBuilder, entryElement);
                } else {
                    createObject(objectValue, valueDsl, valueType, (ObjectType) valueType, entryConfigBuilder, entryElement);
                }
            }
        }));
        ComponentConfiguration entryConfig = entryConfigBuilder.build();
        mapConfig.withNestedComponent(entryConfig);
        mapElement.containing(entryElement.withConfig(entryConfig).build());
    }));
    ComponentConfiguration result = mapConfig.build();
    parentConfig.withNestedComponent(result);
    parentElement.containing(mapElement.withConfig(result).build());
}
Also used : ExtensionMetadataTypeUtils.getId(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getId) OperationModel(org.mule.runtime.api.meta.model.operation.OperationModel) NamedObject(org.mule.runtime.api.meta.NamedObject) LoggerFactory(org.slf4j.LoggerFactory) ParameterizedElementDeclaration(org.mule.runtime.app.declaration.api.ParameterizedElementDeclaration) ComposableModel(org.mule.runtime.api.meta.model.ComposableModel) SourceModel(org.mule.runtime.api.meta.model.source.SourceModel) ArrayType(org.mule.metadata.api.model.ArrayType) KEY_ATTRIBUTE_NAME(org.mule.runtime.internal.dsl.DslConstants.KEY_ATTRIBUTE_NAME) Map(java.util.Map) DslResolvingContext(org.mule.runtime.api.dsl.DslResolvingContext) ParameterSimpleValue(org.mule.runtime.app.declaration.api.fluent.ParameterSimpleValue) ParameterGroupModel(org.mule.runtime.api.meta.model.parameter.ParameterGroupModel) ParameterValueVisitor(org.mule.runtime.app.declaration.api.ParameterValueVisitor) ClassTypeLoader(org.mule.metadata.api.ClassTypeLoader) ConstructModel(org.mule.runtime.api.meta.model.construct.ConstructModel) DslElementModelFactory(org.mule.runtime.config.api.dsl.model.DslElementModelFactory) ParameterElementDeclaration(org.mule.runtime.app.declaration.api.ParameterElementDeclaration) ExtensionModelUtils.isContent(org.mule.runtime.extension.api.util.ExtensionModelUtils.isContent) ExtensionMetadataTypeUtils.isMap(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isMap) ObjectType(org.mule.metadata.api.model.ObjectType) ElementDeclarer.newObjectValue(org.mule.runtime.app.declaration.api.fluent.ElementDeclarer.newObjectValue) InternalComponentConfiguration(org.mule.runtime.dsl.internal.component.config.InternalComponentConfiguration) String.format(java.lang.String.format) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) NAME_ATTRIBUTE_NAME(org.mule.runtime.internal.dsl.DslConstants.NAME_ATTRIBUTE_NAME) NestedRouteModel(org.mule.runtime.api.meta.model.nested.NestedRouteModel) List(java.util.List) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) ConstructElementDeclaration(org.mule.runtime.app.declaration.api.ConstructElementDeclaration) HasOperationModels(org.mule.runtime.api.meta.model.operation.HasOperationModels) DslElementSyntax(org.mule.runtime.extension.api.dsl.syntax.DslElementSyntax) ElementDeclaration(org.mule.runtime.app.declaration.api.ElementDeclaration) LayoutModel(org.mule.runtime.api.meta.model.display.LayoutModel) ConfigurationElementDeclaration(org.mule.runtime.app.declaration.api.ConfigurationElementDeclaration) ExtensionModelUtils.isInfrastructure(org.mule.runtime.extension.api.util.ExtensionModelUtils.isInfrastructure) MetadataType(org.mule.metadata.api.model.MetadataType) DslSyntaxResolver(org.mule.runtime.extension.api.dsl.syntax.resolver.DslSyntaxResolver) Optional(java.util.Optional) ComponentIdentifier.builder(org.mule.runtime.api.component.ComponentIdentifier.builder) ReferableElementDeclaration(org.mule.runtime.app.declaration.api.ReferableElementDeclaration) ExtensionMetadataTypeUtils.getAlias(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getAlias) ExtensionModelUtils.isRequired(org.mule.runtime.extension.api.util.ExtensionModelUtils.isRequired) Optional.empty(java.util.Optional.empty) ParameterModel(org.mule.runtime.api.meta.model.parameter.ParameterModel) SourceElementDeclaration(org.mule.runtime.app.declaration.api.SourceElementDeclaration) CONFIG_ATTRIBUTE_NAME(org.mule.runtime.internal.dsl.DslConstants.CONFIG_ATTRIBUTE_NAME) ConnectionProviderModel(org.mule.runtime.api.meta.model.connection.ConnectionProviderModel) HasConstructModels(org.mule.runtime.api.meta.model.construct.HasConstructModels) ComponentModel(org.mule.runtime.api.meta.model.ComponentModel) ExtensionsTypeLoaderFactory(org.mule.runtime.extension.api.declaration.type.ExtensionsTypeLoaderFactory) RouteElementDeclaration(org.mule.runtime.app.declaration.api.RouteElementDeclaration) Preconditions.checkArgument(org.mule.runtime.api.util.Preconditions.checkArgument) VALUE_ATTRIBUTE_NAME(org.mule.runtime.internal.dsl.DslConstants.VALUE_ATTRIBUTE_NAME) ComponentConfiguration(org.mule.runtime.dsl.api.component.config.ComponentConfiguration) Function(java.util.function.Function) ExtensionMetadataTypeUtils.isFlattenedParameterGroup(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isFlattenedParameterGroup) ParameterListValue(org.mule.runtime.app.declaration.api.fluent.ParameterListValue) DslElementSyntaxBuilder(org.mule.runtime.extension.api.dsl.syntax.DslElementSyntaxBuilder) ExtensionModelUtils.getDefaultValue(org.mule.runtime.extension.api.util.ExtensionModelUtils.getDefaultValue) ParameterObjectValue(org.mule.runtime.app.declaration.api.fluent.ParameterObjectValue) Stream.concat(java.util.stream.Stream.concat) ParameterizedModel(org.mule.runtime.api.meta.model.parameter.ParameterizedModel) Logger(org.slf4j.Logger) ParameterValue(org.mule.runtime.app.declaration.api.ParameterValue) Stream.of(java.util.stream.Stream.of) ConfigurationModel(org.mule.runtime.api.meta.model.config.ConfigurationModel) ConnectionElementDeclaration(org.mule.runtime.app.declaration.api.ConnectionElementDeclaration) ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) DslElementModel(org.mule.runtime.config.api.dsl.model.DslElementModel) Collectors.toList(java.util.stream.Collectors.toList) TopLevelParameterDeclaration(org.mule.runtime.app.declaration.api.TopLevelParameterDeclaration) ExtensionWalker(org.mule.runtime.api.meta.model.util.ExtensionWalker) Reference(org.mule.runtime.api.util.Reference) OperationElementDeclaration(org.mule.runtime.app.declaration.api.OperationElementDeclaration) IS_CDATA(org.mule.runtime.config.internal.dsl.processor.xml.XmlCustomAttributeHandler.IS_CDATA) ComponentElementDeclaration(org.mule.runtime.app.declaration.api.ComponentElementDeclaration) ComponentIdentifier(org.mule.runtime.api.component.ComponentIdentifier) ParameterGroupElementDeclaration(org.mule.runtime.app.declaration.api.ParameterGroupElementDeclaration) HasSourceModels(org.mule.runtime.api.meta.model.source.HasSourceModels) ParameterValueVisitor(org.mule.runtime.app.declaration.api.ParameterValueVisitor) ParameterListValue(org.mule.runtime.app.declaration.api.fluent.ParameterListValue) DslElementSyntaxBuilder(org.mule.runtime.extension.api.dsl.syntax.DslElementSyntaxBuilder) MetadataType(org.mule.metadata.api.model.MetadataType) ParameterSimpleValue(org.mule.runtime.app.declaration.api.fluent.ParameterSimpleValue) InternalComponentConfiguration(org.mule.runtime.dsl.internal.component.config.InternalComponentConfiguration) ArrayType(org.mule.metadata.api.model.ArrayType) InternalComponentConfiguration(org.mule.runtime.dsl.internal.component.config.InternalComponentConfiguration) ComponentConfiguration(org.mule.runtime.dsl.api.component.config.ComponentConfiguration) ObjectType(org.mule.metadata.api.model.ObjectType) ParameterObjectValue(org.mule.runtime.app.declaration.api.fluent.ParameterObjectValue) DslElementModel(org.mule.runtime.config.api.dsl.model.DslElementModel)

Example 15 with ArrayType

use of org.mule.metadata.api.model.ArrayType in project mule by mulesoft.

the class MapSchemaDelegate method generateMapComplexType.

private LocalComplexType generateMapComplexType(DslElementSyntax mapDsl, final ObjectType metadataType) {
    final MetadataType valueType = metadataType.getOpenRestriction().get();
    final LocalComplexType entryComplexType = new LocalComplexType();
    final Attribute keyAttribute = builder.createAttribute(KEY_ATTRIBUTE_NAME, keyType, true, REQUIRED);
    entryComplexType.getAttributeOrAttributeGroup().add(keyAttribute);
    final LocalComplexType mapComplexType = new LocalComplexType();
    final ExplicitGroup mapEntrySequence = new ExplicitGroup();
    mapComplexType.setSequence(mapEntrySequence);
    DslElementSyntax entryValueDsl = mapDsl.getGeneric(valueType).orElseThrow(() -> new IllegalArgumentException("Illegal DslSyntax definition of the given DictionaryType. The DslElementSyntax for the entry is required"));
    final TopLevelElement mapEntryElement = new TopLevelElement();
    mapEntryElement.setName(entryValueDsl.getElementName());
    mapEntryElement.setMinOccurs(ZERO);
    mapEntryElement.setMaxOccurs(UNBOUNDED);
    valueType.accept(new MetadataTypeVisitor() {

        /**
         * For a Map with an {@link ObjectType} as value. The resulting {@link ComplexType} declares a sequence of either a
         * {@code ref} or a {@code choice}.
         * <p/>
         * It creates an element {@code ref} to the concrete element whose {@code type} is the {@link ComplexType} associated to the
         * {@code objectType}
         * <p/>
         * In the case of having a {@link DslElementSyntax#isWrapped wrapped} {@link ObjectType}, then a {@link ExplicitGroup
         * Choice} group that can receive a {@code ref} to any subtype that this wrapped type might have, be it either a top-level
         * element for the mule schema, or if it can only be declared as child of this element.
         *
         * If the map's value is another map, then a value attribute is created for the value map.
         *
         * @param objectType the item's type
         */
        @Override
        public void visitObject(ObjectType objectType) {
            Optional<DslElementSyntax> containedElement = entryValueDsl.getContainedElement(VALUE_ATTRIBUTE_NAME);
            if (isMap(objectType) || !containedElement.isPresent()) {
                defaultVisit(objectType);
                return;
            }
            final boolean shouldGenerateChildElement = containedElement.get().supportsChildDeclaration() || containedElement.get().isWrapped();
            entryComplexType.getAttributeOrAttributeGroup().add(builder.createAttribute(VALUE_ATTRIBUTE_NAME, valueType, !shouldGenerateChildElement, SUPPORTED));
            if (shouldGenerateChildElement) {
                DslElementSyntax typeDsl = builder.getDslResolver().resolve(objectType).orElseThrow(() -> new IllegalArgumentException(format("The given type [%s] cannot be represented as a child element in Map entries", getId(objectType))));
                if (typeDsl.isWrapped()) {
                    ExplicitGroup choice = builder.createTypeRefChoiceLocalOrGlobal(typeDsl, objectType, ZERO, UNBOUNDED);
                    entryComplexType.setChoice(choice);
                } else {
                    ExplicitGroup singleItemSequence = new ExplicitGroup();
                    singleItemSequence.setMaxOccurs("1");
                    TopLevelElement mapItemElement = builder.createTypeRef(typeDsl, objectType, false);
                    singleItemSequence.getParticle().add(objectFactory.createElement(mapItemElement));
                    entryComplexType.setSequence(singleItemSequence);
                }
            }
        }

        @Override
        public void visitArrayType(ArrayType arrayType) {
            entryComplexType.getAttributeOrAttributeGroup().add(builder.createAttribute(VALUE_ATTRIBUTE_NAME, valueType, false, SUPPORTED));
            entryComplexType.setSequence(new ExplicitGroup());
            LocalComplexType itemComplexType = new LocalComplexType();
            MetadataType itemType = arrayType.getType();
            itemComplexType.getAttributeOrAttributeGroup().add(builder.createAttribute(VALUE_ATTRIBUTE_NAME, itemType, true, REQUIRED));
            DslElementSyntax itemDsl = entryValueDsl.getGeneric(itemType).orElseThrow(() -> new IllegalArgumentException("Illegal DslSyntax definition of the given ArrayType. The DslElementSyntax for the item is required"));
            TopLevelElement itemElement = builder.createTopLevelElement(itemDsl.getElementName(), ZERO, UNBOUNDED, itemComplexType);
            entryComplexType.getSequence().getParticle().add(objectFactory.createElement(itemElement));
        }

        @Override
        protected void defaultVisit(MetadataType metadataType) {
            entryComplexType.getAttributeOrAttributeGroup().add(builder.createValueAttribute(valueType));
        }
    });
    mapEntryElement.setComplexType(entryComplexType);
    mapEntrySequence.getParticle().add(objectFactory.createElement(mapEntryElement));
    return mapComplexType;
}
Also used : ArrayType(org.mule.metadata.api.model.ArrayType) ObjectType(org.mule.metadata.api.model.ObjectType) Optional(java.util.Optional) Attribute(org.mule.runtime.module.extension.internal.capability.xml.schema.model.Attribute) TopLevelElement(org.mule.runtime.module.extension.internal.capability.xml.schema.model.TopLevelElement) DslElementSyntax(org.mule.runtime.extension.api.dsl.syntax.DslElementSyntax) MetadataType(org.mule.metadata.api.model.MetadataType) LocalComplexType(org.mule.runtime.module.extension.internal.capability.xml.schema.model.LocalComplexType) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) ExplicitGroup(org.mule.runtime.module.extension.internal.capability.xml.schema.model.ExplicitGroup)

Aggregations

ArrayType (org.mule.metadata.api.model.ArrayType)26 MetadataType (org.mule.metadata.api.model.MetadataType)25 ObjectType (org.mule.metadata.api.model.ObjectType)20 MetadataTypeVisitor (org.mule.metadata.api.visitor.MetadataTypeVisitor)17 Optional (java.util.Optional)14 ObjectFieldType (org.mule.metadata.api.model.ObjectFieldType)13 ExtensionModel (org.mule.runtime.api.meta.model.ExtensionModel)13 String.format (java.lang.String.format)12 List (java.util.List)12 ParameterGroupModel (org.mule.runtime.api.meta.model.parameter.ParameterGroupModel)12 ParameterModel (org.mule.runtime.api.meta.model.parameter.ParameterModel)12 Reference (org.mule.runtime.api.util.Reference)12 Map (java.util.Map)11 ParameterizedModel (org.mule.runtime.api.meta.model.parameter.ParameterizedModel)11 Set (java.util.Set)10 Collectors.toList (java.util.stream.Collectors.toList)10 ClassTypeLoader (org.mule.metadata.api.ClassTypeLoader)10 StringType (org.mule.metadata.api.model.StringType)9 DslElementSyntax (org.mule.runtime.extension.api.dsl.syntax.DslElementSyntax)9 ExtensionMetadataTypeUtils.isMap (org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.isMap)9