Search in sources :

Example 1 with DefaultObjectBuilder

use of org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder in project mule by mulesoft.

the class TopLevelParameterObjectFactory method doGetObject.

@Override
public Object doGetObject() throws Exception {
    return withContextClassLoader(classLoader, () -> {
        // TODO MULE-10919 - This logic is similar to that of the resolverset object builder and should
        // be generalized
        DefaultObjectBuilder builder = this.builder.get();
        resolveParameters(objectType, builder);
        resolveParameterGroups(objectType, builder);
        injectFields();
        ValueResolver<Object> resolver = new ObjectBuilderValueResolver<>(builder, muleContext);
        if (resolver.isDynamic()) {
            return resolver;
        }
        CoreEvent initialiserEvent = null;
        try {
            initialiserEvent = getInitialiserEvent(muleContext);
            staticProduct = resolver.resolve(from(initialiserEvent));
            muleContext.getInjector().inject(staticProduct);
            return staticProduct;
        } finally {
            if (initialiserEvent != null) {
                ((BaseEventContext) initialiserEvent.getContext()).success();
            }
        }
    }, Exception.class, exception -> {
        throw exception;
    });
}
Also used : BaseEventContext(org.mule.runtime.core.privileged.event.BaseEventContext) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) ObjectBuilderValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ObjectBuilderValueResolver) DefaultObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder)

Example 2 with DefaultObjectBuilder

use of org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder in project mule by mulesoft.

the class DefaultExtensionsClient method resolveParameters.

private Map<String, ValueResolver> resolveParameters(Map<String, Object> parameters, CoreEvent event) {
    LinkedHashMap<String, ValueResolver> values = new LinkedHashMap<>();
    parameters.forEach((name, value) -> {
        if (value instanceof ComplexParameter) {
            ComplexParameter complex = (ComplexParameter) value;
            DefaultObjectBuilder<?> builder = new DefaultObjectBuilder<>(complex.getType());
            resolveParameters(complex.getParameters(), event).forEach((propertyName, valueResolver) -> {
                try {
                    initialiseIfNeeded(valueResolver, true, muleContext);
                    builder.addPropertyResolver(propertyName, valueResolver);
                } catch (InitialisationException e) {
                    throw new MuleRuntimeException(e);
                }
            });
            try {
                values.put(name, new StaticValueResolver<>(builder.build(from(event))));
            } catch (MuleException e) {
                throw new MuleRuntimeException(createStaticMessage(format("Could not construct parameter [%s]", name)), e);
            }
        } else {
            if (value instanceof String && parser.isContainsTemplate((String) value)) {
                values.put(name, new ExpressionValueResolver((String) value));
            } else {
                values.put(name, new StaticValueResolver<>(value));
            }
        }
    });
    return values;
}
Also used : ComplexParameter(org.mule.runtime.extension.internal.client.ComplexParameter) StaticValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.StaticValueResolver) ValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ValueResolver) ExpressionValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ExpressionValueResolver) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) InitialisationException(org.mule.runtime.api.lifecycle.InitialisationException) DefaultObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder) MuleException(org.mule.runtime.api.exception.MuleException) LinkedHashMap(java.util.LinkedHashMap) ExpressionValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.ExpressionValueResolver)

Example 3 with DefaultObjectBuilder

use of org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder in project mule by mulesoft.

the class ReflectiveOperationExecutorFactory method createExecutor.

@Override
public ComponentExecutor<M> createExecutor(M operationModel, Map<String, Object> parameters) {
    DefaultObjectBuilder objectBuilder = new DefaultObjectBuilder(implementationClass);
    parameters.forEach((k, v) -> objectBuilder.addPropertyResolver(k, new StaticValueResolver<>(v)));
    Object delegate;
    CoreEvent initialiserEvent = null;
    try {
        initialiserEvent = getInitialiserEvent();
        delegate = objectBuilder.build(from(initialiserEvent));
    } catch (Exception e) {
        throw new MuleRuntimeException(createStaticMessage("Could not create instance of operation class " + implementationClass.getName()), e);
    } finally {
        if (initialiserEvent != null) {
            ((BaseEventContext) initialiserEvent.getContext()).success();
        }
    }
    return new ReflectiveMethodOperationExecutor(operationModel, operationMethod, delegate);
}
Also used : BaseEventContext(org.mule.runtime.core.privileged.event.BaseEventContext) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) StaticValueResolver(org.mule.runtime.module.extension.internal.runtime.resolver.StaticValueResolver) ReflectiveMethodOperationExecutor(org.mule.runtime.module.extension.internal.runtime.operation.ReflectiveMethodOperationExecutor) DefaultObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException)

Example 4 with DefaultObjectBuilder

use of org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder 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 5 with DefaultObjectBuilder

use of org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder in project mule by mulesoft.

the class DefaultObjectBuilderTestCase method noPublicConstructor.

@Test(expected = IllegalArgumentException.class)
public void noPublicConstructor() throws Exception {
    builder = new DefaultObjectBuilder(NoPublicConstructor.class);
    builder.build(resolvingContext);
}
Also used : DefaultObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder) SmallTest(org.mule.tck.size.SmallTest) Test(org.junit.Test)

Aggregations

DefaultObjectBuilder (org.mule.runtime.module.extension.internal.runtime.objectbuilder.DefaultObjectBuilder)13 Test (org.junit.Test)4 SmallTest (org.mule.tck.size.SmallTest)4 StaticValueResolver (org.mule.runtime.module.extension.internal.runtime.resolver.StaticValueResolver)3 Field (java.lang.reflect.Field)2 ObjectType (org.mule.metadata.api.model.ObjectType)2 MuleException (org.mule.runtime.api.exception.MuleException)2 MuleRuntimeException (org.mule.runtime.api.exception.MuleRuntimeException)2 InitialisationException (org.mule.runtime.api.lifecycle.InitialisationException)2 CoreEvent (org.mule.runtime.core.api.event.CoreEvent)2 BaseEventContext (org.mule.runtime.core.privileged.event.BaseEventContext)2 String.format (java.lang.String.format)1 Collections.emptyList (java.util.Collections.emptyList)1 LinkedHashMap (java.util.LinkedHashMap)1 Optional (java.util.Optional)1 Collectors.joining (java.util.stream.Collectors.joining)1 StringUtils.isBlank (org.apache.commons.lang3.StringUtils.isBlank)1 Before (org.junit.Before)1 TypeIdAnnotation (org.mule.metadata.api.annotation.TypeIdAnnotation)1 BaseTypeBuilder (org.mule.metadata.api.builder.BaseTypeBuilder)1