Search in sources :

Example 1 with CamelContextAware

use of org.apache.camel.CamelContextAware in project camel by apache.

the class CxfJavaOnlyCamelContextAwareTest method testCxfEndpointHasCamelContext.

@Test
public void testCxfEndpointHasCamelContext() throws Exception {
    String s = "<GetPerson xmlns=\"http://camel.apache.org/wsdl-first/types\"><personId>123</personId></GetPerson>";
    Document xml = context.getTypeConverter().convertTo(Document.class, s);
    log.info("Endpoints: {}", context.getEndpoints());
    Object output = template.requestBody("personService", xml);
    assertNotNull(output);
    // using CxfPayload in payload mode
    CxfPayload<?> payload = (CxfPayload<?>) output;
    // convert the payload body to string
    String reply = context.getTypeConverter().convertTo(String.class, payload.getBody().get(0));
    assertNotNull(reply);
    assertTrue(reply.contains("<personId>123</personId"));
    assertTrue(reply.contains("<ssn>456</ssn"));
    assertTrue(reply.contains("<name>Donald Duck</name"));
    assertTrue(context.getEndpoint("personService") instanceof CamelContextAware);
    assertNotNull("CamelContext should be set on CxfEndpoint", context.getEndpoint("personService").getCamelContext());
}
Also used : CamelContextAware(org.apache.camel.CamelContextAware) Document(org.w3c.dom.Document) Test(org.junit.Test)

Example 2 with CamelContextAware

use of org.apache.camel.CamelContextAware in project camel by apache.

the class ServiceCallDefinition method createProcessor.

// *****************************
// Processor Factory
// *****************************
@Override
public Processor createProcessor(RouteContext routeContext) throws Exception {
    final CamelContext camelContext = routeContext.getCamelContext();
    final ServiceDiscovery serviceDiscovery = retrieveServiceDiscovery(camelContext);
    final ServiceFilter serviceFilter = retrieveServiceFilter(camelContext);
    final ServiceChooser serviceChooser = retrieveServiceChooser(camelContext);
    final LoadBalancer loadBalancer = retrieveLoadBalancer(camelContext);
    final Expression expression = retrieveExpression(camelContext);
    if (loadBalancer instanceof CamelContextAware) {
        ((CamelContextAware) loadBalancer).setCamelContext(camelContext);
    }
    if (loadBalancer instanceof ServiceDiscoveryAware) {
        ((ServiceDiscoveryAware) loadBalancer).setServiceDiscovery(serviceDiscovery);
    }
    if (loadBalancer instanceof ServiceFilterAware) {
        ((ServiceFilterAware) loadBalancer).setServiceFilter(serviceFilter);
    }
    if (loadBalancer instanceof ServiceChooserAware) {
        ((ServiceChooserAware) loadBalancer).setServiceChooser(serviceChooser);
    }
    // The component is used to configure the default scheme to use (eg camel component name).
    // The component configured on EIP takes precedence vs configured on configuration.
    String component = this.component;
    if (component == null) {
        ServiceCallConfigurationDefinition conf = retrieveConfig(camelContext);
        if (conf != null) {
            component = conf.getComponent();
        }
    }
    if (component == null) {
        ServiceCallConfigurationDefinition conf = retrieveDefaultConfig(camelContext);
        if (conf != null) {
            component = conf.getComponent();
        }
    }
    return new DefaultServiceCallProcessor(camelContext, name, component, uri, pattern, loadBalancer, expression);
}
Also used : CamelContext(org.apache.camel.CamelContext) PassThroughServiceFilter(org.apache.camel.impl.cloud.PassThroughServiceFilter) ServiceFilter(org.apache.camel.cloud.ServiceFilter) HealthyServiceFilter(org.apache.camel.impl.cloud.HealthyServiceFilter) CamelContextAware(org.apache.camel.CamelContextAware) ServiceDiscoveryAware(org.apache.camel.cloud.ServiceDiscoveryAware) ServiceChooserAware(org.apache.camel.cloud.ServiceChooserAware) DefaultServiceCallProcessor(org.apache.camel.impl.cloud.DefaultServiceCallProcessor) DefaultLoadBalancer(org.apache.camel.impl.cloud.DefaultLoadBalancer) LoadBalancer(org.apache.camel.cloud.LoadBalancer) ServiceFilterAware(org.apache.camel.cloud.ServiceFilterAware) ServiceChooser(org.apache.camel.cloud.ServiceChooser) RoundRobinServiceChooser(org.apache.camel.impl.cloud.RoundRobinServiceChooser) RandomServiceChooser(org.apache.camel.impl.cloud.RandomServiceChooser) DefaultServiceCallExpression(org.apache.camel.impl.cloud.DefaultServiceCallExpression) Expression(org.apache.camel.Expression) ServiceDiscovery(org.apache.camel.cloud.ServiceDiscovery)

Example 3 with CamelContextAware

use of org.apache.camel.CamelContextAware in project camel by apache.

