Search in sources :

Example 11 with LifecycleStrategy

use of org.apache.camel.spi.LifecycleStrategy in project camel by apache.

the class DefaultCamelContext method doStartCamel.

private void doStartCamel() throws Exception {
    // custom properties may use property placeholders so resolve those early on
    if (globalOptions != null && !globalOptions.isEmpty()) {
        for (Map.Entry<String, String> entry : globalOptions.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (value != null) {
                String replaced = resolvePropertyPlaceholders(value);
                if (!value.equals(replaced)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Camel property with key {} replaced value from {} -> {}", new Object[] { key, value, replaced });
                    }
                    entry.setValue(replaced);
                }
            }
        }
    }
    if (classResolver instanceof CamelContextAware) {
        ((CamelContextAware) classResolver).setCamelContext(this);
    }
    if (log.isDebugEnabled()) {
        log.debug("Using ClassResolver={}, PackageScanClassResolver={}, ApplicationContextClassLoader={}", new Object[] { getClassResolver(), getPackageScanClassResolver(), getApplicationContextClassLoader() });
    }
    if (isStreamCaching()) {
        log.info("StreamCaching is enabled on CamelContext: {}", getName());
    }
    if (isTracing()) {
        // tracing is added in the DefaultChannel so we can enable it on the fly
        log.info("Tracing is enabled on CamelContext: {}", getName());
    }
    if (isUseMDCLogging()) {
        // log if MDC has been enabled
        log.info("MDC logging is enabled on CamelContext: {}", getName());
    }
    if (isHandleFault()) {
        // only add a new handle fault if not already configured
        if (HandleFault.getHandleFault(this) == null) {
            log.info("HandleFault is enabled on CamelContext: {}", getName());
            addInterceptStrategy(new HandleFault());
        }
    }
    if (getDelayer() != null && getDelayer() > 0) {
        log.info("Delayer is enabled with: {} ms. on CamelContext: {}", getDelayer(), getName());
    }
    // register debugger
    if (getDebugger() != null) {
        log.info("Debugger: {} is enabled on CamelContext: {}", getDebugger(), getName());
        // register this camel context on the debugger
        getDebugger().setCamelContext(this);
        startService(getDebugger());
        addInterceptStrategy(new Debug(getDebugger()));
    }
    // start management strategy before lifecycles are started
    ManagementStrategy managementStrategy = getManagementStrategy();
    // inject CamelContext if aware
    if (managementStrategy instanceof CamelContextAware) {
        ((CamelContextAware) managementStrategy).setCamelContext(this);
    }
    ServiceHelper.startService(managementStrategy);
    // start lifecycle strategies
    ServiceHelper.startServices(lifecycleStrategies);
    Iterator<LifecycleStrategy> it = lifecycleStrategies.iterator();
    while (it.hasNext()) {
        LifecycleStrategy strategy = it.next();
        try {
            strategy.onContextStart(this);
        } catch (VetoCamelContextStartException e) {
            // okay we should not start Camel since it was vetoed
            log.warn("Lifecycle strategy vetoed starting CamelContext ({}) due: {}", getName(), e.getMessage());
            throw e;
        } catch (Exception e) {
            log.warn("Lifecycle strategy " + strategy + " failed starting CamelContext ({}) due: {}", getName(), e.getMessage());
            throw e;
        }
    }
    // start notifiers as services
    for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
        if (notifier instanceof Service) {
            Service service = (Service) notifier;
            for (LifecycleStrategy strategy : lifecycleStrategies) {
                strategy.onServiceAdd(this, service, null);
            }
        }
        if (notifier instanceof Service) {
            startService((Service) notifier);
        }
    }
    // must let some bootstrap service be started before we can notify the starting event
    EventHelper.notifyCamelContextStarting(this);
    forceLazyInitialization();
    // re-create endpoint registry as the cache size limit may be set after the constructor of this instance was called.
    // and we needed to create endpoints up-front as it may be accessed before this context is started
    endpoints = new DefaultEndpointRegistry(this, endpoints);
    // add this as service and force pre-start them
    addService(endpoints, true, true);
    // special for executorServiceManager as want to stop it manually so false in stopOnShutdown
    addService(executorServiceManager, false, true);
    addService(producerServicePool, true, true);
    addService(pollingConsumerServicePool, true, true);
    addService(inflightRepository, true, true);
    addService(asyncProcessorAwaitManager, true, true);
    addService(shutdownStrategy, true, true);
    addService(packageScanClassResolver, true, true);
    addService(restRegistry, true, true);
    addService(messageHistoryFactory, true, true);
    addService(runtimeCamelCatalog, true, true);
    if (reloadStrategy != null) {
        log.info("Using ReloadStrategy: {}", reloadStrategy);
        addService(reloadStrategy, true, true);
    }
    // Initialize declarative transformer/validator registry
    transformerRegistry = new DefaultTransformerRegistry(this, transformers);
    addService(transformerRegistry, true, true);
    validatorRegistry = new DefaultValidatorRegistry(this, validators);
    addService(validatorRegistry, true, true);
    if (runtimeEndpointRegistry != null) {
        if (runtimeEndpointRegistry instanceof EventNotifier) {
            getManagementStrategy().addEventNotifier((EventNotifier) runtimeEndpointRegistry);
        }
        addService(runtimeEndpointRegistry, true, true);
    }
    // eager lookup any configured properties component to avoid subsequent lookup attempts which may impact performance
    // due we use properties component for property placeholder resolution at runtime
    Component existing = CamelContextHelper.lookupPropertiesComponent(this, false);
    if (existing != null) {
        // store reference to the existing properties component
        if (existing instanceof PropertiesComponent) {
            propertiesComponent = (PropertiesComponent) existing;
        } else {
            // properties component must be expected type
            throw new IllegalArgumentException("Found properties component of type: " + existing.getClass() + " instead of expected: " + PropertiesComponent.class);
        }
    }
    // start components
    startServices(components.values());
    // start the route definitions before the routes is started
    startRouteDefinitions(routeDefinitions);
    // is there any stream caching enabled then log an info about this and its limit of spooling to disk, so people is aware of this
    boolean streamCachingInUse = isStreamCaching();
    if (!streamCachingInUse) {
        for (RouteDefinition route : routeDefinitions) {
            Boolean routeCache = CamelContextHelper.parseBoolean(this, route.getStreamCache());
            if (routeCache != null && routeCache) {
                streamCachingInUse = true;
                break;
            }
        }
    }
    if (streamCachingInUse) {
        // stream caching is in use so enable the strategy
        getStreamCachingStrategy().setEnabled(true);
        addService(getStreamCachingStrategy(), true, true);
    } else {
        // log if stream caching is not in use as this can help people to enable it if they use streams
        log.info("StreamCaching is not in use. If using streams then its recommended to enable stream caching." + " See more details at http://camel.apache.org/stream-caching.html");
    }
    if (isAllowUseOriginalMessage()) {
        log.debug("AllowUseOriginalMessage enabled because UseOriginalMessage is in use");
    }
    // start routes
    if (doNotStartRoutesOnFirstStart) {
        log.debug("Skip starting of routes as CamelContext has been configured with autoStartup=false");
    }
    // invoke this logic to warmup the routes and if possible also start the routes
    doStartOrResumeRoutes(routeServices, true, !doNotStartRoutesOnFirstStart, false, true);
