Search in sources :

Example 6 with MetadataTypeVisitor

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

the class IntrospectionUtils method toDataType.

/**
 * Transforms a {@link MetadataType} and generates the correspondent {@link DataType}
 *
 * @param metadataType to introspect a create a {@link DataType} from it.
 * @return a {@link DataType} based on the given {@link MetadataType}
 */
public static DataType toDataType(MetadataType metadataType) {
    Class<?> type = getType(metadataType).orElse(null);
    if (type == null) {
        return DataType.fromType(Object.class);
    }
    Reference<DataType> dataType = new Reference<>();
    metadataType.accept(new MetadataTypeVisitor() {

        @Override
        protected void defaultVisit(MetadataType metadataType) {
            dataType.set(DataType.fromType(type));
        }

        @Override
        public void visitArrayType(ArrayType arrayType) {
            Class itemClass = getType(arrayType.getType()).get();
            if (Collection.class.isAssignableFrom(type)) {
                dataType.set(DataType.builder().collectionType((Class<? extends Collection>) type).itemType(itemClass).build());
            } else if (Iterator.class.isAssignableFrom(type)) {
                dataType.set(DataType.builder().streamType((Class<? extends Iterator>) type).itemType(itemClass).build());
            } else {
                defaultVisit(arrayType);
            }
        }

        @Override
        public void visitObject(ObjectType objectType) {
            if (Map.class.isAssignableFrom(type)) {
                dataType.set(DataType.builder().mapType((Class<? extends Map>) type).keyType(String.class).valueType(objectType.getOpenRestriction().map(restriction -> {
                    if (restriction.getAnnotation(TypedValueTypeAnnotation.class).isPresent()) {
                        return TypedValue.class;
                    }
                    return getType(restriction).get();
                }).orElse(Object.class)).build());
            } else {
                defaultVisit(objectType);
            }
        }
    });
    return dataType.get();
}
Also used : FieldElement(org.mule.runtime.module.extension.api.loader.java.type.FieldElement) READ_ONLY(org.mule.runtime.module.extension.api.loader.java.type.PropertyElement.Accessibility.READ_ONLY) ParameterDeclaration(org.mule.runtime.api.meta.model.declaration.fluent.ParameterDeclaration) Message(org.mule.runtime.api.message.Message) Optional.of(java.util.Optional.of) RequireNameField(org.mule.runtime.module.extension.internal.loader.java.property.RequireNameField) ImplementingParameterModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ImplementingParameterModelProperty) TypeElement(javax.lang.model.element.TypeElement) ClassUtils(org.mule.runtime.core.api.util.ClassUtils) DeclaringMemberModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.DeclaringMemberModelProperty) ArrayUtils.isEmpty(org.apache.commons.lang3.ArrayUtils.isEmpty) Type(org.mule.runtime.module.extension.api.loader.java.type.Type) ArrayType(org.mule.metadata.api.model.ArrayType) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Objects.isNull(java.util.Objects.isNull) LiteralTypeAnnotation(org.mule.runtime.extension.api.declaration.type.annotation.LiteralTypeAnnotation) ClassTypeLoader(org.mule.metadata.api.ClassTypeLoader) ModelProperty(org.mule.runtime.api.meta.model.ModelProperty) Startable(org.mule.runtime.api.lifecycle.Startable) Collectors.toImmutableList(org.mule.runtime.api.util.collection.Collectors.toImmutableList) ObjectType(org.mule.metadata.api.model.ObjectType) ConnectionProvider(org.mule.runtime.api.connection.ConnectionProvider) Member(java.lang.reflect.Member) Set(java.util.Set) ParameterResolverTypeAnnotation(org.mule.runtime.extension.api.declaration.type.annotation.ParameterResolverTypeAnnotation) Element(javax.lang.model.element.Element) JavaTypeUtils.getId(org.mule.metadata.java.api.utils.JavaTypeUtils.getId) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) IntrospectionException(java.beans.IntrospectionException) BaseTypeBuilder.create(org.mule.metadata.api.builder.BaseTypeBuilder.create) IllegalConfigurationModelDefinitionException(org.mule.runtime.extension.api.exception.IllegalConfigurationModelDefinitionException) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) StringType(org.mule.metadata.api.model.StringType) ParameterResolver(org.mule.runtime.extension.api.runtime.parameter.ParameterResolver) Stream(java.util.stream.Stream) PropertyDescriptor(java.beans.PropertyDescriptor) MetadataType(org.mule.metadata.api.model.MetadataType) InjectedFieldModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.InjectedFieldModelProperty) Expression(org.mule.runtime.extension.api.annotation.Expression) AnnotatedElement(java.lang.reflect.AnnotatedElement) Optional.empty(java.util.Optional.empty) MetadataTypeUtils.isObjectType(org.mule.metadata.api.utils.MetadataTypeUtils.isObjectType) AnyType(org.mule.metadata.api.model.AnyType) ConnectionProviderModel(org.mule.runtime.api.meta.model.connection.ConnectionProviderModel) VariableElement(javax.lang.model.element.VariableElement) Preconditions.checkArgument(org.mule.runtime.api.util.Preconditions.checkArgument) Modifier.isStatic(java.lang.reflect.Modifier.isStatic) Supplier(java.util.function.Supplier) BaseTypeBuilder(org.mule.metadata.api.builder.BaseTypeBuilder) ArrayList(java.util.ArrayList) Introspector(java.beans.Introspector) DeclaredType(javax.lang.model.type.DeclaredType) ParameterGroup(org.mule.runtime.extension.api.annotation.param.ParameterGroup) LinkedHashSet(java.util.LinkedHashSet) Disposable(org.mule.runtime.api.lifecycle.Disposable) ParameterizedModel(org.mule.runtime.api.meta.model.parameter.ParameterizedModel) DataType(org.mule.runtime.api.metadata.DataType) Field(java.lang.reflect.Field) ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) TypedValue(org.mule.runtime.api.metadata.TypedValue) ExtensionMetadataTypeUtils.getType(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getType) Modifier.isPublic(java.lang.reflect.Modifier.isPublic) ParameterizedType(java.lang.reflect.ParameterizedType) Stoppable(org.mule.runtime.api.lifecycle.Stoppable) ExtensionWalker(org.mule.runtime.api.meta.model.util.ExtensionWalker) Reference(org.mule.runtime.api.util.Reference) RefName(org.mule.runtime.extension.api.annotation.param.RefName) CollectionUtils.isEmpty(org.apache.commons.collections.CollectionUtils.isEmpty) ReflectionUtils(org.reflections.ReflectionUtils) ReflectionUtils.getAllFields(org.reflections.ReflectionUtils.getAllFields) SubTypesModel(org.mule.runtime.api.meta.model.SubTypesModel) HasOutputModel(org.mule.runtime.api.meta.model.HasOutputModel) TargetModelProperty(org.mule.runtime.extension.internal.property.TargetModelProperty) NamedObject(org.mule.runtime.api.meta.NamedObject) Source(org.mule.runtime.extension.api.runtime.source.Source) VoidType(org.mule.metadata.api.model.VoidType) MetadataTypeUtils.isEnum(org.mule.metadata.api.utils.MetadataTypeUtils.isEnum) DefaultEncodingModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.DefaultEncodingModelProperty) ParameterGroupModel(org.mule.runtime.api.meta.model.parameter.ParameterGroupModel) SUPPORTED(org.mule.runtime.api.meta.ExpressionSupport.SUPPORTED) ResolvableType(org.springframework.core.ResolvableType) Pair(org.mule.runtime.api.util.Pair) Method(java.lang.reflect.Method) Collectors.toSet(java.util.stream.Collectors.toSet) Collections.reverse(java.util.Collections.reverse) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) ClassInformationAnnotation(org.mule.metadata.java.api.annotation.ClassInformationAnnotation) Types(javax.lang.model.util.Types) String.format(java.lang.String.format) List(java.util.List) Modifier(java.lang.reflect.Modifier) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) TypeVariable(javax.lang.model.type.TypeVariable) EnrichableModel(org.mule.runtime.api.meta.model.EnrichableModel) Arrays.stream(java.util.Arrays.stream) IllegalModelDefinitionException(org.mule.runtime.extension.api.exception.IllegalModelDefinitionException) MessageMetadataTypeBuilder(org.mule.metadata.message.api.MessageMetadataTypeBuilder) ParameterModel(org.mule.runtime.api.meta.model.parameter.ParameterModel) Alias(org.mule.runtime.extension.api.annotation.Alias) TypeGeneric(org.mule.runtime.module.extension.api.loader.java.type.TypeGeneric) ComponentModel(org.mule.runtime.api.meta.model.ComponentModel) JAVA(org.mule.metadata.api.model.MetadataFormat.JAVA) MetadataKeyId(org.mule.runtime.extension.api.annotation.metadata.MetadataKeyId) Ignore(org.mule.runtime.extension.api.annotation.Ignore) HashSet(java.util.HashSet) Collectors.toCollection(java.util.stream.Collectors.toCollection) MethodElement(org.mule.runtime.module.extension.api.loader.java.type.MethodElement) ImmutableList(com.google.common.collect.ImmutableList) Literal(org.mule.runtime.extension.api.runtime.parameter.Literal) ParameterGroupModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ParameterGroupModelProperty) LinkedList(java.util.LinkedList) Parameter(org.mule.runtime.extension.api.annotation.param.Parameter) TypedValueTypeAnnotation(org.mule.runtime.extension.api.declaration.type.annotation.TypedValueTypeAnnotation) AccessibleObject(java.lang.reflect.AccessibleObject) Iterator(java.util.Iterator) ElementKind(javax.lang.model.element.ElementKind) PUBLIC(javax.lang.model.element.Modifier.PUBLIC) ExpressionSupport(org.mule.runtime.api.meta.ExpressionSupport) ExecutableElement(javax.lang.model.element.ExecutableElement) READ_WRITE(org.mule.runtime.module.extension.api.loader.java.type.PropertyElement.Accessibility.READ_WRITE) Initialisable(org.mule.runtime.api.lifecycle.Initialisable) Result(org.mule.runtime.extension.api.runtime.operation.Result) DefaultEncoding(org.mule.runtime.extension.api.annotation.param.DefaultEncoding) Collectors.toList(java.util.stream.Collectors.toList) TypeMirror(javax.lang.model.type.TypeMirror) BaseDeclaration(org.mule.runtime.api.meta.model.declaration.fluent.BaseDeclaration) METHOD(javax.lang.model.element.ElementKind.METHOD) PagingProvider(org.mule.runtime.extension.api.runtime.streaming.PagingProvider) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) ComponentLocation(org.mule.runtime.api.component.location.ComponentLocation) MuleExtensionAnnotationParser(org.mule.runtime.module.extension.internal.loader.java.MuleExtensionAnnotationParser) ImplementingTypeModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ImplementingTypeModelProperty) Reference(org.mule.runtime.api.util.Reference) MetadataType(org.mule.metadata.api.model.MetadataType) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) ArrayType(org.mule.metadata.api.model.ArrayType) ObjectType(org.mule.metadata.api.model.ObjectType) MetadataTypeUtils.isObjectType(org.mule.metadata.api.utils.MetadataTypeUtils.isObjectType) Iterator(java.util.Iterator) DataType(org.mule.runtime.api.metadata.DataType) Collection(java.util.Collection) Collectors.toCollection(java.util.stream.Collectors.toCollection) Map(java.util.Map)

