Search in sources :

Example 1 with ConnectionProvider

use of org.mule.runtime.api.connection.ConnectionProvider in project mule by mulesoft.

the class LifecycleAwareConfigurationInstance method testConnectivity.

private void testConnectivity() throws MuleException {
    ConnectionProvider provider = connectionProvider.get();
    if (provider instanceof NoConnectivityTest) {
        return;
    }
    Scheduler retryScheduler = schedulerService.ioScheduler();
    RetryPolicyTemplate retryTemplate = connectionManager.getRetryTemplateFor(provider);
    ReconnectionConfig reconnectionConfig = connectionManager.getReconnectionConfigFor(provider);
    RetryCallback retryCallback = new RetryCallback() {

        @Override
        public void doWork(RetryContext context) throws Exception {
            Lock lock = testConnectivityLock;
            if (lock != null) {
                final boolean lockAcquired = lock.tryLock();
                if (lockAcquired) {
                    LOGGER.info("Doing testConnectivity() for config " + getName());
                    try {
                        ConnectionValidationResult result = connectionManager.testConnectivity(LifecycleAwareConfigurationInstance.this);
                        if (result.isValid()) {
                            context.setOk();
                        } else {
                            if ((reconnectionConfig.isFailsDeployment())) {
                                context.setFailed(result.getException());
                                throw new ConnectionException(format("Connectivity test failed for config '%s'", getName()), result.getException());
                            } else {
                                if (LOGGER.isInfoEnabled()) {
                                    LOGGER.info(format("Connectivity test failed for config '%s'. Application deployment will continue. Error was: ", getName(), result.getMessage()), result.getException());
                                }
                            }
                        }
                    } finally {
                        lock.unlock();
                    }
                } else {
                    LOGGER.warn("There is a testConnectivity() already running for config " + getName());
                }
            }
        }

        @Override
        public String getWorkDescription() {
            return format("Testing connectivity for config '%s'", getName());
        }

        @Override
        public Object getWorkOwner() {
            return value;
        }
    };
    try {
        retryTemplate.execute(retryCallback, retryScheduler);
    } catch (Exception e) {
        throw new DefaultMuleException(createStaticMessage(format("Could not perform connectivity testing for config '%s'", getName())), e);
    } finally {
        if (retryScheduler != null) {
            retryScheduler.stop();
        }
    }
}
Also used : RetryPolicyTemplate(org.mule.runtime.core.api.retry.policy.RetryPolicyTemplate) Scheduler(org.mule.runtime.api.scheduler.Scheduler) RetryContext(org.mule.runtime.core.api.retry.RetryContext) ReconnectionConfig(org.mule.runtime.core.internal.retry.ReconnectionConfig) InitialisationException(org.mule.runtime.api.lifecycle.InitialisationException) MuleException(org.mule.runtime.api.exception.MuleException) DefaultMuleException(org.mule.runtime.api.exception.DefaultMuleException) ConnectionException(org.mule.runtime.api.connection.ConnectionException) ConnectionProvider(org.mule.runtime.api.connection.ConnectionProvider) Lock(java.util.concurrent.locks.Lock) DefaultMuleException(org.mule.runtime.api.exception.DefaultMuleException) ConnectionValidationResult(org.mule.runtime.api.connection.ConnectionValidationResult) NoConnectivityTest(org.mule.runtime.extension.api.connectivity.NoConnectivityTest) ConnectionException(org.mule.runtime.api.connection.ConnectionException) RetryCallback(org.mule.runtime.core.api.retry.RetryCallback)

Example 2 with ConnectionProvider

use of org.mule.runtime.api.connection.ConnectionProvider in project mule by mulesoft.

the class SourceAdapter method setConnection.

private void setConnection() throws MuleException {
    if (!connectionSetter.isPresent()) {
        return;
    }
    FieldSetter<Object, ConnectionProvider> setter = connectionSetter.get();
    ConfigurationInstance config = configurationInstance.orElseThrow(() -> new DefaultMuleException(createStaticMessage("Message Source on root component '%s' requires a connection but it doesn't point to any configuration. Please review your " + "application", component.getLocation().getRootContainerName())));
    if (!config.getConnectionProvider().isPresent()) {
        throw new DefaultMuleException(createStaticMessage(format("Message Source on root component '%s' requires a connection, but points to config '%s' which doesn't specify any. " + "Please review your application", component.getLocation().getRootContainerName(), config.getName())));
    }
    ConnectionProvider<Object> connectionProvider = new SourceConnectionProvider(connectionManager, config);
    setter.set(sourceInvokationTarget.get(), connectionProvider);
}
Also used : DefaultMuleException(org.mule.runtime.api.exception.DefaultMuleException) ConnectionProvider(org.mule.runtime.api.connection.ConnectionProvider) ConfigurationInstance(org.mule.runtime.extension.api.runtime.config.ConfigurationInstance)

Example 3 with ConnectionProvider

use of org.mule.runtime.api.connection.ConnectionProvider in project mule by mulesoft.

the class CachedConnectionHandlerTestCase method getConnectionConcurrentlyAndConnectOnlyOnce.