the class DefaultChannel method initChannel.

@SuppressWarnings("deprecation")
public void initChannel(ProcessorDefinition<?> outputDefinition, RouteContext routeContext) throws Exception {
    this.routeContext = routeContext;
    this.definition = outputDefinition;
    this.camelContext = routeContext.getCamelContext();
    Processor target = nextProcessor;
    Processor next;
    // init CamelContextAware as early as possible on target
    if (target instanceof CamelContextAware) {
        ((CamelContextAware) target).setCamelContext(camelContext);
    }
    // the definition to wrap should be the fine grained,
    // so if a child is set then use it, if not then its the original output used
    ProcessorDefinition<?> targetOutputDef = childDefinition != null ? childDefinition : outputDefinition;
    LOG.debug("Initialize channel for target: '{}'", targetOutputDef);
    // ideally we need the design time route -> runtime route to be a 2-phase pass (scheduled work for Camel 3.0)
    if (childDefinition != null && outputDefinition != childDefinition) {
        childDefinition.setParent(outputDefinition);
    }
    // force the creation of an id
    RouteDefinitionHelper.forceAssignIds(routeContext.getCamelContext(), definition);
    // first wrap the output with the managed strategy if any
    InterceptStrategy managed = routeContext.getManagedInterceptStrategy();
    if (managed != null) {
        next = target == nextProcessor ? null : nextProcessor;
        target = managed.wrapProcessorInInterceptors(routeContext.getCamelContext(), targetOutputDef, target, next);
    }
    // then wrap the output with the backlog and tracer (backlog first, as we do not want regular tracer to tracer the backlog)
    InterceptStrategy tracer = getOrCreateBacklogTracer();
    camelContext.addService(tracer);
    if (tracer instanceof BacklogTracer) {
        BacklogTracer backlogTracer = (BacklogTracer) tracer;
        RouteDefinition route = ProcessorDefinitionHelper.getRoute(definition);
        boolean first = false;
        if (route != null && !route.getOutputs().isEmpty()) {
            first = route.getOutputs().get(0) == definition;
        }
        addAdvice(new BacklogTracerAdvice(backlogTracer, targetOutputDef, route, first));
        // add debugger as well so we have both tracing and debugging out of the box
        InterceptStrategy debugger = getOrCreateBacklogDebugger();
        camelContext.addService(debugger);
        if (debugger instanceof BacklogDebugger) {
            BacklogDebugger backlogDebugger = (BacklogDebugger) debugger;
            addAdvice(new BacklogDebuggerAdvice(backlogDebugger, target, targetOutputDef));
        }
    }
    if (routeContext.isMessageHistory()) {
        // add message history advice
        MessageHistoryFactory factory = camelContext.getMessageHistoryFactory();
        addAdvice(new MessageHistoryAdvice(factory, targetOutputDef));
    }
    // the regular tracer is not a task on internalProcessor as this is not really needed
    // end users have to explicit enable the tracer to use it, and then its okay if we wrap
    // the processors (but by default tracer is disabled, and therefore we do not wrap processors)
    tracer = getOrCreateTracer();
    camelContext.addService(tracer);
    if (tracer != null) {
        TraceInterceptor trace = (TraceInterceptor) tracer.wrapProcessorInInterceptors(routeContext.getCamelContext(), targetOutputDef, target, null);
        // trace interceptor need to have a reference to route context so we at runtime can enable/disable tracing on-the-fly
        trace.setRouteContext(routeContext);
        target = trace;
    }
    // sort interceptors according to ordered
    interceptors.sort(new OrderedComparator());
    // then reverse list so the first will be wrapped last, as it would then be first being invoked
    Collections.reverse(interceptors);
    // wrap the output with the configured interceptors
    for (InterceptStrategy strategy : interceptors) {
        next = target == nextProcessor ? null : nextProcessor;
        // skip tracer as we did the specially beforehand and it could potentially be added as an interceptor strategy
        if (strategy instanceof Tracer) {
            continue;
        }
        // skip stream caching as it must be wrapped as outer most, which we do later
        if (strategy instanceof StreamCaching) {
            continue;
        }
        // use the fine grained definition (eg the child if available). Its always possible to get back to the parent
        Processor wrapped = strategy.wrapProcessorInInterceptors(routeContext.getCamelContext(), targetOutputDef, target, next);
        if (!(wrapped instanceof AsyncProcessor)) {
            LOG.warn("Interceptor: " + strategy + " at: " + outputDefinition + " does not return an AsyncProcessor instance." + " This causes the asynchronous routing engine to not work as optimal as possible." + " See more details at the InterceptStrategy javadoc." + " Camel will use a bridge to adapt the interceptor to the asynchronous routing engine," + " but its not the most optimal solution. Please consider changing your interceptor to comply.");
            // use a bridge and wrap again which allows us to adapt and leverage the asynchronous routing engine anyway
            // however its not the most optimal solution, but we can still run.
            InterceptorToAsyncProcessorBridge bridge = new InterceptorToAsyncProcessorBridge(target);
            wrapped = strategy.wrapProcessorInInterceptors(routeContext.getCamelContext(), targetOutputDef, bridge, next);
            // Avoid the stack overflow
            if (!wrapped.equals(bridge)) {
                bridge.setTarget(wrapped);
            } else {
                // Just skip the wrapped processor
                bridge.setTarget(null);
            }
            wrapped = bridge;
        }
        if (!(wrapped instanceof WrapProcessor)) {
            // wrap the target so it becomes a service and we can manage its lifecycle
            wrapped = new WrapProcessor(wrapped, target);
        }
        target = wrapped;
    }
    if (routeContext.isStreamCaching()) {
        addAdvice(new StreamCachingAdvice(camelContext.getStreamCachingStrategy()));
    }
    if (routeContext.getDelayer() != null && routeContext.getDelayer() > 0) {
        addAdvice(new DelayerAdvice(routeContext.getDelayer()));
    }
    // sets the delegate to our wrapped output
    output = target;
}
Also used : MessageHistoryFactory(org.apache.camel.spi.MessageHistoryFactory) CamelInternalProcessor(org.apache.camel.processor.CamelInternalProcessor) Processor(org.apache.camel.Processor) WrapProcessor(org.apache.camel.processor.WrapProcessor) AsyncProcessor(org.apache.camel.AsyncProcessor) CamelContextAware(org.apache.camel.CamelContextAware) InterceptorToAsyncProcessorBridge(org.apache.camel.processor.InterceptorToAsyncProcessorBridge) InterceptStrategy(org.apache.camel.spi.InterceptStrategy) RouteDefinition(org.apache.camel.model.RouteDefinition) WrapProcessor(org.apache.camel.processor.WrapProcessor) AsyncProcessor(org.apache.camel.AsyncProcessor) OrderedComparator(org.apache.camel.util.OrderedComparator)