// starting will continue in the start method
}
Also used : CamelContextAware(org.apache.camel.CamelContextAware) DefaultManagementStrategy(org.apache.camel.management.DefaultManagementStrategy) ManagementStrategy(org.apache.camel.spi.ManagementStrategy) Service(org.apache.camel.Service) StatefulService(org.apache.camel.StatefulService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) SuspendableService(org.apache.camel.SuspendableService) RuntimeCamelException(org.apache.camel.RuntimeCamelException) MalformedObjectNameException(javax.management.MalformedObjectNameException) VetoCamelContextStartException(org.apache.camel.VetoCamelContextStartException) IOException(java.io.IOException) LoadPropertiesException(org.apache.camel.util.LoadPropertiesException) NoSuchEndpointException(org.apache.camel.NoSuchEndpointException) ResolveEndpointFailedException(org.apache.camel.ResolveEndpointFailedException) NoFactoryAvailableException(org.apache.camel.NoFactoryAvailableException) FailedToStartRouteException(org.apache.camel.FailedToStartRouteException) RouteDefinition(org.apache.camel.model.RouteDefinition) LifecycleStrategy(org.apache.camel.spi.LifecycleStrategy) VetoCamelContextStartException(org.apache.camel.VetoCamelContextStartException) EventNotifier(org.apache.camel.spi.EventNotifier) HandleFault(org.apache.camel.processor.interceptor.HandleFault) PropertiesComponent(org.apache.camel.component.properties.PropertiesComponent) Component(org.apache.camel.Component) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) PropertiesComponent(org.apache.camel.component.properties.PropertiesComponent) Debug(org.apache.camel.processor.interceptor.Debug)

