Search in sources :

Example 71 with ExtensionModel

use of org.mule.runtime.api.meta.model.ExtensionModel in project mule by mulesoft.

the class IsolatedClassLoaderExtensionsManagerConfigurationBuilder method loadExtensionModels.

public void loadExtensionModels() {
    try {
        loadRuntimeExtensionModels().forEach(extensionModels::add);
        for (Object pluginClassLoader : pluginsClassLoaders) {
            String artifactName = (String) pluginClassLoader.getClass().getMethod("getArtifactId").invoke(pluginClassLoader);
            ClassLoader classLoader = (ClassLoader) pluginClassLoader.getClass().getMethod("getClassLoader").invoke(pluginClassLoader);
            withContextClassLoader(classLoader, (CheckedRunnable) () -> {
                Method findResource = classLoader.getClass().getMethod("findResource", String.class);
                URL json = ((URL) findResource.invoke(classLoader, META_INF_MULE_ARTIFACT_MULE_PLUGIN));
                if (json == null) {
                    json = ((URL) findResource.invoke(classLoader, MULE_AUTO_GENERATED_ARTIFACT_PATH_INSIDE_JAR));
                }
                if (json != null) {
                    LOGGER.debug("Discovered extension '{}'", artifactName);
                    MulePluginBasedLoaderFinder finder = new MulePluginBasedLoaderFinder(json.openStream());
                    if (finder.isExtensionModelLoaderDescriptorDefined()) {
                        ExtensionModel extension = finder.getLoader().loadExtensionModel(classLoader, getDefault(ImmutableSet.copyOf(extensionModels)), finder.getParams());
                        extensionModels.add(extension);
                    } else {
                        LOGGER.debug("Discarding plugin with artifactName '{}' as it doesn't have an ExtensionModelLoaderDescriptor defined", artifactName);
                    }
                } else {
                    LOGGER.debug("Discarding plugin with artifactName '{}' as it doesn't have a mule-artifact.json", artifactName);
                }
            });
        }
    } catch (Exception e) {
        throw new RuntimeException("Error while loading extension models", e);
    }
}
Also used : ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) ArtifactClassLoader(org.mule.runtime.module.artifact.api.classloader.ArtifactClassLoader) ClassUtils.withContextClassLoader(org.mule.runtime.core.api.util.ClassUtils.withContextClassLoader) Method(java.lang.reflect.Method) URL(java.net.URL) InitialisationException(org.mule.runtime.api.lifecycle.InitialisationException)

Example 72 with ExtensionModel

use of org.mule.runtime.api.meta.model.ExtensionModel in project mule by mulesoft.

the class ExtensionsTestInfrastructureDiscoverer method discoverExtension.

/**
 * It will register the extensions described or annotated and it will generate their resources. If no describers are defined the
 * annotatedClasses would be used to generate the describers.
 *
 * @return a {@link List} of the resources generated for the given describers or annotated classes
 * @throws IllegalStateException if no extensions can be described
 */
public ExtensionModel discoverExtension(Class<?> annotatedClass, ExtensionModelLoader loader) {
    Map<String, Object> params = new HashMap<>();
    params.put(TYPE_PROPERTY_NAME, annotatedClass.getName());
    params.put(VERSION, getProductVersion());
    DslResolvingContext dslResolvingContext = getDefault(singleton(MuleExtensionModelProvider.getExtensionModel()));
    ExtensionModel model = loader.loadExtensionModel(annotatedClass.getClassLoader(), dslResolvingContext, params);
    extensionManager.registerExtension(model);
    return model;
}
Also used : HashMap(java.util.HashMap) ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) DslResolvingContext(org.mule.runtime.api.dsl.DslResolvingContext) NullDslResolvingContext(org.mule.runtime.internal.dsl.NullDslResolvingContext)

Example 73 with ExtensionModel

use of org.mule.runtime.api.meta.model.ExtensionModel in project mule by mulesoft.

the class NullSafeModelValidator method validate.

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

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

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

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

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

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

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

Example 74 with ExtensionModel

use of org.mule.runtime.api.meta.model.ExtensionModel in project mule by mulesoft.

the class XmlExtensionLoaderDelegate method findTestConnectionGlobalElementFrom.

/**
 * Goes over all {@code globalElementsComponentModel} looking for the configuration and connection elements (parent and child),
 * where if present looks for the {@link ExtensionModel}s validating if the element is in fact a {@link ConnectionProvider}.
 * It heavily relies on the {@link DslSyntaxResolver}, as many elements in the XML do not match to the names of the model.
 *
 * @param globalElementsComponentModel global elements of the smart connector
 * @param extensions set of extensions used to generate the current {@link ExtensionModel}
 * @return a {@link ComponentModel} of the global element to do test connection, empty otherwise.
 */