Example 4 with CamelContextAware

use of org.apache.camel.CamelContextAware in project camel by apache.

the class AggregationStrategyBeanAdapter method doStart.

@Override
protected void doStart() throws Exception {
    Method found = null;
    if (methodName != null) {
        for (Method method : type.getMethods()) {
            if (isValidMethod(method) && method.getName().equals(methodName)) {
                if (found == null) {
                    found = method;
                } else {
                    throw new IllegalArgumentException("The bean " + type + " has 2 or more methods with the name " + methodName);
                }
            }
        }
    } else {
        for (Method method : type.getMethods()) {
            if (isValidMethod(method)) {
                if (found == null) {
                    found = method;
                } else {
                    throw new IllegalArgumentException("The bean " + type + " has 2 or more methods and no explicit method name was configured.");
                }
            }
        }
    }
    if (found == null) {
        throw new UnsupportedOperationException("Cannot find a valid method with name: " + methodName + " on bean type: " + type);
    }
    // if its not a static method then we must have an instance of the pojo
    if (!isStaticMethod(found) && pojo == null) {
        pojo = camelContext.getInjector().newInstance(type);
    }
    // create the method info which has adapted to the pojo
    AggregationStrategyBeanInfo bi = new AggregationStrategyBeanInfo(type, found);
    mi = bi.createMethodInfo();
    // in case the POJO is CamelContextAware
    if (pojo != null && pojo instanceof CamelContextAware) {
        ((CamelContextAware) pojo).setCamelContext(getCamelContext());
    }
    // in case the pojo is a service
    ServiceHelper.startService(pojo);
}
Also used : CamelContextAware(org.apache.camel.CamelContextAware) Method(java.lang.reflect.Method)

Example 5 with CamelContextAware

use of org.apache.camel.CamelContextAware 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)

Aggregations

CamelContextAware (org.apache.camel.CamelContextAware)82 HashMap (java.util.HashMap)70 ConditionalOnBean (org.springframework.boot.autoconfigure.condition.ConditionalOnBean)69 ConditionalOnClass (org.springframework.boot.autoconfigure.condition.ConditionalOnClass)69 ConditionalOnMissingBean (org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean)69 Bean (org.springframework.context.annotation.Bean)69 RuntimeCamelException (org.apache.camel.RuntimeCamelException)47 DataFormatFactory (org.apache.camel.spi.DataFormatFactory)45 Scope (org.springframework.context.annotation.Scope)24 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)3 CamelContext (org.apache.camel.CamelContext)3 Service (org.apache.camel.Service)3 StatefulService (org.apache.camel.StatefulService)3 SuspendableService (org.apache.camel.SuspendableService)3 IOException (java.io.IOException)2 MalformedObjectNameException (javax.management.MalformedObjectNameException)2 FailedToStartRouteException (org.apache.camel.FailedToStartRouteException)2 IsSingleton (org.apache.camel.IsSingleton)2 NoFactoryAvailableException (org.apache.camel.NoFactoryAvailableException)2 NoSuchEndpointException (org.apache.camel.NoSuchEndpointException)2