Search in sources :

Example 11 with MuleContextWithRegistries

use of org.mule.runtime.core.internal.context.MuleContextWithRegistries in project mule by mulesoft.

the class TypeBasedTransformerResolver method resolve.

public Transformer resolve(DataType source, DataType result) throws ResolverException {
    Transformer transformer = exactTransformerCache.get(source.toString() + result.toString());
    if (transformer != null) {
        return transformer;
    }
    MuleRegistry registry = ((MuleContextWithRegistries) muleContext).getRegistry();
    List<Transformer> trans = registry.lookupTransformers(source, result);
    Transformer compositeTransformer = graphTransformerResolver.resolve(source, result);
    if (compositeTransformer != null) {
        // Needs to create a new list because the lookup returns a cached instance
        trans = new LinkedList<>(trans);
        trans.add(compositeTransformer);
    }
    transformer = getNearestTransformerMatch(trans, source.getType(), result.getType());
    // If an exact mach is not found, we have a 'second pass' transformer that can be used to converting to String or
    // byte[]
    Transformer secondPass;
    if (transformer == null) {
        // using Object.class and then convert to String or byte[] using the second pass transformer
        if (String.class.equals(result.getType())) {
            secondPass = objectToString;
        } else if (byte[].class.equals(result.getType())) {
            secondPass = objectToByteArray;
        } else {
            return null;
        }
        // Perform a more general search
        trans = registry.lookupTransformers(source, DataType.OBJECT);
        transformer = getNearestTransformerMatch(trans, source.getType(), result.getType());
        if (transformer != null) {
            transformer = new TransformerChain(transformer, secondPass);
            try {
                registry.registerTransformer(transformer);
            } catch (MuleException e) {
                throw new ResolverException(e.getI18nMessage(), e);
            }
        }
    }
    if (transformer != null) {
        exactTransformerCache.put(source.toString() + result.toString(), transformer);
    }
    return transformer;
}
Also used : Transformer(org.mule.runtime.core.api.transformer.Transformer) ResolverException(org.mule.runtime.core.internal.transformer.ResolverException) MuleContextWithRegistries(org.mule.runtime.core.internal.context.MuleContextWithRegistries) TransformerChain(org.mule.runtime.core.privileged.transformer.TransformerChain) MuleException(org.mule.runtime.api.exception.MuleException)

Example 12 with MuleContextWithRegistries

use of org.mule.runtime.core.internal.context.MuleContextWithRegistries in project mule by mulesoft.

the class TransformerUtils method attemptTransformation.

private static <S, R> R attemptTransformation(DataType sourceDataType, S source, DataType resultDataType, MuleContext muleContext) {
    Transformer transformer;
    try {
        transformer = ((MuleContextWithRegistries) muleContext).getRegistry().lookupTransformer(sourceDataType, resultDataType);
    } catch (TransformerException e) {
        LOGGER.debug("Could not find a transformer from type {} to {}", sourceDataType.getType().getName(), resultDataType.getType().getName());
        return null;
    }
    LOGGER.debug("Located transformer {} from type {} to type {}. Attempting transformation...", transformer.getName(), sourceDataType.getType().getName(), resultDataType.getType().getName());
    try {
        return (R) transformer.transform(source);
    } catch (TransformerException e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(format("Transformer %s threw exception while trying to transform an object of type %s into a %s", transformer.getName(), sourceDataType.getType().getName(), resultDataType.getType().getName()), e);
        }
        return null;
    }
}
Also used : Transformer(org.mule.runtime.core.api.transformer.Transformer) AbstractTransformer(org.mule.runtime.core.api.transformer.AbstractTransformer) MuleContextWithRegistries(org.mule.runtime.core.internal.context.MuleContextWithRegistries) TransformerException(org.mule.runtime.core.api.transformer.TransformerException)

Example 13 with MuleContextWithRegistries

use of org.mule.runtime.core.internal.context.MuleContextWithRegistries in project mule by mulesoft.

the class AbstractExtensionMessageSourceTestCase method before.