Example 12 with LifecycleStrategy

use of org.apache.camel.spi.LifecycleStrategy in project camel by apache.

the class DefaultCamelContext method removeEndpoints.

public Collection<Endpoint> removeEndpoints(String uri) throws Exception {
    Collection<Endpoint> answer = new ArrayList<Endpoint>();
    Endpoint oldEndpoint = endpoints.remove(getEndpointKey(uri));
    if (oldEndpoint != null) {
        answer.add(oldEndpoint);
        stopServices(oldEndpoint);
    } else {
        for (Map.Entry<EndpointKey, Endpoint> entry : endpoints.entrySet()) {
            oldEndpoint = entry.getValue();
            if (EndpointHelper.matchEndpoint(this, oldEndpoint.getEndpointUri(), uri)) {
                try {
                    stopServices(oldEndpoint);
                } catch (Exception e) {
                    log.warn("Error stopping endpoint " + oldEndpoint + ". This exception will be ignored.", e);
                }
                answer.add(oldEndpoint);
                endpoints.remove(entry.getKey());
            }
        }
    }
    // notify lifecycle its being removed
    for (Endpoint endpoint : answer) {
        for (LifecycleStrategy strategy : lifecycleStrategies) {
            strategy.onEndpointRemove(endpoint);
        }
    }
    return answer;
}
Also used : Endpoint(org.apache.camel.Endpoint) LifecycleStrategy(org.apache.camel.spi.LifecycleStrategy) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) RuntimeCamelException(org.apache.camel.RuntimeCamelException) MalformedObjectNameException(javax.management.MalformedObjectNameException) VetoCamelContextStartException(org.apache.camel.VetoCamelContextStartException) IOException(java.io.IOException) LoadPropertiesException(org.apache.camel.util.LoadPropertiesException) NoSuchEndpointException(org.apache.camel.NoSuchEndpointException) ResolveEndpointFailedException(org.apache.camel.ResolveEndpointFailedException) NoFactoryAvailableException(org.apache.camel.NoFactoryAvailableException) FailedToStartRouteException(org.apache.camel.FailedToStartRouteException)

Example 13 with LifecycleStrategy

use of org.apache.camel.spi.LifecycleStrategy in project camel by apache.

the class CamelAutoConfiguration method afterPropertiesSet.

/**
     * Performs additional configuration to lookup beans of Camel types to configure
     * advanced configurations.
     * <p/>
     * Similar code in camel-core-xml module in class org.apache.camel.core.xml.AbstractCamelContextFactoryBean.
     */