Example 7 with MetadataTypeVisitor

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

the class IntrospectionUtils method collectRelativeClassesAsString.

/**
 * Given a {@link MetadataType} it adds all the {@link Class} that are related from that type. This includes generics of an
 * {@link ArrayType}, open restriction of an {@link ObjectType} as well as its fields.
 *
 * @param type {@link MetadataType} to inspect
 * @return {@link Set<Class>>} with the classes reachable from the {@code type}
 */
public static Set<String> collectRelativeClassesAsString(MetadataType type) {
    Set<String> relativeClasses = new HashSet<>();
    type.accept(new MetadataTypeVisitor() {

        @Override
        public void visitArrayType(ArrayType arrayType) {
            arrayType.getType().accept(this);
        }

        @Override
        public void visitObjectField(ObjectFieldType objectFieldType) {
            objectFieldType.getValue().accept(this);
        }

        @Override
        public void visitObject(ObjectType objectType) {
            if (objectType.getMetadataFormat() != JAVA) {
                return;
            }
            final String clazz = getId(objectType).orElse(null);
            if (clazz == null || relativeClasses.contains(clazz)) {
                return;
            }
            Optional<ClassInformationAnnotation> classInformation = objectType.getAnnotation(ClassInformationAnnotation.class);
            classInformation.ifPresent(classInformationAnnotation -> relativeClasses.addAll(classInformationAnnotation.getGenericTypes()));
            relativeClasses.add(clazz);
            objectType.getFields().forEach(objectFieldType -> objectFieldType.accept(this));
            objectType.getOpenRestriction().ifPresent(t -> t.accept(this));
        }

        @Override
        public void visitString(StringType stringType) {
            if (stringType.getMetadataFormat() == JAVA && isEnum(stringType)) {
                getId(stringType).ifPresent(relativeClasses::add);
            }
        }
    });
    return relativeClasses;
}
Also used : ArrayType(org.mule.metadata.api.model.ArrayType) FieldElement(org.mule.runtime.module.extension.api.loader.java.type.FieldElement) READ_ONLY(org.mule.runtime.module.extension.api.loader.java.type.PropertyElement.Accessibility.READ_ONLY) ParameterDeclaration(org.mule.runtime.api.meta.model.declaration.fluent.ParameterDeclaration) Message(org.mule.runtime.api.message.Message) Optional.of(java.util.Optional.of) RequireNameField(org.mule.runtime.module.extension.internal.loader.java.property.RequireNameField) ImplementingParameterModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ImplementingParameterModelProperty) TypeElement(javax.lang.model.element.TypeElement) ClassUtils(org.mule.runtime.core.api.util.ClassUtils) DeclaringMemberModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.DeclaringMemberModelProperty) ArrayUtils.isEmpty(org.apache.commons.lang3.ArrayUtils.isEmpty) Type(org.mule.runtime.module.extension.api.loader.java.type.Type) ArrayType(org.mule.metadata.api.model.ArrayType) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Objects.isNull(java.util.Objects.isNull) LiteralTypeAnnotation(org.mule.runtime.extension.api.declaration.type.annotation.LiteralTypeAnnotation) ClassTypeLoader(org.mule.metadata.api.ClassTypeLoader) ModelProperty(org.mule.runtime.api.meta.model.ModelProperty) Startable(org.mule.runtime.api.lifecycle.Startable) Collectors.toImmutableList(org.mule.runtime.api.util.collection.Collectors.toImmutableList) ObjectType(org.mule.metadata.api.model.ObjectType) ConnectionProvider(org.mule.runtime.api.connection.ConnectionProvider) Member(java.lang.reflect.Member) Set(java.util.Set) ParameterResolverTypeAnnotation(org.mule.runtime.extension.api.declaration.type.annotation.ParameterResolverTypeAnnotation) Element(javax.lang.model.element.Element) JavaTypeUtils.getId(org.mule.metadata.java.api.utils.JavaTypeUtils.getId) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) IntrospectionException(java.beans.IntrospectionException) BaseTypeBuilder.create(org.mule.metadata.api.builder.BaseTypeBuilder.create) IllegalConfigurationModelDefinitionException(org.mule.runtime.extension.api.exception.IllegalConfigurationModelDefinitionException) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) StringType(org.mule.metadata.api.model.StringType) ParameterResolver(org.mule.runtime.extension.api.runtime.parameter.ParameterResolver) Stream(java.util.stream.Stream) PropertyDescriptor(java.beans.PropertyDescriptor) MetadataType(org.mule.metadata.api.model.MetadataType) InjectedFieldModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.InjectedFieldModelProperty) Expression(org.mule.runtime.extension.api.annotation.Expression) AnnotatedElement(java.lang.reflect.AnnotatedElement) Optional.empty(java.util.Optional.empty) MetadataTypeUtils.isObjectType(org.mule.metadata.api.utils.MetadataTypeUtils.isObjectType) AnyType(org.mule.metadata.api.model.AnyType) ConnectionProviderModel(org.mule.runtime.api.meta.model.connection.ConnectionProviderModel) VariableElement(javax.lang.model.element.VariableElement) Preconditions.checkArgument(org.mule.runtime.api.util.Preconditions.checkArgument) Modifier.isStatic(java.lang.reflect.Modifier.isStatic) Supplier(java.util.function.Supplier) BaseTypeBuilder(org.mule.metadata.api.builder.BaseTypeBuilder) ArrayList(java.util.ArrayList) Introspector(java.beans.Introspector) DeclaredType(javax.lang.model.type.DeclaredType) ParameterGroup(org.mule.runtime.extension.api.annotation.param.ParameterGroup) LinkedHashSet(java.util.LinkedHashSet) Disposable(org.mule.runtime.api.lifecycle.Disposable) ParameterizedModel(org.mule.runtime.api.meta.model.parameter.ParameterizedModel) DataType(org.mule.runtime.api.metadata.DataType) Field(java.lang.reflect.Field) ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) TypedValue(org.mule.runtime.api.metadata.TypedValue) ExtensionMetadataTypeUtils.getType(org.mule.runtime.extension.api.util.ExtensionMetadataTypeUtils.getType) Modifier.isPublic(java.lang.reflect.Modifier.isPublic) ParameterizedType(java.lang.reflect.ParameterizedType) Stoppable(org.mule.runtime.api.lifecycle.Stoppable) ExtensionWalker(org.mule.runtime.api.meta.model.util.ExtensionWalker) Reference(org.mule.runtime.api.util.Reference) RefName(org.mule.runtime.extension.api.annotation.param.RefName) CollectionUtils.isEmpty(org.apache.commons.collections.CollectionUtils.isEmpty) ReflectionUtils(org.reflections.ReflectionUtils) ReflectionUtils.getAllFields(org.reflections.ReflectionUtils.getAllFields) SubTypesModel(org.mule.runtime.api.meta.model.SubTypesModel) HasOutputModel(org.mule.runtime.api.meta.model.HasOutputModel) TargetModelProperty(org.mule.runtime.extension.internal.property.TargetModelProperty) NamedObject(org.mule.runtime.api.meta.NamedObject) Source(org.mule.runtime.extension.api.runtime.source.Source) VoidType(org.mule.metadata.api.model.VoidType) MetadataTypeUtils.isEnum(org.mule.metadata.api.utils.MetadataTypeUtils.isEnum) DefaultEncodingModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.DefaultEncodingModelProperty) ParameterGroupModel(org.mule.runtime.api.meta.model.parameter.ParameterGroupModel) SUPPORTED(org.mule.runtime.api.meta.ExpressionSupport.SUPPORTED) ResolvableType(org.springframework.core.ResolvableType) Pair(org.mule.runtime.api.util.Pair) Method(java.lang.reflect.Method) Collectors.toSet(java.util.stream.Collectors.toSet) Collections.reverse(java.util.Collections.reverse) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) ClassInformationAnnotation(org.mule.metadata.java.api.annotation.ClassInformationAnnotation) Types(javax.lang.model.util.Types) String.format(java.lang.String.format) List(java.util.List) Modifier(java.lang.reflect.Modifier) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) TypeVariable(javax.lang.model.type.TypeVariable) EnrichableModel(org.mule.runtime.api.meta.model.EnrichableModel) Arrays.stream(java.util.Arrays.stream) IllegalModelDefinitionException(org.mule.runtime.extension.api.exception.IllegalModelDefinitionException) MessageMetadataTypeBuilder(org.mule.metadata.message.api.MessageMetadataTypeBuilder) ParameterModel(org.mule.runtime.api.meta.model.parameter.ParameterModel) Alias(org.mule.runtime.extension.api.annotation.Alias) TypeGeneric(org.mule.runtime.module.extension.api.loader.java.type.TypeGeneric) ComponentModel(org.mule.runtime.api.meta.model.ComponentModel) JAVA(org.mule.metadata.api.model.MetadataFormat.JAVA) MetadataKeyId(org.mule.runtime.extension.api.annotation.metadata.MetadataKeyId) Ignore(org.mule.runtime.extension.api.annotation.Ignore) HashSet(java.util.HashSet) Collectors.toCollection(java.util.stream.Collectors.toCollection) MethodElement(org.mule.runtime.module.extension.api.loader.java.type.MethodElement) ImmutableList(com.google.common.collect.ImmutableList) Literal(org.mule.runtime.extension.api.runtime.parameter.Literal) ParameterGroupModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ParameterGroupModelProperty) LinkedList(java.util.LinkedList) Parameter(org.mule.runtime.extension.api.annotation.param.Parameter) TypedValueTypeAnnotation(org.mule.runtime.extension.api.declaration.type.annotation.TypedValueTypeAnnotation) AccessibleObject(java.lang.reflect.AccessibleObject) Iterator(java.util.Iterator) ElementKind(javax.lang.model.element.ElementKind) PUBLIC(javax.lang.model.element.Modifier.PUBLIC) ExpressionSupport(org.mule.runtime.api.meta.ExpressionSupport) ExecutableElement(javax.lang.model.element.ExecutableElement) READ_WRITE(org.mule.runtime.module.extension.api.loader.java.type.PropertyElement.Accessibility.READ_WRITE) Initialisable(org.mule.runtime.api.lifecycle.Initialisable) Result(org.mule.runtime.extension.api.runtime.operation.Result) DefaultEncoding(org.mule.runtime.extension.api.annotation.param.DefaultEncoding) Collectors.toList(java.util.stream.Collectors.toList) TypeMirror(javax.lang.model.type.TypeMirror) BaseDeclaration(org.mule.runtime.api.meta.model.declaration.fluent.BaseDeclaration) METHOD(javax.lang.model.element.ElementKind.METHOD) PagingProvider(org.mule.runtime.extension.api.runtime.streaming.PagingProvider) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) ComponentLocation(org.mule.runtime.api.component.location.ComponentLocation) MuleExtensionAnnotationParser(org.mule.runtime.module.extension.internal.loader.java.MuleExtensionAnnotationParser) ImplementingTypeModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ImplementingTypeModelProperty) ObjectType(org.mule.metadata.api.model.ObjectType) MetadataTypeUtils.isObjectType(org.mule.metadata.api.utils.MetadataTypeUtils.isObjectType) Optional(java.util.Optional) StringType(org.mule.metadata.api.model.StringType) ObjectFieldType(org.mule.metadata.api.model.ObjectFieldType) MetadataTypeVisitor(org.mule.metadata.api.visitor.MetadataTypeVisitor) ClassInformationAnnotation(org.mule.metadata.java.api.annotation.ClassInformationAnnotation) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 8 with MetadataTypeVisitor