@Before
public void before() throws Exception {
    initMocks(this);
    spyInjector(muleContext);
    reset(muleContext.getSchedulerService());
    when(result.getMediaType()).thenReturn(of(ANY));
    when(result.getAttributes()).thenReturn(empty());
    ((MuleContextWithRegistries) muleContext).getRegistry().registerObject(OBJECT_STREAMING_MANAGER, streamingManager);
    when(extensionModel.getXmlDslModel()).thenReturn(XmlDslModel.builder().setPrefix("test-extension").build());
    cursorStreamProviderFactory = getDefaultCursorStreamProviderFactory(streamingManager);
    sourceAdapter = createSourceAdapter();
    when(sourceAdapterFactory.createAdapter(any(), any(), any(), any(), any())).thenReturn(sourceAdapter);
    mockExceptionEnricher(sourceModel, null);
    when(sourceModel.requiresConnection()).thenReturn(true);
    when(sourceModel.getName()).thenReturn(SOURCE_NAME);
    when(sourceModel.getModelProperty(MetadataResolverFactoryModelProperty.class)).thenReturn(empty());
    when(sourceModel.getModelProperty(SourceCallbackModelProperty.class)).thenReturn(empty());
    when(sourceModel.getModelProperty(MediaTypeModelProperty.class)).thenReturn(empty());
    setRequires(sourceModel, true, true);
    when(sourceModel.getOutput().getType()).thenReturn(TYPE_LOADER.load(String.class));
    when(sourceModel.getNotificationModels()).thenReturn(emptySet());
    mockExceptionEnricher(extensionModel, null);
    mockClassLoaderModelProperty(extensionModel, getClass().getClassLoader());
    retryPolicyTemplate.setNotificationFirer(((MuleContextWithRegistries) muleContext).getRegistry().lookupObject(NotificationDispatcher.class));
    initialiseIfNeeded(retryPolicyTemplate, muleContext);
    ((MuleContextWithRegistries) muleContext).getRegistry().registerObject(OBJECT_EXTENSION_MANAGER, extensionManager);
    when(flowConstruct.getMuleContext()).thenReturn(muleContext);
    mockSubTypes(extensionModel);
    when(configurationModel.getSourceModel(SOURCE_NAME)).thenReturn(of(sourceModel));
    when(extensionManager.getConfigurationProvider(CONFIG_NAME)).thenReturn(of(configurationProvider));
    when(configurationProvider.get(any())).thenReturn(configurationInstance);
    when(configurationProvider.getConfigurationModel()).thenReturn(configurationModel);
    when(configurationProvider.getName()).thenReturn(CONFIG_NAME);
    mockMetadataResolverFactory(sourceModel, metadataResolverFactory);
    when(metadataResolverFactory.getKeyResolver()).thenReturn(new TestNoConfigMetadataResolver());
    when(metadataResolverFactory.getInputResolver("content")).thenReturn(new TestNoConfigMetadataResolver());
    when(metadataResolverFactory.getInputResolver("type")).thenReturn(new NullMetadataResolver());
    when(metadataResolverFactory.getOutputResolver()).thenReturn(new TestNoConfigMetadataResolver());
    when(metadataResolverFactory.getOutputAttributesResolver()).thenReturn(new TestNoConfigMetadataResolver());
    when(sourceModel.getOutput()).thenReturn(new ImmutableOutputModel("Output", BaseTypeBuilder.create(JAVA).stringType().build(), true, emptySet()));
    when(sourceModel.getOutputAttributes()).thenReturn(new ImmutableOutputModel("Output", BaseTypeBuilder.create(JAVA).stringType().build(), false, emptySet()));
    when(sourceModel.getModelProperty(MetadataKeyIdModelProperty.class)).thenReturn(of(new MetadataKeyIdModelProperty(typeLoader.load(String.class), METADATA_KEY)));
    when(sourceModel.getAllParameterModels()).thenReturn(emptyList());
    when(messageProcessContext.getTransactionConfig()).thenReturn(empty());
    messageSource = getNewExtensionMessageSourceInstance();
    sourceCallback = spy(DefaultSourceCallback.builder().setSourceModel(sourceModel).setProcessingManager(messageProcessingManager).setListener(messageProcessor).setSource(messageSource).setMuleContext(muleContext).setProcessContextSupplier(() -> messageProcessContext).setCompletionHandlerFactory(completionHandlerFactory).setExceptionCallback(exceptionCallback).setCursorStreamProviderFactory(cursorStreamProviderFactory).build());
    when(sourceCallbackFactory.createSourceCallback(any())).thenReturn(sourceCallback);
}
Also used : NullMetadataResolver(org.mule.runtime.extension.api.metadata.NullMetadataResolver) ImmutableOutputModel(org.mule.runtime.extension.api.model.ImmutableOutputModel) MetadataKeyIdModelProperty(org.mule.runtime.extension.api.property.MetadataKeyIdModelProperty) MuleContextWithRegistries(org.mule.runtime.core.internal.context.MuleContextWithRegistries) NotificationDispatcher(org.mule.runtime.api.notification.NotificationDispatcher) TestNoConfigMetadataResolver(org.mule.test.metadata.extension.resolver.TestNoConfigMetadataResolver) Before(org.junit.Before)

Example 14 with MuleContextWithRegistries

use of org.mule.runtime.core.internal.context.MuleContextWithRegistries in project mule by mulesoft.

