Search in sources :

Example 16 with RouteDefinition

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

the class RouteScopedErrorHandlerAndOnExceptionTest method testErrorHandler.

public void testErrorHandler() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("seda:*").skipSendToOriginalEndpoint().throwException(new FileNotFoundException("Forced"));
        }
    });
    getMockEndpoint("mock:local").expectedMessageCount(1);
    getMockEndpoint("mock:seda").expectedMessageCount(0);
    getMockEndpoint("mock:exhausted").expectedMessageCount(0);
    template.sendBody("direct:start", "Hello World");
    assertMockEndpointsSatisfied();
}
Also used : RouteDefinition(org.apache.camel.model.RouteDefinition) RouteBuilder(org.apache.camel.builder.RouteBuilder) FileNotFoundException(java.io.FileNotFoundException) CamelExecutionException(org.apache.camel.CamelExecutionException) ConnectException(java.net.ConnectException) FileNotFoundException(java.io.FileNotFoundException)

Example 17 with RouteDefinition

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

the class StopRouteImpactsErrorHandlerTest method testIssue.

public void testIssue() throws Exception {
    RouteDefinition testRoute = context.getRouteDefinition("TestRoute");
    testRoute.adviceWith(context, new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("seda:*").skipSendToOriginalEndpoint().to("log:seda").throwException(new IllegalArgumentException("Forced"));
        }
    });
    RouteDefinition smtpRoute = context.getRouteDefinition("smtpRoute");
    smtpRoute.adviceWith(context, new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("smtp*").to("log:smtp").skipSendToOriginalEndpoint().to("mock:smtp");
        }
    });
    // we should fail and end up sending to smtp
    getMockEndpoint("mock:smtp").expectedMessageCount(1);
    // stopping a route after advice with causes problem with error handlers
    context.stopRoute("pollRoute");
    template.sendBody("direct:start", "Hello World");
    assertMockEndpointsSatisfied();
}
Also used : RouteDefinition(org.apache.camel.model.RouteDefinition) RouteBuilder(org.apache.camel.builder.RouteBuilder)

Example 18 with RouteDefinition

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

the class RouteScopedOnExceptionWithInterceptSendToEndpointIssueWithPredicateTest method testIssue.

public void testIssue() throws Exception {
    final Predicate fail = PredicateBuilder.or(header(Exchange.REDELIVERY_COUNTER).isNull(), header(Exchange.REDELIVERY_COUNTER).isLessThan(5));
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("seda:*").skipSendToOriginalEndpoint().process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    invoked.incrementAndGet();
                    if (fail.matches(exchange)) {
                        throw new ConnectException("Forced");
                    }
                }
            }).to("mock:ok");
        }
    });
    getMockEndpoint("mock:global").expectedMessageCount(0);
    getMockEndpoint("mock:ok").expectedMessageCount(1);
    getMockEndpoint("mock:exhausted").expectedMessageCount(0);
    template.sendBody("direct:start", "Hello World");
    assertMockEndpointsSatisfied();
    // 5 retry + 1 ok
    assertEquals(6, invoked.get());
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) RouteDefinition(org.apache.camel.model.RouteDefinition) RouteBuilder(org.apache.camel.builder.RouteBuilder) ConnectException(java.net.ConnectException) Predicate(org.apache.camel.Predicate) ConnectException(java.net.ConnectException)

Example 19 with RouteDefinition

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

the class DefaultExecutorServiceManager method onThreadPoolCreated.

/**
     * Invoked when a new thread pool is created.
     * This implementation will invoke the {@link LifecycleStrategy#onThreadPoolAdd(org.apache.camel.CamelContext,
     * java.util.concurrent.ThreadPoolExecutor, String, String, String, String) LifecycleStrategy.onThreadPoolAdd} method,
     * which for example will enlist the thread pool in JMX management.
     *
     * @param executorService the thread pool
     * @param source          the source to use the thread pool
     * @param threadPoolProfileId profile id, if the thread pool was created from a thread pool profile
     */