use of org.mule.metadata.api.visitor.MetadataTypeVisitor 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 9 with MetadataTypeVisitor

use of org.mule.metadata.api.visitor.MetadataTypeVisitor 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 10 with MetadataTypeVisitor

use of org.mule.metadata.api.visitor.MetadataTypeVisitor 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

MetadataTypeVisitor (org.mule.metadata.api.visitor.MetadataTypeVisitor)19 MetadataType (org.mule.metadata.api.model.MetadataType)17 ObjectType (org.mule.metadata.api.model.ObjectType)17 ArrayType (org.mule.metadata.api.model.ArrayType)14 Optional (java.util.Optional)13 ExtensionModel (org.mule.runtime.api.meta.model.ExtensionModel)11 String.format (java.lang.String.format)10 List (java.util.List)10 Set (java.util.Set)10 ParameterGroupModel (org.mule.runtime.api.meta.model.parameter.ParameterGroupModel)10 ParameterModel (org.mule.runtime.api.meta.model.parameter.ParameterModel)10 ObjectFieldType (org.mule.metadata.api.model.ObjectFieldType)9 ParameterizedModel (org.mule.runtime.api.meta.model.parameter.ParameterizedModel)9 Reference (org.mule.runtime.api.util.Reference)9 HashSet (java.util.HashSet)8 StringType (org.mule.metadata.api.model.StringType)8 ImmutableList (com.google.common.collect.ImmutableList)7 Collection (java.util.Collection)7 Map (java.util.Map)7 Collectors.toList (java.util.stream.Collectors.toList)7