@Test
public void getConnectionConcurrentlyAndConnectOnlyOnce() throws Exception {
    Banana mockConnection = mock(Banana.class);
    connectionProvider = mock(ConnectionProvider.class);
    before();
    Latch latch = new Latch();
    when(connectionProvider.connect()).thenAnswer(invocation -> {
        new Thread(() -> {
            try {
                latch.release();
                getConnection();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).start();
        return mockConnection;
    });
    Banana connection = managedConnection.getConnection();
    assertThat(latch.await(5, TimeUnit.SECONDS), is(true));
    assertThat(connection, is(sameInstance(mockConnection)));
    verify(connectionProvider).connect();
}
Also used : Latch(org.mule.runtime.api.util.concurrent.Latch) Banana(org.mule.tck.testmodels.fruit.Banana) ConnectionProvider(org.mule.runtime.api.connection.ConnectionProvider) Test(org.junit.Test) SmallTest(org.mule.tck.size.SmallTest)

Example 4 with ConnectionProvider

use of org.mule.runtime.api.connection.ConnectionProvider in project mule by mulesoft.

the class ConfigurationProviderToolingAdapter method withConnectionProviderInfo.

private <T> T withConnectionProviderInfo(WithConnectionProviderCallable<T> withConnectionProviderCallable) throws ValueResolvingException {
    ConnectionProvider<?> connectionProvider = configuration.getConnectionProvider().orElseThrow(() -> new ValueResolvingException("Unable to obtain the Connection Provider Instance", UNKNOWN));
    ConnectionProvider unwrap = unwrapProviderWrapper(connectionProvider);
    ConnectionProviderModel connectionProviderModel = getConnectionProviderModel(unwrap.getClass(), getAllConnectionProviders(getExtensionModel(), getConfigurationModel())).orElseThrow(() -> new ValueResolvingException("Internal error. Unable to obtain the Connection Provider Model", UNKNOWN));
    return withConnectionProviderCallable.call(unwrap, connectionProviderModel);
}
Also used : IntrospectionUtils.getConnectionProviderModel(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.getConnectionProviderModel) ConnectionProviderModel(org.mule.runtime.api.meta.model.connection.ConnectionProviderModel) ValueResolvingException(org.mule.runtime.extension.api.values.ValueResolvingException) ConnectionProvider(org.mule.runtime.api.connection.ConnectionProvider)

Example 5 with ConnectionProvider

use of org.mule.runtime.api.connection.ConnectionProvider in project mule by mulesoft.

the class DefaultConnectionProviderObjectBuilder method applyExtensionClassLoaderProxy.

/**
 * Wraps the {@link ConnectionProvider} inside of a dynamic proxy which changes the current {@link ClassLoader} to the the
 * extension's {@link ClassLoader} when executing any method of this wrapped {@link ConnectionProvider}
 * <p>
 * This ensures that every time that the {@link ConnectionProvider} is used, it will work in the correct classloader.
 * <p>
 * Although if the {@link ConnectionProvider} is created with the correct classloader and then used with an incorrect one this
 * may work, due that static class references were loaded correctly, logic loading class in a dynamic way will fail.
 *
 * @param provider The {@link ConnectionProvider} to wrap
 * @return The wrapped {@link ConnectionProvider}
 */
private ConnectionProvider<C> applyExtensionClassLoaderProxy(ConnectionProvider provider) {
    Enhancer enhancer = new Enhancer();
    ClassLoader classLoader = getClassLoader(extensionModel);
    Class[] proxyInterfaces = getProxyInterfaces(provider);
    enhancer.setInterfaces(proxyInterfaces);
    MethodInterceptor returnProviderInterceptor = (obj, method, args, proxy) -> provider;
    MethodInterceptor invokerInterceptor = (obj, method, args, proxy) -> {
        Reference<Object> resultReference = new Reference<>();
        Reference<Throwable> errorReference = new Reference<>();
        withContextClassLoader(classLoader, () -> {
            try {
                resultReference.set(method.invoke(provider, args));
            } catch (InvocationTargetException e) {
                errorReference.set(e.getTargetException());
            } catch (Throwable t) {
                errorReference.set(t);
            }
        });
        if (errorReference.get() != null) {
            throw errorReference.get();
        } else {
            return resultReference.get();
        }
    };
    CallbackHelper callbackHelper = new CallbackHelper(Object.class, proxyInterfaces) {

        @Override
        protected Object getCallback(Method method) {
            if (method.getDeclaringClass().equals(HasDelegate.class) && method.getName().equals("getDelegate")) {
                return returnProviderInterceptor;
            } else {
                return invokerInterceptor;
            }
        }
    };
    enhancer.setCallbackTypes(callbackHelper.getCallbackTypes());
    enhancer.setCallbackFilter(callbackHelper);
    if (Enhancer.class.getClassLoader() != classLoader) {
        enhancer.setClassLoader(new CompositeClassLoader(DefaultConnectionProviderObjectBuilder.class.getClassLoader(), classLoader));
        enhancer.setUseCache(false);
    }
    Class<ConnectionProvider<C>> proxyClass = enhancer.createClass();
    registerStaticCallbacks(proxyClass, callbackHelper.getCallbacks());
    try {
        return proxyClass.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new MuleRuntimeException(e);
    }
}
Also used : ErrorTypeHandlerConnectionProviderWrapper(org.mule.runtime.core.internal.connection.ErrorTypeHandlerConnectionProviderWrapper) ConnectionProviderModel(org.mule.runtime.api.meta.model.connection.ConnectionProviderModel) MuleExtensionUtils.getClassLoader(org.mule.runtime.module.extension.internal.util.MuleExtensionUtils.getClassLoader) ResolverSet(org.mule.runtime.module.extension.internal.runtime.resolver.ResolverSet) POOLING(org.mule.runtime.api.meta.model.connection.ConnectionManagementType.POOLING) ClassUtils(org.apache.commons.lang3.ClassUtils) MuleContext(org.mule.runtime.core.api.MuleContext) MuleException(org.mule.runtime.api.exception.MuleException) ReconnectableConnectionProviderWrapper(org.mule.runtime.core.internal.connection.ReconnectableConnectionProviderWrapper) PoolingProfile(org.mule.runtime.api.config.PoolingProfile) ClassUtils.withContextClassLoader(org.mule.runtime.core.api.util.ClassUtils.withContextClassLoader) Pair(org.mule.runtime.api.util.Pair) Enhancer(net.sf.cglib.proxy.Enhancer) Method(java.lang.reflect.Method) PoolingConnectionProviderWrapper(org.mule.runtime.core.internal.connection.PoolingConnectionProviderWrapper) IntrospectionUtils.injectFields(org.mule.runtime.module.extension.internal.util.IntrospectionUtils.injectFields) Enhancer.registerStaticCallbacks(net.sf.cglib.proxy.Enhancer.registerStaticCallbacks) CallbackHelper(net.sf.cglib.proxy.CallbackHelper) ConnectionProvider(org.mule.runtime.api.connection.ConnectionProvider) ResolverSetBasedObjectBuilder(org.mule.runtime.module.extension.internal.runtime.objectbuilder.ResolverSetBasedObjectBuilder) MethodInterceptor(net.sf.cglib.proxy.MethodInterceptor) CompositeClassLoader(org.mule.runtime.core.internal.util.CompositeClassLoader) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) Initialisable(org.mule.runtime.api.lifecycle.Initialisable) ConnectionManagementType(org.mule.runtime.api.meta.model.connection.ConnectionManagementType) ExtensionModel(org.mule.runtime.api.meta.model.ExtensionModel) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) HasDelegate(org.mule.runtime.core.internal.connection.HasDelegate) ReconnectionConfig(org.mule.runtime.core.internal.retry.ReconnectionConfig) Reference(org.mule.runtime.api.util.Reference) ResolverSetResult(org.mule.runtime.module.extension.internal.runtime.resolver.ResolverSetResult) Enhancer(net.sf.cglib.proxy.Enhancer) CallbackHelper(net.sf.cglib.proxy.CallbackHelper) Reference(org.mule.runtime.api.util.Reference) Method(java.lang.reflect.Method) HasDelegate(org.mule.runtime.core.internal.connection.HasDelegate) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConnectionProvider(org.mule.runtime.api.connection.ConnectionProvider) MethodInterceptor(net.sf.cglib.proxy.MethodInterceptor) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) MuleExtensionUtils.getClassLoader(org.mule.runtime.module.extension.internal.util.MuleExtensionUtils.getClassLoader) ClassUtils.withContextClassLoader(org.mule.runtime.core.api.util.ClassUtils.withContextClassLoader) CompositeClassLoader(org.mule.runtime.core.internal.util.CompositeClassLoader) CompositeClassLoader(org.mule.runtime.core.internal.util.CompositeClassLoader)