private void onThreadPoolCreated(ExecutorService executorService, Object source, String threadPoolProfileId) {
    // add to internal list of thread pools
    executorServices.add(executorService);
    String id;
    String sourceId = null;
    String routeId = null;
    // extract id from source
    if (source instanceof NamedNode) {
        id = ((OptionalIdentifiedDefinition<?>) source).idOrCreate(this.camelContext.getNodeIdFactory());
        // and let source be the short name of the pattern
        sourceId = ((NamedNode) source).getShortName();
    } else if (source instanceof String) {
        id = (String) source;
    } else if (source != null) {
        if (source instanceof StaticService) {
            // the source is static service so its name would be unique
            id = source.getClass().getSimpleName();
        } else {
            // fallback and use the simple class name with hashcode for the id so its unique for this given source
            id = source.getClass().getSimpleName() + "(" + ObjectHelper.getIdentityHashCode(source) + ")";
        }
    } else {
        // no source, so fallback and use the simple class name from thread pool and its hashcode identity so its unique
        id = executorService.getClass().getSimpleName() + "(" + ObjectHelper.getIdentityHashCode(executorService) + ")";
    }
    // id is mandatory
    ObjectHelper.notEmpty(id, "id for thread pool " + executorService);
    // extract route id if possible
    if (source instanceof ProcessorDefinition) {
        RouteDefinition route = ProcessorDefinitionHelper.getRoute((ProcessorDefinition<?>) source);
        if (route != null) {
            routeId = route.idOrCreate(this.camelContext.getNodeIdFactory());
        }
    }
    // let lifecycle strategy be notified as well which can let it be managed in JMX as well
    ThreadPoolExecutor threadPool = null;
    if (executorService instanceof ThreadPoolExecutor) {
        threadPool = (ThreadPoolExecutor) executorService;
    } else if (executorService instanceof SizedScheduledExecutorService) {
        threadPool = ((SizedScheduledExecutorService) executorService).getScheduledThreadPoolExecutor();
    }
    if (threadPool != null) {
        for (LifecycleStrategy lifecycle : camelContext.getLifecycleStrategies()) {
            lifecycle.onThreadPoolAdd(camelContext, threadPool, id, sourceId, routeId, threadPoolProfileId);
        }
    }
    // now call strategy to allow custom logic
    onNewExecutorService(executorService);
}
Also used : SizedScheduledExecutorService(org.apache.camel.util.concurrent.SizedScheduledExecutorService) RouteDefinition(org.apache.camel.model.RouteDefinition) LifecycleStrategy(org.apache.camel.spi.LifecycleStrategy) ProcessorDefinition(org.apache.camel.model.ProcessorDefinition) NamedNode(org.apache.camel.NamedNode) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) StaticService(org.apache.camel.StaticService)

Example 20 with RouteDefinition

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

the class DefaultExceptionPolicyStrategy method findMatchedExceptionPolicy.

private boolean findMatchedExceptionPolicy(Map<ExceptionPolicyKey, OnExceptionDefinition> exceptionPolicies, Exchange exchange, Throwable exception, Map<Integer, OnExceptionDefinition> candidates) {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Finding best suited exception policy for thrown exception {}", exception.getClass().getName());
    }
    // the goal is to find the exception with the same/closet inheritance level as the target exception being thrown
    int targetLevel = getInheritanceLevel(exception.getClass());
    // candidate is the best candidate found so far to return
    OnExceptionDefinition candidate = null;
    // difference in inheritance level between the current candidate and the thrown exception (target level)
    int candidateDiff = Integer.MAX_VALUE;
    // loop through all the entries and find the best candidates to use
    Set<Map.Entry<ExceptionPolicyKey, OnExceptionDefinition>> entries = exceptionPolicies.entrySet();
    for (Map.Entry<ExceptionPolicyKey, OnExceptionDefinition> entry : entries) {
        Class<?> clazz = entry.getKey().getExceptionClass();
        OnExceptionDefinition type = entry.getValue();
        // so we will not pick an OnException from another route
        if (exchange != null && exchange.getUnitOfWork() != null && type.isRouteScoped()) {
            RouteDefinition route = exchange.getUnitOfWork().getRouteContext() != null ? exchange.getUnitOfWork().getRouteContext().getRoute() : null;
            RouteDefinition typeRoute = ProcessorDefinitionHelper.getRoute(type);
            if (route != null && typeRoute != null && route != typeRoute) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("The type is scoped for route: {} however Exchange is at route: {}", typeRoute.getId(), route.getId());
                }
                continue;
            }
        }
        if (filter(type, clazz, exception)) {
            // must match
            if (!matchesWhen(type, exchange)) {
                LOG.trace("The type did not match when: {}", type);
                continue;
            }
            // exact match then break
            if (clazz.equals(exception.getClass())) {
                candidate = type;
                candidateDiff = 0;
                break;
            }
            // not an exact match so find the best candidate
            int level = getInheritanceLevel(clazz);
            int diff = targetLevel - level;
            if (diff < candidateDiff) {
                // replace with a much better candidate
                candidate = type;
                candidateDiff = diff;
            }
        }
    }
    if (candidate != null) {
        if (!candidates.containsKey(candidateDiff)) {
            // only add as candidate if we do not already have it registered with that level
            LOG.trace("Adding {} as candidate at level {}", candidate, candidateDiff);
            candidates.put(candidateDiff, candidate);
        } else {
            // for example we check route scope before context scope (preferring route scopes)
            if (LOG.isTraceEnabled()) {
                LOG.trace("Existing candidate {} takes precedence over{} at level {}", new Object[] { candidates.get(candidateDiff), candidate, candidateDiff });
            }
        }
    }
    // if we found a exact match then we should stop continue looking
    boolean exactMatch = candidateDiff == 0;
    if (LOG.isTraceEnabled() && exactMatch) {
        LOG.trace("Exact match found for candidate: {}", candidate);
    }
    return exactMatch;
}
Also used : RouteDefinition(org.apache.camel.model.RouteDefinition) OnExceptionDefinition(org.apache.camel.model.OnExceptionDefinition) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) Map(java.util.Map)

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