Search in sources :

Example 31 with RouteDefinition

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

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

the class DefaultCamelContext method createRouteStaticEndpointJson.

public String createRouteStaticEndpointJson(String routeId, boolean includeDynamic) {
    List<RouteDefinition> routes = new ArrayList<RouteDefinition>();
    if (routeId != null) {
        RouteDefinition route = getRouteDefinition(routeId);
        if (route == null) {
            throw new IllegalArgumentException("Route with id " + routeId + " does not exist");
        }
        routes.add(route);
    } else {
        routes.addAll(getRouteDefinitions());
    }
    StringBuilder buffer = new StringBuilder("{\n  \"routes\": {");
    boolean firstRoute = true;
    for (RouteDefinition route : routes) {
        if (!firstRoute) {
            buffer.append("\n    },");
        } else {
            firstRoute = false;
        }
        String id = route.getId();
        buffer.append("\n    \"").append(id).append("\": {");
        buffer.append("\n      \"inputs\": [");
        // for inputs we do not need to check dynamic as we have the data from the route definition
        Set<String> inputs = RouteDefinitionHelper.gatherAllStaticEndpointUris(this, route, true, false);
        boolean first = true;
        for (String input : inputs) {
            if (!first) {
                buffer.append(",");
            } else {
                first = false;
            }
            buffer.append("\n        ");
            buffer.append(StringHelper.toJson("uri", input, true));
        }
        buffer.append("\n      ]");
        buffer.append(",");
        buffer.append("\n      \"outputs\": [");
        Set<String> outputs = RouteDefinitionHelper.gatherAllEndpointUris(this, route, false, true, includeDynamic);
        first = true;
        for (String output : outputs) {
            if (!first) {
                buffer.append(",");
            } else {
                first = false;
            }
            buffer.append("\n        ");
            buffer.append(StringHelper.toJson("uri", output, true));
        }
        buffer.append("\n      ]");
    }
    if (!firstRoute) {
        buffer.append("\n    }");
    }
    buffer.append("\n  }\n}\n");
    return buffer.toString();
}
Also used : RouteDefinition(org.apache.camel.model.RouteDefinition) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList)

Example 33 with RouteDefinition

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

the class DefaultCamelContext method removeRouteDefinition.

public synchronized void removeRouteDefinition(RouteDefinition routeDefinition) throws Exception {
    RouteDefinition toBeRemoved = routeDefinition;
    String id = routeDefinition.getId();
    if (id != null) {
        // remove existing route
        stopRoute(id);
        removeRoute(id);
        toBeRemoved = getRouteDefinition(id);
    }
    this.routeDefinitions.remove(toBeRemoved);
}
Also used : RouteDefinition(org.apache.camel.model.RouteDefinition)

Example 34 with RouteDefinition

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

the class DefaultManagementLifecycleStrategy method removeWrappedProcessorsForRoutes.

/**
     * Removes the wrapped processors for the given routes, as they are no longer in use.
     * <p/>
     * This is needed to avoid accumulating memory, if a lot of routes is being added and removed.
     *
     * @param routes the routes
     */
private void removeWrappedProcessorsForRoutes(Collection<Route> routes) {
    // loop the routes, and remove the route associated wrapped processors, as they are no longer in use
    for (Route route : routes) {
        String id = route.getId();
        Iterator<KeyValueHolder<ProcessorDefinition<?>, InstrumentationProcessor>> it = wrappedProcessors.values().iterator();
        while (it.hasNext()) {
            KeyValueHolder<ProcessorDefinition<?>, InstrumentationProcessor> holder = it.next();
            RouteDefinition def = ProcessorDefinitionHelper.getRoute(holder.getKey());
            if (def != null && id.equals(def.getId())) {
                it.remove();
            }
        }
    }
}
Also used : RouteDefinition(org.apache.camel.model.RouteDefinition) ProcessorDefinition(org.apache.camel.model.ProcessorDefinition) KeyValueHolder(org.apache.camel.util.KeyValueHolder) ManagedRoute(org.apache.camel.management.mbean.ManagedRoute) Route(org.apache.camel.Route) EventDrivenConsumerRoute(org.apache.camel.impl.EventDrivenConsumerRoute)

Example 35 with RouteDefinition

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

the class ManagedCamelContext method dumpRoutesAsXml.

@Override
public String dumpRoutesAsXml(boolean resolvePlaceholders) throws Exception {
    List<RouteDefinition> routes = context.getRouteDefinitions();
    if (routes.isEmpty()) {
        return null;
    }
    // use a routes definition to dump the routes
    RoutesDefinition def = new RoutesDefinition();
    def.setRoutes(routes);
    String xml = ModelHelper.dumpModelAsXml(context, def);
    // if resolving placeholders we parse the xml, and resolve the property placeholders during parsing
    if (resolvePlaceholders) {
        final AtomicBoolean changed = new AtomicBoolean();
        InputStream is = new ByteArrayInputStream(xml.getBytes());
        Document dom = XmlLineNumberParser.parseXml(is, new XmlLineNumberParser.XmlTextTransformer() {

            @Override
            public String transform(String text) {
                try {
                    String after = getContext().resolvePropertyPlaceholders(text);
                    if (!changed.get()) {
                        changed.set(!text.equals(after));
                    }
                    return after;
                } catch (Exception e) {
                    // ignore
                    return text;
                }
            }
        });
        // okay there were some property placeholder replaced so re-create the model
        if (changed.get()) {
            xml = context.getTypeConverter().mandatoryConvertTo(String.class, dom);
            RoutesDefinition copy = ModelHelper.createModelFromXml(context, xml, RoutesDefinition.class);
            xml = ModelHelper.dumpModelAsXml(context, copy);
        }
    }
    return xml;
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RouteDefinition(org.apache.camel.model.RouteDefinition) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) RoutesDefinition(org.apache.camel.model.RoutesDefinition) Document(org.w3c.dom.Document) XmlLineNumberParser(org.apache.camel.util.XmlLineNumberParser) IOException(java.io.IOException)

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