Aggregations

ConnectionProvider (org.mule.runtime.api.connection.ConnectionProvider)8 ReconnectionConfig (org.mule.runtime.core.internal.retry.ReconnectionConfig)3 ConfigurationInstance (org.mule.runtime.extension.api.runtime.config.ConfigurationInstance)3 Test (org.junit.Test)2 DefaultMuleException (org.mule.runtime.api.exception.DefaultMuleException)2 MuleException (org.mule.runtime.api.exception.MuleException)2 ConnectionProviderModel (org.mule.runtime.api.meta.model.connection.ConnectionProviderModel)2 ReconnectableConnectionProviderWrapper (org.mule.runtime.core.internal.connection.ReconnectableConnectionProviderWrapper)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 List (java.util.List)1 Lock (java.util.concurrent.locks.Lock)1 TransactionManager (javax.transaction.TransactionManager)1 CallbackHelper (net.sf.cglib.proxy.CallbackHelper)1 Enhancer (net.sf.cglib.proxy.Enhancer)1 Enhancer.registerStaticCallbacks (net.sf.cglib.proxy.Enhancer.registerStaticCallbacks)1 MethodInterceptor (net.sf.cglib.proxy.MethodInterceptor)1 ClassUtils (org.apache.commons.lang3.ClassUtils)1 Before (org.junit.Before)1 PoolingProfile (org.mule.runtime.api.config.PoolingProfile)1