the class MuleTestUtils method createAndRegisterFlow.

/**
 * Creates a new flow and registers it in the given {@code mockComponentLocator}
 *
 * @param mockComponentLocator a {@link Mockito#mock(Class)} {@link ConfigurationComponentLocator}
 */
public static Flow createAndRegisterFlow(MuleContext context, String flowName, ConfigurationComponentLocator mockComponentLocator) throws MuleException {
    Flow flow = createFlow(context, flowName);
    MuleRegistry registry = ((MuleContextWithRegistries) context).getRegistry();
    if (registry != null) {
        registry.registerFlowConstruct(flow);
    }
    when(mockComponentLocator.find(Location.builder().globalName(flowName).build())).thenReturn(Optional.of(flow));
    return flow;
}
Also used : MuleContextWithRegistries(org.mule.runtime.core.internal.context.MuleContextWithRegistries) MuleRegistry(org.mule.runtime.core.internal.registry.MuleRegistry) Flow(org.mule.runtime.core.api.construct.Flow)

Example 15 with MuleContextWithRegistries

use of org.mule.runtime.core.internal.context.MuleContextWithRegistries in project mule by mulesoft.

the class TestServicesConfigurationBuilder method doConfigure.

@Override
public void doConfigure(MuleContext muleContext) throws Exception {
    MuleRegistry registry = ((MuleContextWithRegistries) muleContext).getRegistry();
    registry.registerObject(schedulerService.getName(), spy(schedulerService));
    registry.registerObject(OBJECT_SCHEDULER_BASE_CONFIG, config());
    if (mockExpressionExecutor) {
        DefaultExpressionLanguageFactoryService expressionExecutor = mock(DefaultExpressionLanguageFactoryService.class, RETURNS_DEEP_STUBS);
        registry.registerObject(MOCK_EXPR_EXECUTOR, expressionExecutor);
    } else {
        // Avoid doing the DW warm-up for every test, reusing the ExpressionLanguage implementation
        if (cachedExprLanguageFactory == null) {
            final DefaultExpressionLanguageFactoryService exprExecutor = new WeaveDefaultExpressionLanguageFactoryService();
            ExpressionLanguage exprLanguage = exprExecutor.create();
            // Force initialization of internal DataWeave stuff
            // This way we avoid doing some heavy initialization on the test itself,
            // which may cause trouble when evaluation expressions in places with small timeouts
            exprLanguage.evaluate("{dataWeave: 'is'} ++ {mule: 'default EL'}", NULL_BINDING_CONTEXT);
            cachedExprLanguageFactory = new DefaultExpressionLanguageFactoryService() {

                @Override
                public ExpressionLanguage create() {
                    return exprLanguage;
                }

                @Override
                public String getName() {
                    return exprExecutor.getName();
                }
            };
        }
        registry.registerObject(cachedExprLanguageFactory.getName(), cachedExprLanguageFactory);
    }
    if (mockHttpService) {
        registry.registerObject(MOCK_HTTP_SERVICE, mock(HttpService.class));
    }
}
Also used : WeaveDefaultExpressionLanguageFactoryService(org.mule.weave.v2.el.WeaveDefaultExpressionLanguageFactoryService) MuleContextWithRegistries(org.mule.runtime.core.internal.context.MuleContextWithRegistries) HttpService(org.mule.runtime.http.api.HttpService) MuleRegistry(org.mule.runtime.core.internal.registry.MuleRegistry) DefaultExpressionLanguageFactoryService(org.mule.runtime.api.el.DefaultExpressionLanguageFactoryService) WeaveDefaultExpressionLanguageFactoryService(org.mule.weave.v2.el.WeaveDefaultExpressionLanguageFactoryService) ExpressionLanguage(org.mule.runtime.api.el.ExpressionLanguage)

Aggregations

MuleContextWithRegistries (org.mule.runtime.core.internal.context.MuleContextWithRegistries)25 Test (org.junit.Test)12 MuleRegistry (org.mule.runtime.core.internal.registry.MuleRegistry)7 Before (org.junit.Before)6 NotificationDispatcher (org.mule.runtime.api.notification.NotificationDispatcher)6 RegistrationException (org.mule.runtime.core.privileged.registry.RegistrationException)6 Collections.singletonMap (java.util.Collections.singletonMap)5 HashMap (java.util.HashMap)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 Map (java.util.Map)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Assert.assertEquals (org.junit.Assert.assertEquals)4 DataType (org.mule.runtime.api.metadata.DataType)4 Transformer (org.mule.runtime.core.api.transformer.Transformer)4 FileReader (java.io.FileReader)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 BigDecimal (java.math.BigDecimal)3 BigInteger (java.math.BigInteger)3 URI (java.net.URI)3