Search in sources :

Example 16 with Component

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

the class DefaultCamelContext method addComponent.

public void addComponent(String componentName, final Component component) {
    ObjectHelper.notNull(component, "component");
    component.setCamelContext(this);
    Component oldValue = components.putIfAbsent(componentName, component);
    if (oldValue != null) {
        throw new IllegalArgumentException("Cannot add component as its already previously added: " + componentName);
    }
    postInitComponent(componentName, component);
}
Also used : PropertiesComponent(org.apache.camel.component.properties.PropertiesComponent) Component(org.apache.camel.Component)

Example 17 with Component

use of org.apache.camel.Component 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 18 with Component

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

the class DefaultCamelContext method initComponent.

/**
     * Function to initialize a component and auto start. Returns null if the autoCreateComponents is disabled
     */
private Component initComponent(String name, boolean autoCreateComponents, boolean autoStart) {
    Component component = null;
    if (autoCreateComponents) {
        try {
            if (log.isDebugEnabled()) {
                log.debug("Using ComponentResolver: {} to resolve component with name: {}", getComponentResolver(), name);
            }
            component = getComponentResolver().resolveComponent(name, this);
            if (component != null) {
                component.setCamelContext(this);
                postInitComponent(name, component);
                if (autoStart && (isStarted() || isStarting())) {
                    // If the component is looked up after the context is started, lets start it up.
                    if (component instanceof Service) {
                        startService((Service) component);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeCamelException("Cannot auto create component: " + name, e);
        }
    }
    return component;
}
Also used : 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) PropertiesComponent(org.apache.camel.component.properties.PropertiesComponent) Component(org.apache.camel.Component) 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)

Example 19 with Component

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

the class DefaultCamelContext method explainComponentJson.

public String explainComponentJson(String componentName, boolean includeAllOptions) {
    try {
        String json = getComponentParameterJsonSchema(componentName);
        if (json == null) {
            return null;
        }
        List<Map<String, String>> rows = JsonSchemaHelper.parseJsonSchema("componentProperties", json, true);
        // selected rows to use for answer
        Map<String, String[]> selected = new LinkedHashMap<String, String[]>();
        // insert values from component
        Component component = getComponent(componentName);
        Map<String, Object> options = new HashMap<String, Object>();
        IntrospectionSupport.getProperties(component, options, null);
        for (Map.Entry<String, Object> entry : options.entrySet()) {
            String name = entry.getKey();
            // skip unwanted options which is default inherited from DefaultComponent
            if ("camelContext".equals(name) || "endpointClass".equals(name)) {
                continue;
            }
            String value = "";
            if (entry.getValue() != null) {
                value = entry.getValue().toString();
            }
            value = URISupport.sanitizePath(value);
            // find type and description from the json schema
            String type = null;
            String kind = null;
            String group = null;
            String label = null;
            String required = null;
            String javaType = null;
            String deprecated = null;
            String secret = null;
            String defaultValue = null;
            String description = null;
            for (Map<String, String> row : rows) {
                if (name.equals(row.get("name"))) {
                    type = row.get("type");
                    kind = row.get("kind");
                    group = row.get("group");
                    label = row.get("label");
                    required = row.get("required");
                    javaType = row.get("javaType");
                    deprecated = row.get("deprecated");
                    secret = row.get("secret");
                    defaultValue = row.get("defaultValue");
                    description = row.get("description");
                    break;
                }
            }
            // add as selected row
            selected.put(name, new String[] { name, kind, group, label, required, type, javaType, deprecated, secret, value, defaultValue, description });
        }
        // include other rows
        for (Map<String, String> row : rows) {
            String name = row.get("name");
            String kind = row.get("kind");
            String group = row.get("group");
            String label = row.get("label");
            String required = row.get("required");
            String value = row.get("value");
            String defaultValue = row.get("defaultValue");
            String type = row.get("type");
            String javaType = row.get("javaType");
            String deprecated = row.get("deprecated");
            String secret = row.get("secret");
            value = URISupport.sanitizePath(value);
            String description = row.get("description");
            // always include path options
            if (includeAllOptions) {
                // add as selected row
                if (!selected.containsKey(name)) {
                    selected.put(name, new String[] { name, kind, group, label, required, type, javaType, deprecated, secret, value, defaultValue, description });
                }
            }
        }
        json = ObjectHelper.before(json, "  \"componentProperties\": {");
        StringBuilder buffer = new StringBuilder("  \"componentProperties\": {");
        boolean first = true;
        for (String[] row : selected.values()) {
            if (first) {
                first = false;
            } else {
                buffer.append(",");
            }
            buffer.append("\n    ");
            String name = row[0];
            String kind = row[1];
            String group = row[2];
            String label = row[3];
            String required = row[4];
            String type = row[5];
            String javaType = row[6];
            String deprecated = row[7];
            String secret = row[8];
            String value = row[9];
            String defaultValue = row[10];
            String description = row[11];
            // add json of the option
            buffer.append(StringQuoteHelper.doubleQuote(name)).append(": { ");
            CollectionStringBuffer csb = new CollectionStringBuffer();
            if (kind != null) {
                csb.append("\"kind\": \"" + kind + "\"");
            }
            if (group != null) {
                csb.append("\"group\": \"" + group + "\"");
            }
            if (label != null) {
                csb.append("\"label\": \"" + label + "\"");
            }
            if (required != null) {
                csb.append("\"required\": \"" + required + "\"");
            }
            if (type != null) {
                csb.append("\"type\": \"" + type + "\"");
            }
            if (javaType != null) {
                csb.append("\"javaType\": \"" + javaType + "\"");
            }
            if (deprecated != null) {
                csb.append("\"deprecated\": \"" + deprecated + "\"");
            }
            if (secret != null) {
                csb.append("\"secret\": \"" + secret + "\"");
            }
            if (value != null) {
                csb.append("\"value\": \"" + value + "\"");
            }
            if (defaultValue != null) {
                csb.append("\"defaultValue\": \"" + defaultValue + "\"");
            }
            if (description != null) {
                csb.append("\"description\": \"" + description + "\"");
            }
            if (!csb.isEmpty()) {
                buffer.append(csb.toString());
            }
            buffer.append(" }");
        }
        buffer.append("\n  }\n}\n");
        // insert the original first part of the json into the start of the buffer
        buffer.insert(0, json);
        return buffer.toString();
    } catch (Exception e) {
        // ignore and return empty response
        return null;
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) CollectionStringBuffer(org.apache.camel.util.CollectionStringBuffer) 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) LinkedHashMap(java.util.LinkedHashMap) PropertiesComponent(org.apache.camel.component.properties.PropertiesComponent) Component(org.apache.camel.Component) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 20 with Component

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

the class RestEndpoint method createConsumer.

@Override
public Consumer createConsumer(Processor processor) throws Exception {
    RestConsumerFactory factory = null;
    String cname = null;
    if (getComponentName() != null) {
        Object comp = getCamelContext().getRegistry().lookupByName(getComponentName());
        if (comp != null && comp instanceof RestConsumerFactory) {
            factory = (RestConsumerFactory) comp;
        } else {
            comp = getCamelContext().getComponent(getComponentName());
            if (comp != null && comp instanceof RestConsumerFactory) {
                factory = (RestConsumerFactory) comp;
            }
        }
        if (factory == null) {
            if (comp != null) {
                throw new IllegalArgumentException("Component " + getComponentName() + " is not a RestConsumerFactory");
            } else {
                throw new NoSuchBeanException(getComponentName(), RestConsumerFactory.class.getName());
            }
        }
        cname = getComponentName();
    }
    // try all components
    if (factory == null) {
        for (String name : getCamelContext().getComponentNames()) {
            Component comp = getCamelContext().getComponent(name);
            if (comp != null && comp instanceof RestConsumerFactory) {
                factory = (RestConsumerFactory) comp;
                cname = name;
                break;
            }
        }
    }
    // lookup in registry
    if (factory == null) {
        Set<RestConsumerFactory> factories = getCamelContext().getRegistry().findByType(RestConsumerFactory.class);
        if (factories != null && factories.size() == 1) {
            factory = factories.iterator().next();
        }
    }
    // and there must only be exactly one so we safely can pick this one
    if (factory == null) {
        RestConsumerFactory found = null;
        String foundName = null;
        for (String name : DEFAULT_REST_CONSUMER_COMPONENTS) {
            Object comp = getCamelContext().getComponent(name, true);
            if (comp != null && comp instanceof RestConsumerFactory) {
                if (found == null) {
                    found = (RestConsumerFactory) comp;
                    foundName = name;
                } else {
                    throw new IllegalArgumentException("Multiple RestConsumerFactory found on classpath. Configure explicit which component to use");
                }
            }
        }
        if (found != null) {
            LOG.debug("Auto discovered {} as RestConsumerFactory", foundName);
            factory = found;
        }
    }
    if (factory != null) {
        // if no explicit port/host configured, then use port from rest configuration
        String scheme = "http";
        String host = "";
        int port = 80;
        RestConfiguration config = getCamelContext().getRestConfiguration(cname, true);
        if (config.getScheme() != null) {
            scheme = config.getScheme();
        }
        if (config.getHost() != null) {
            host = config.getHost();
        }
        int num = config.getPort();
        if (num > 0) {
            port = num;
        }
        // if no explicit hostname set then resolve the hostname
        if (ObjectHelper.isEmpty(host)) {
            if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
                host = "0.0.0.0";
            } else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
                host = HostUtils.getLocalHostName();
            } else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
                host = HostUtils.getLocalIp();
            }
        }
        // calculate the url to the rest service
        String path = getPath();
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        // there may be an optional context path configured to help Camel calculate the correct urls for the REST services
        // this may be needed when using camel-servlet where we cannot get the actual context-path or port number of the servlet engine
        // during init of the servlet
        String contextPath = config.getContextPath();
        if (contextPath != null) {
            if (!contextPath.startsWith("/")) {
                path = "/" + contextPath + path;
            } else {
                path = contextPath + path;
            }
        }
        String baseUrl = scheme + "://" + host + (port != 80 ? ":" + port : "") + path;
        String url = baseUrl;
        if (uriTemplate != null) {
            // make sure to avoid double slashes
            if (uriTemplate.startsWith("/")) {
                url = url + uriTemplate;
            } else {
                url = url + "/" + uriTemplate;
            }
        }
        Consumer consumer = factory.createConsumer(getCamelContext(), processor, getMethod(), getPath(), getUriTemplate(), getConsumes(), getProduces(), config, getParameters());
        configureConsumer(consumer);
        // add to rest registry so we can keep track of them, we will remove from the registry when the consumer is removed
        // the rest registry will automatic keep track when the consumer is removed,
        // and un-register the REST service from the registry
        getCamelContext().getRestRegistry().addRestService(consumer, url, baseUrl, getPath(), getUriTemplate(), getMethod(), getConsumes(), getProduces(), getInType(), getOutType(), getRouteId(), getDescription());
        return consumer;
    } else {
        throw new IllegalStateException("Cannot find RestConsumerFactory in Registry or as a Component to use");
    }
}
Also used : Consumer(org.apache.camel.Consumer) NoSuchBeanException(org.apache.camel.NoSuchBeanException) RestConfiguration(org.apache.camel.spi.RestConfiguration) Component(org.apache.camel.Component) RestConsumerFactory(org.apache.camel.spi.RestConsumerFactory) DefaultEndpoint(org.apache.camel.impl.DefaultEndpoint) UriEndpoint(org.apache.camel.spi.UriEndpoint)

