Search in sources :

Example 1 with OrderedComparator

use of org.apache.camel.util.OrderedComparator in project camel by apache.

the class CamelInternalProcessor method addAdvice.

/**
     * Adds an {@link CamelInternalProcessorAdvice} advice to the list of advices to execute by this internal processor.
     *
     * @param advice  the advice to add
     */
public void addAdvice(CamelInternalProcessorAdvice advice) {
    advices.add(advice);
    // ensure advices are sorted so they are in the order we want
    advices.sort(new OrderedComparator());
}
Also used : OrderedComparator(org.apache.camel.util.OrderedComparator)

Example 2 with OrderedComparator

use of org.apache.camel.util.OrderedComparator 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 3 with OrderedComparator

use of org.apache.camel.util.OrderedComparator in project camel by apache.

the class DefaultCamelContext method safelyStartRouteServices.

/**
     * Starts the routes services in a proper manner which ensures the routes will be started in correct order,
     * check for clash and that the routes will also be shutdown in correct order as well.
     * <p/>
     * This method <b>must</b> be used to start routes in a safe manner.
     *
     * @param checkClash     whether to check for startup order clash
     * @param startConsumer  whether the route consumer should be started. Can be used to warmup the route without starting the consumer.
     * @param resumeConsumer whether the route consumer should be resumed.
     * @param addingRoutes   whether we are adding new routes
     * @param routeServices  the routes
     * @throws Exception is thrown if error starting the routes
     */
protected synchronized void safelyStartRouteServices(boolean checkClash, boolean startConsumer, boolean resumeConsumer, boolean addingRoutes, Collection<RouteService> routeServices) throws Exception {
    // list of inputs to start when all the routes have been prepared for starting
    // we use a tree map so the routes will be ordered according to startup order defined on the route
    Map<Integer, DefaultRouteStartupOrder> inputs = new TreeMap<Integer, DefaultRouteStartupOrder>();
    // figure out the order in which the routes should be started
    for (RouteService routeService : routeServices) {
        DefaultRouteStartupOrder order = doPrepareRouteToBeStarted(routeService);
        // check for clash before we add it as input
        if (checkClash) {
            doCheckStartupOrderClash(order, inputs);
        }
        inputs.put(order.getStartupOrder(), order);
    }
    // warm up routes before we start them
    doWarmUpRoutes(inputs, startConsumer);
    // sort the startup listeners so they are started in the right order
    startupListeners.sort(new OrderedComparator());
    // (only the actual route consumer has not yet been started)
    for (StartupListener startup : startupListeners) {
        startup.onCamelContextStarted(this, isStarted());
    }
    // because the consumers may also register startup listeners we need to reset
    // the already started listeners
    List<StartupListener> backup = new ArrayList<>(startupListeners);
    startupListeners.clear();
    // now start the consumers
    if (startConsumer) {
        if (resumeConsumer) {
            // and now resume the routes
            doResumeRouteConsumers(inputs, addingRoutes);
        } else {
            // and now start the routes
            // and check for clash with multiple consumers of the same endpoints which is not allowed
            doStartRouteConsumers(inputs, addingRoutes);
        }
    }
    // sort the startup listeners so they are started in the right order
    startupListeners.sort(new OrderedComparator());
    // so we need to ensure they get started as well
    for (StartupListener startup : startupListeners) {
        startup.onCamelContextStarted(this, isStarted());
    }
    // and add the previous started startup listeners to the list so we have them all
    startupListeners.addAll(0, backup);
    // inputs no longer needed
    inputs.clear();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) OrderedComparator(org.apache.camel.util.OrderedComparator) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) TreeMap(java.util.TreeMap) StartupListener(org.apache.camel.StartupListener)

Aggregations

OrderedComparator (org.apache.camel.util.OrderedComparator)3 ArrayList (java.util.ArrayList)1 TreeMap (java.util.TreeMap)1 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 AsyncProcessor (org.apache.camel.AsyncProcessor)1 CamelContextAware (org.apache.camel.CamelContextAware)1 Processor (org.apache.camel.Processor)1 StartupListener (org.apache.camel.StartupListener)1 RouteDefinition (org.apache.camel.model.RouteDefinition)1 CamelInternalProcessor (org.apache.camel.processor.CamelInternalProcessor)1 InterceptorToAsyncProcessorBridge (org.apache.camel.processor.InterceptorToAsyncProcessorBridge)1 WrapProcessor (org.apache.camel.processor.WrapProcessor)1 InterceptStrategy (org.apache.camel.spi.InterceptStrategy)1 MessageHistoryFactory (org.apache.camel.spi.MessageHistoryFactory)1