void afterPropertiesSet(ApplicationContext applicationContext, CamelContext camelContext) {
    Tracer tracer = getSingleBeanOfType(applicationContext, Tracer.class);
    if (tracer != null) {
        // use formatter if there is a TraceFormatter bean defined
        TraceFormatter formatter = getSingleBeanOfType(applicationContext, TraceFormatter.class);
        if (formatter != null) {
            tracer.setFormatter(formatter);
        }
        LOG.info("Using custom Tracer: {}", tracer);
        camelContext.addInterceptStrategy(tracer);
    }
    BacklogTracer backlogTracer = getSingleBeanOfType(applicationContext, BacklogTracer.class);
    if (backlogTracer != null) {
        LOG.info("Using custom BacklogTracer: {}", backlogTracer);
        camelContext.addInterceptStrategy(backlogTracer);
    }
    HandleFault handleFault = getSingleBeanOfType(applicationContext, HandleFault.class);
    if (handleFault != null) {
        LOG.info("Using custom HandleFault: {}", handleFault);
        camelContext.addInterceptStrategy(handleFault);
    }
    InflightRepository inflightRepository = getSingleBeanOfType(applicationContext, InflightRepository.class);
    if (inflightRepository != null) {
        LOG.info("Using custom InflightRepository: {}", inflightRepository);
        camelContext.setInflightRepository(inflightRepository);
    }
    AsyncProcessorAwaitManager asyncProcessorAwaitManager = getSingleBeanOfType(applicationContext, AsyncProcessorAwaitManager.class);
    if (asyncProcessorAwaitManager != null) {
        LOG.info("Using custom AsyncProcessorAwaitManager: {}", asyncProcessorAwaitManager);
        camelContext.setAsyncProcessorAwaitManager(asyncProcessorAwaitManager);
    }
    ManagementStrategy managementStrategy = getSingleBeanOfType(applicationContext, ManagementStrategy.class);
    if (managementStrategy != null) {
        LOG.info("Using custom ManagementStrategy: {}", managementStrategy);
        camelContext.setManagementStrategy(managementStrategy);
    }
    ManagementNamingStrategy managementNamingStrategy = getSingleBeanOfType(applicationContext, ManagementNamingStrategy.class);
    if (managementNamingStrategy != null) {
        LOG.info("Using custom ManagementNamingStrategy: {}", managementNamingStrategy);
        camelContext.getManagementStrategy().setManagementNamingStrategy(managementNamingStrategy);
    }
    EventFactory eventFactory = getSingleBeanOfType(applicationContext, EventFactory.class);
    if (eventFactory != null) {
        LOG.info("Using custom EventFactory: {}", eventFactory);
        camelContext.getManagementStrategy().setEventFactory(eventFactory);
    }
    UnitOfWorkFactory unitOfWorkFactory = getSingleBeanOfType(applicationContext, UnitOfWorkFactory.class);
    if (unitOfWorkFactory != null) {
        LOG.info("Using custom UnitOfWorkFactory: {}", unitOfWorkFactory);
        camelContext.setUnitOfWorkFactory(unitOfWorkFactory);
    }
    RuntimeEndpointRegistry runtimeEndpointRegistry = getSingleBeanOfType(applicationContext, RuntimeEndpointRegistry.class);
    if (runtimeEndpointRegistry != null) {
        LOG.info("Using custom RuntimeEndpointRegistry: {}", runtimeEndpointRegistry);
        camelContext.setRuntimeEndpointRegistry(runtimeEndpointRegistry);
    }
    // custom type converters defined as <bean>s
    Map<String, TypeConverters> typeConverters = applicationContext.getBeansOfType(TypeConverters.class);
    if (typeConverters != null && !typeConverters.isEmpty()) {
        for (Map.Entry<String, TypeConverters> entry : typeConverters.entrySet()) {
            TypeConverters converter = entry.getValue();
            LOG.info("Adding custom TypeConverters with id: {} and implementation: {}", entry.getKey(), converter);
            camelContext.getTypeConverterRegistry().addTypeConverters(converter);
        }
    }
    // set the event notifier strategies if defined
    Map<String, EventNotifier> eventNotifiers = applicationContext.getBeansOfType(EventNotifier.class);
    if (eventNotifiers != null && !eventNotifiers.isEmpty()) {
        for (Map.Entry<String, EventNotifier> entry : eventNotifiers.entrySet()) {
            EventNotifier notifier = entry.getValue();
            // do not add if already added, for instance a tracer that is also an InterceptStrategy class
            if (!camelContext.getManagementStrategy().getEventNotifiers().contains(notifier)) {
                LOG.info("Using custom EventNotifier with id: {} and implementation: {}", entry.getKey(), notifier);
                camelContext.getManagementStrategy().addEventNotifier(notifier);
            }
        }
    }
    // set endpoint strategies if defined
    Map<String, EndpointStrategy> endpointStrategies = applicationContext.getBeansOfType(EndpointStrategy.class);
    if (endpointStrategies != null && !endpointStrategies.isEmpty()) {
        for (Map.Entry<String, EndpointStrategy> entry : endpointStrategies.entrySet()) {
            EndpointStrategy strategy = entry.getValue();
            LOG.info("Using custom EndpointStrategy with id: {} and implementation: {}", entry.getKey(), strategy);
            camelContext.addRegisterEndpointCallback(strategy);
        }
    }
    // shutdown
    ShutdownStrategy shutdownStrategy = getSingleBeanOfType(applicationContext, ShutdownStrategy.class);
    if (shutdownStrategy != null) {
        LOG.info("Using custom ShutdownStrategy: " + shutdownStrategy);
        camelContext.setShutdownStrategy(shutdownStrategy);
    }
    // add global interceptors
    Map<String, InterceptStrategy> interceptStrategies = applicationContext.getBeansOfType(InterceptStrategy.class);
    if (interceptStrategies != null && !interceptStrategies.isEmpty()) {
        for (Map.Entry<String, InterceptStrategy> entry : interceptStrategies.entrySet()) {
            InterceptStrategy strategy = entry.getValue();
            // do not add if already added, for instance a tracer that is also an InterceptStrategy class
            if (!camelContext.getInterceptStrategies().contains(strategy)) {
                LOG.info("Using custom InterceptStrategy with id: {} and implementation: {}", entry.getKey(), strategy);
                camelContext.addInterceptStrategy(strategy);
            }
        }
    }
    // set the lifecycle strategy if defined
    Map<String, LifecycleStrategy> lifecycleStrategies = applicationContext.getBeansOfType(LifecycleStrategy.class);
    if (lifecycleStrategies != null && !lifecycleStrategies.isEmpty()) {
        for (Map.Entry<String, LifecycleStrategy> entry : lifecycleStrategies.entrySet()) {
            LifecycleStrategy strategy = entry.getValue();
            // do not add if already added, for instance a tracer that is also an InterceptStrategy class
            if (!camelContext.getLifecycleStrategies().contains(strategy)) {
                LOG.info("Using custom LifecycleStrategy with id: {} and implementation: {}", entry.getKey(), strategy);
                camelContext.addLifecycleStrategy(strategy);
            }
        }
    }
    // add route policy factories
    Map<String, RoutePolicyFactory> routePolicyFactories = applicationContext.getBeansOfType(RoutePolicyFactory.class);
    if (routePolicyFactories != null && !routePolicyFactories.isEmpty()) {
        for (Map.Entry<String, RoutePolicyFactory> entry : routePolicyFactories.entrySet()) {
            RoutePolicyFactory factory = entry.getValue();
            LOG.info("Using custom RoutePolicyFactory with id: {} and implementation: {}", entry.getKey(), factory);
            camelContext.addRoutePolicyFactory(factory);
        }
    }
    // set the default thread pool profile if defined
    initThreadPoolProfiles(applicationContext, camelContext);
}
Also used : InflightRepository(org.apache.camel.spi.InflightRepository) UnitOfWorkFactory(org.apache.camel.spi.UnitOfWorkFactory) TypeConverters(org.apache.camel.TypeConverters) EndpointStrategy(org.apache.camel.spi.EndpointStrategy) EventNotifier(org.apache.camel.spi.EventNotifier) RoutePolicyFactory(org.apache.camel.spi.RoutePolicyFactory) TraceFormatter(org.apache.camel.processor.interceptor.TraceFormatter) DefaultTraceFormatter(org.apache.camel.processor.interceptor.DefaultTraceFormatter) BacklogTracer(org.apache.camel.processor.interceptor.BacklogTracer) ManagementStrategy(org.apache.camel.spi.ManagementStrategy) ShutdownStrategy(org.apache.camel.spi.ShutdownStrategy) Tracer(org.apache.camel.processor.interceptor.Tracer) BacklogTracer(org.apache.camel.processor.interceptor.BacklogTracer) EventFactory(org.apache.camel.spi.EventFactory) AsyncProcessorAwaitManager(org.apache.camel.spi.AsyncProcessorAwaitManager) InterceptStrategy(org.apache.camel.spi.InterceptStrategy) ManagementNamingStrategy(org.apache.camel.spi.ManagementNamingStrategy) LifecycleStrategy(org.apache.camel.spi.LifecycleStrategy) RuntimeEndpointRegistry(org.apache.camel.spi.RuntimeEndpointRegistry) HandleFault(org.apache.camel.processor.interceptor.HandleFault) Map(java.util.Map)

