Search in sources :

Example 21 with RouteDefinition

use of org.apache.camel.model.RouteDefinition in project camel by apache.

the class BacklogTracer method shouldTracePattern.

private boolean shouldTracePattern(ProcessorDefinition<?> definition) {
    for (String pattern : patterns) {
        // match either route id, or node id
        String id = definition.getId();
        // use matchPattern method from endpoint helper that has a good matcher we use in Camel
        if (EndpointHelper.matchPattern(id, pattern)) {
            return true;
        }
        RouteDefinition route = ProcessorDefinitionHelper.getRoute(definition);
        if (route != null) {
            id = route.getId();
            if (EndpointHelper.matchPattern(id, pattern)) {
                return true;
            }
        }
    }
    // not matched the pattern
    return false;
}
Also used : RouteDefinition(org.apache.camel.model.RouteDefinition)

Example 22 with RouteDefinition

use of org.apache.camel.model.RouteDefinition 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 23 with RouteDefinition

use of org.apache.camel.model.RouteDefinition in project camel by apache.

the class StartAndStopRoutesTest method testStartRouteThenStopMutateAndStartRouteAgain.

public void testStartRouteThenStopMutateAndStartRouteAgain() throws Exception {
    List<RouteDefinition> routes = context.getRouteDefinitions();
    assertCollectionSize("Route", routes, 1);
    RouteDefinition route = routes.get(0);
    endpointA = getMandatoryEndpoint("seda:test.a", SedaEndpoint.class);
    endpointB = getMandatoryEndpoint("seda:test.b", SedaEndpoint.class);
    endpointC = getMandatoryEndpoint("seda:test.C", SedaEndpoint.class);
    // send from A over B to results
    MockEndpoint results = getMockEndpoint("mock:results");
    results.expectedBodiesReceived(expectedBody);
    template.sendBody(endpointA, expectedBody);
    assertMockEndpointsSatisfied();
    // stop the route
    context.stopRoute(route);
    // lets mutate the route...
    FromDefinition fromType = assertOneElement(route.getInputs());
    fromType.setUri("seda:test.C");
    context.startRoute(route);
    // now lets check it works
    // send from C over B to results
    results.reset();
    results = getMockEndpoint("mock:results");
    results.expectedBodiesReceived(expectedBody);
    template.sendBody(endpointC, expectedBody);
    assertMockEndpointsSatisfied();
}
Also used : FromDefinition(org.apache.camel.model.FromDefinition) RouteDefinition(org.apache.camel.model.RouteDefinition) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) SedaEndpoint(org.apache.camel.component.seda.SedaEndpoint)

Example 24 with RouteDefinition

use of org.apache.camel.model.RouteDefinition in project camel by apache.

the class BacklogTracerIdOnAllNodesTest method testBacklogTracerEventMessage.