private Optional<ComponentModel> findTestConnectionGlobalElementFrom(List<ComponentModel> globalElementsComponentModel, Set<ExtensionModel> extensions) {
    Optional<ComponentModel> testConnectionGlobalElement;
    final DslResolvingContext dslResolvingContext = DslResolvingContext.getDefault(extensions);
    final Set<ComponentModel> testConnectionComponentModels = new HashSet<>();
    for (ComponentModel globalElementComponentModel : globalElementsComponentModel) {
        for (ComponentModel connectionProviderChildElement : globalElementComponentModel.getInnerComponents()) {
            final String globalElementConfigurationModelName = globalElementComponentModel.getIdentifier().getName();
            final String childConnectionProviderName = connectionProviderChildElement.getIdentifier().getName();
            for (ExtensionModel extensionModel : extensions) {
                final DslSyntaxResolver dslSyntaxResolver = DslSyntaxResolver.getDefault(extensionModel, dslResolvingContext);
                for (ConfigurationModel configurationModel : extensionModel.getConfigurationModels()) {
                    if (dslSyntaxResolver.resolve(configurationModel).getElementName().equals(globalElementConfigurationModelName)) {
                        for (ConnectionProviderModel connectionProviderModel : configurationModel.getConnectionProviders()) {
                            if (dslSyntaxResolver.resolve(connectionProviderModel).getElementName().equals(childConnectionProviderName)) {
                                testConnectionComponentModels.add(globalElementComponentModel);
                            }
                        }
                    }
                }
            }
        }
    }
    if (testConnectionComponentModels.size() > 1) {
        throw new MuleRuntimeException(createStaticMessage(format("There are [%d] global elements that can be potentially used for test connection when it should be just one. Mark any of them with the attribute [%s=\"true\"], offended global elements are: [%s]", testConnectionComponentModels.size(), MODULE_CONNECTION_MARKER_ATTRIBUTE, testConnectionComponentModels.stream().map(ComponentModel::getNameAttribute).sorted().collect(Collectors.joining(", ")))));
    }
    testConnectionGlobalElement = testConnectionComponentModels.stream().findFirst();
    return testConnectionGlobalElement;
}
Also used : ConfigurationModel(org.mule.runtime.api.meta.model.config.ConfigurationModel) ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) ComponentModel(org.mule.runtime.config.internal.model.ComponentModel) NullDslResolvingContext(org.mule.runtime.internal.dsl.NullDslResolvingContext) DslResolvingContext(org.mule.runtime.api.dsl.DslResolvingContext) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) DslSyntaxResolver(org.mule.runtime.extension.api.dsl.syntax.resolver.DslSyntaxResolver) ConnectionProviderModel(org.mule.runtime.api.meta.model.connection.ConnectionProviderModel) HashSet(java.util.HashSet)

Example 75 with ExtensionModel

use of org.mule.runtime.api.meta.model.ExtensionModel in project mule by mulesoft.

the class XmlExtensionLoaderDelegate method getModuleDocument.

private Document getModuleDocument(ExtensionLoadingContext context, URL resource) {
    XmlConfigurationDocumentLoader xmlConfigurationDocumentLoader = validateXml ? schemaValidatingDocumentLoader() : schemaValidatingDocumentLoader(NoOpXmlErrorHandler::new);
    try {
        final Set<ExtensionModel> extensions = new HashSet<>(context.getDslResolvingContext().getExtensions());
        createTnsExtensionModel(resource, extensions).ifPresent(extensions::add);
        return xmlConfigurationDocumentLoader.loadDocument(extensions, resource.getFile(), resource.openStream());
    } catch (IOException e) {
        throw new MuleRuntimeException(createStaticMessage(format("There was an issue reading the stream for the resource %s", resource.getFile())));
    }
}
Also used : ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) IOException(java.io.IOException) XmlConfigurationDocumentLoader(org.mule.runtime.config.api.XmlConfigurationDocumentLoader) HashSet(java.util.HashSet)

Aggregations

ExtensionModel (org.mule.runtime.api.meta.model.ExtensionModel)94 Test (org.junit.Test)50 SmallTest (org.mule.tck.size.SmallTest)34 OperationModel (org.mule.runtime.api.meta.model.operation.OperationModel)31 Optional (java.util.Optional)26 ConfigurationModel (org.mule.runtime.api.meta.model.config.ConfigurationModel)24 List (java.util.List)22 Set (java.util.Set)19 MuleRuntimeException (org.mule.runtime.api.exception.MuleRuntimeException)19 ParameterModel (org.mule.runtime.api.meta.model.parameter.ParameterModel)19 ConnectionProviderModel (org.mule.runtime.api.meta.model.connection.ConnectionProviderModel)16 HashMap (java.util.HashMap)15 SourceModel (org.mule.runtime.api.meta.model.source.SourceModel)15 String.format (java.lang.String.format)13 Collectors.toList (java.util.stream.Collectors.toList)13 HashSet (java.util.HashSet)12 Map (java.util.Map)12 Reference (org.mule.runtime.api.util.Reference)12 Optional.empty (java.util.Optional.empty)11 ObjectType (org.mule.metadata.api.model.ObjectType)11