Example 14 with LifecycleStrategy

use of org.apache.camel.spi.LifecycleStrategy in project camel by apache.

the class ManagedNonManagedServiceTest method testNonManagedService.

public void testNonManagedService() throws Exception {
    // JMX tests dont work well on AIX CI servers (hangs them)
    if (isPlatform("aix")) {
        return;
    }
    // must enable always as CamelContext has been started
    // and we add the service manually below
    context.getManagementStrategy().getManagementAgent().setRegisterAlways(true);
    MyNonService service = new MyNonService();
    for (LifecycleStrategy strategy : context.getLifecycleStrategies()) {
        strategy.onServiceAdd(context, service, null);
    }
    MBeanServer mbeanServer = getMBeanServer();
    Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=services,*"), null);
    assertEquals(11, set.size());
}
Also used : LifecycleStrategy(org.apache.camel.spi.LifecycleStrategy) MBeanServer(javax.management.MBeanServer) ObjectName(javax.management.ObjectName)

Example 15 with LifecycleStrategy

use of org.apache.camel.spi.LifecycleStrategy in project camel by apache.

the class ManagedNonManagedServiceTest method testService.

public void testService() throws Exception {
    // JMX tests dont work well on AIX CI servers (hangs them)
    if (isPlatform("aix")) {
        return;
    }
    // must enable always as CamelContext has been started
    // and we add the service manually below
    context.getManagementStrategy().getManagementAgent().setRegisterAlways(true);
    MyService service = new MyService();
    for (LifecycleStrategy strategy : context.getLifecycleStrategies()) {
        strategy.onServiceAdd(context, service, null);
    }
    MBeanServer mbeanServer = getMBeanServer();
    Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=services,*"), null);
    assertEquals(12, set.size());
}
Also used : LifecycleStrategy(org.apache.camel.spi.LifecycleStrategy) MBeanServer(javax.management.MBeanServer) ObjectName(javax.management.ObjectName)

Aggregations

LifecycleStrategy (org.apache.camel.spi.LifecycleStrategy)20 Service (org.apache.camel.Service)8 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 Endpoint (org.apache.camel.Endpoint)4 Route (org.apache.camel.Route)4 HandleFault (org.apache.camel.processor.interceptor.HandleFault)4 EventNotifier (org.apache.camel.spi.EventNotifier)4 LinkedHashMap (java.util.LinkedHashMap)3 TreeMap (java.util.TreeMap)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)3 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)3 Consumer (org.apache.camel.Consumer)3 FailedToStartRouteException (org.apache.camel.FailedToStartRouteException)3 NoSuchEndpointException (org.apache.camel.NoSuchEndpointException)3 RoutePolicy (org.apache.camel.spi.RoutePolicy)3 IOException (java.io.IOException)2 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)2