Aggregations

Component (org.apache.camel.Component)52 Test (org.junit.Test)24 ComponentConfiguration (org.apache.camel.ComponentConfiguration)14 PropertiesComponent (org.apache.camel.component.properties.PropertiesComponent)9 SedaComponent (org.apache.camel.component.seda.SedaComponent)9 Map (java.util.Map)7 CamelContext (org.apache.camel.CamelContext)7 NoFactoryAvailableException (org.apache.camel.NoFactoryAvailableException)7 IOException (java.io.IOException)6 Endpoint (org.apache.camel.Endpoint)6 NoSuchEndpointException (org.apache.camel.NoSuchEndpointException)6 ResolveEndpointFailedException (org.apache.camel.ResolveEndpointFailedException)6 DefaultCamelContext (org.apache.camel.impl.DefaultCamelContext)5 LinkedHashMap (java.util.LinkedHashMap)4 MalformedObjectNameException (javax.management.MalformedObjectNameException)4 FailedToStartRouteException (org.apache.camel.FailedToStartRouteException)4 NoSuchBeanException (org.apache.camel.NoSuchBeanException)4 RuntimeCamelException (org.apache.camel.RuntimeCamelException)4 VetoCamelContextStartException (org.apache.camel.VetoCamelContextStartException)4 DirectComponent (org.apache.camel.component.direct.DirectComponent)4