@SuppressWarnings("unchecked")
public void testBacklogTracerEventMessage() throws Exception {
    // JMX tests dont work well on AIX CI servers (hangs them)
    if (isPlatform("aix")) {
        return;
    }
    MBeanServer mbeanServer = getMBeanServer();
    ObjectName on = new ObjectName("org.apache.camel:context=camel-1,type=tracer,name=BacklogTracer");
    assertNotNull(on);
    mbeanServer.isRegistered(on);
    Boolean enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled");
    assertEquals("Should not be enabled", Boolean.FALSE, enabled);
    Integer size = (Integer) mbeanServer.getAttribute(on, "BacklogSize");
    assertEquals("Should be 1000", 1000, size.intValue());
    // enable it
    mbeanServer.setAttribute(on, new Attribute("Enabled", Boolean.TRUE));
    getMockEndpoint("mock:camel").expectedBodiesReceived("Hello Camel");
    getMockEndpoint("mock:other").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:end").expectedMessageCount(2);
    template.sendBody("direct:start", "Hello Camel");
    template.sendBody("direct:start", "Hello World");
    assertMockEndpointsSatisfied();
    List<Exchange> fooExchanges = getMockEndpoint("mock:foo").getReceivedExchanges();
    List<Exchange> camelExchanges = getMockEndpoint("mock:camel").getReceivedExchanges();
    RouteDefinition route = context.getRouteDefinitions().get(0);
    assertNotNull(route);
    ChoiceDefinition choice = (ChoiceDefinition) route.getOutputs().get(0);
    assertEquals("choice1", choice.getId());
    WhenDefinition when = (WhenDefinition) choice.getOutputs().get(0);
    assertEquals("when1", when.getId());
    LogDefinition log1 = (LogDefinition) when.getOutputs().get(0);
    assertEquals("log1", log1.getId());
    ToDefinition to1 = (ToDefinition) when.getOutputs().get(1);
    assertEquals("camel", to1.getId());
    OtherwiseDefinition other = (OtherwiseDefinition) choice.getOutputs().get(1);
    assertEquals("otherwise1", other.getId());
    LogDefinition log2 = (LogDefinition) other.getOutputs().get(0);
    assertEquals("log2", log2.getId());
    ToDefinition to2 = (ToDefinition) other.getOutputs().get(1);
    assertEquals("to1", to2.getId());
    ToDefinition to3 = (ToDefinition) other.getOutputs().get(2);
    assertEquals("foo", to3.getId());
    ToDefinition to4 = (ToDefinition) route.getOutputs().get(1);
    assertEquals("end", to4.getId());
    List<BacklogTracerEventMessage> events = (List<BacklogTracerEventMessage>) mbeanServer.invoke(on, "dumpTracedMessages", new Object[] { "to1" }, new String[] { "java.lang.String" });
    assertNotNull(events);
    assertEquals(1, events.size());
    BacklogTracerEventMessage event1 = events.get(0);
    assertEquals("to1", event1.getToNode());
    assertEquals("    <message exchangeId=\"" + fooExchanges.get(0).getExchangeId() + "\">\n" + "      <body type=\"java.lang.String\">Hello World</body>\n" + "    </message>", event1.getMessageAsXml());
    events = (List<BacklogTracerEventMessage>) mbeanServer.invoke(on, "dumpTracedMessages", new Object[] { "camel" }, new String[] { "java.lang.String" });
    assertNotNull(events);
    assertEquals(1, events.size());
    event1 = events.get(0);
    assertEquals("camel", event1.getToNode());
    assertEquals("    <message exchangeId=\"" + camelExchanges.get(0).getExchangeId() + "\">\n" + "      <body type=\"java.lang.String\">Hello Camel</body>\n" + "    </message>", event1.getMessageAsXml());
}
Also used : ToDefinition(org.apache.camel.model.ToDefinition) BacklogTracerEventMessage(org.apache.camel.api.management.mbean.BacklogTracerEventMessage) Attribute(javax.management.Attribute) OtherwiseDefinition(org.apache.camel.model.OtherwiseDefinition) ObjectName(javax.management.ObjectName) Exchange(org.apache.camel.Exchange) RouteDefinition(org.apache.camel.model.RouteDefinition) ChoiceDefinition(org.apache.camel.model.ChoiceDefinition) List(java.util.List) LogDefinition(org.apache.camel.model.LogDefinition) WhenDefinition(org.apache.camel.model.WhenDefinition) MBeanServer(javax.management.MBeanServer)

Example 25 with RouteDefinition

use of org.apache.camel.model.RouteDefinition in project camel by apache.

the class RemoveRouteDefinitionTest method testStopRoute.

public void testStopRoute() throws Exception {
    // JMX tests dont work well on AIX CI servers (hangs them)
    if (isPlatform("aix")) {
        return;
    }
    MBeanServer mbeanServer = getMBeanServer();
    Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null);
    assertEquals(1, set.size());
    ObjectName on = set.iterator().next();
    boolean registered = mbeanServer.isRegistered(on);
    assertEquals("Should be registered", true, registered);
    RouteDefinition definition = context.getRouteDefinition("route1");
    List<RouteDefinition> routeDefinitions = new ArrayList<RouteDefinition>();
    routeDefinitions.add(definition);
    context.stopRoute("route1");
    // route is only stopped so its still in JMX
    set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null);
    assertEquals(1, set.size());
}
Also used : RouteDefinition(org.apache.camel.model.RouteDefinition) ArrayList(java.util.ArrayList) MBeanServer(javax.management.MBeanServer) ObjectName(javax.management.ObjectName)

Aggregations

RouteDefinition (org.apache.camel.model.RouteDefinition)102 AdviceWithRouteBuilder (org.apache.camel.builder.AdviceWithRouteBuilder)17 RouteBuilder (org.apache.camel.builder.RouteBuilder)17 Test (org.junit.Test)11 ArrayList (java.util.ArrayList)9 FromDefinition (org.apache.camel.model.FromDefinition)9 HashMap (java.util.HashMap)6 Processor (org.apache.camel.Processor)6 ConnectException (java.net.ConnectException)5 Exchange (org.apache.camel.Exchange)5 ProcessorDefinition (org.apache.camel.model.ProcessorDefinition)5 IOException (java.io.IOException)4 Map (java.util.Map)4 MBeanServer (javax.management.MBeanServer)4 ObjectName (javax.management.ObjectName)4 ChoiceDefinition (org.apache.camel.model.ChoiceDefinition)4 HystrixConfigurationDefinition (org.apache.camel.model.HystrixConfigurationDefinition)4 HystrixDefinition (org.apache.camel.model.HystrixDefinition)4 LogDefinition (org.apache.camel.model.LogDefinition)4 ModelCamelContext (org.apache.camel.model.ModelCamelContext)4