001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.impl;
018    
019    import java.io.IOException;
020    import java.lang.reflect.Constructor;
021    import java.util.ArrayList;
022    import java.util.Collection;
023    import java.util.HashMap;
024    import java.util.List;
025    import java.util.Map;
026    import java.util.concurrent.Callable;
027    
028    import javax.naming.Context;
029    
030    import org.apache.camel.CamelContext;
031    import org.apache.camel.Component;
032    import org.apache.camel.Endpoint;
033    import org.apache.camel.Exchange;
034    import org.apache.camel.Processor;
035    import org.apache.camel.ProducerTemplate;
036    import org.apache.camel.ResolveEndpointFailedException;
037    import org.apache.camel.Route;
038    import org.apache.camel.Routes;
039    import org.apache.camel.RuntimeCamelException;
040    import org.apache.camel.Service;
041    import org.apache.camel.TypeConverter;
042    import org.apache.camel.builder.ErrorHandlerBuilder;
043    import org.apache.camel.impl.converter.DefaultTypeConverter;
044    import org.apache.camel.management.InstrumentationLifecycleStrategy;
045    import org.apache.camel.management.JmxSystemPropertyKeys;
046    import org.apache.camel.model.RouteType;
047    import org.apache.camel.model.dataformat.DataFormatType;
048    import org.apache.camel.processor.interceptor.Delayer;
049    import org.apache.camel.processor.interceptor.TraceFormatter;
050    import org.apache.camel.processor.interceptor.Tracer;
051    import org.apache.camel.spi.ComponentResolver;
052    import org.apache.camel.spi.ExchangeConverter;
053    import org.apache.camel.spi.Injector;
054    import org.apache.camel.spi.InterceptStrategy;
055    import org.apache.camel.spi.Language;
056    import org.apache.camel.spi.LanguageResolver;
057    import org.apache.camel.spi.LifecycleStrategy;
058    import org.apache.camel.spi.Registry;
059    import org.apache.camel.util.CamelContextHelper;
060    import org.apache.camel.util.FactoryFinder;
061    import org.apache.camel.util.NoFactoryAvailableException;
062    import org.apache.camel.util.ObjectHelper;
063    import org.apache.camel.util.ReflectionInjector;
064    import org.apache.camel.util.SystemHelper;
065    import org.apache.commons.logging.Log;
066    import org.apache.commons.logging.LogFactory;
067    
068    import static org.apache.camel.util.ServiceHelper.startServices;
069    import static org.apache.camel.util.ServiceHelper.stopServices;
070    
071    /**
072     * Represents the context used to configure routes and the policies to use.
073     *
074     * @version $Revision: 2741 $
075     */
076    public class DefaultCamelContext extends ServiceSupport implements CamelContext, Service {
077        private static final transient Log LOG = LogFactory.getLog(DefaultCamelContext.class);
078        private static final String NAME_PREFIX = "camel-";
079        private static int nameSuffix;
080    
081        private String name;
082        private final Map<String, Endpoint> endpoints = new HashMap<String, Endpoint>();
083        private final Map<String, Component> components = new HashMap<String, Component>();
084        private List<Route> routes;
085        private List<Service> servicesToClose = new ArrayList<Service>();
086        private TypeConverter typeConverter;
087        private ExchangeConverter exchangeConverter;
088        private Injector injector;
089        private ComponentResolver componentResolver;
090        private boolean autoCreateComponents = true;
091        private LanguageResolver languageResolver = new DefaultLanguageResolver();
092        private Registry registry;
093        private LifecycleStrategy lifecycleStrategy;
094        private List<RouteType> routeDefinitions = new ArrayList<RouteType>();
095        private List<InterceptStrategy> interceptStrategies = new ArrayList<InterceptStrategy>();
096        private Boolean trace;
097        private Long delay;
098        private ErrorHandlerBuilder errorHandlerBuilder;
099        private Map<String, DataFormatType> dataFormats = new HashMap<String, DataFormatType>();
100        private Class<? extends FactoryFinder> factoryFinderClass = FactoryFinder.class;
101    
102        public DefaultCamelContext() {
103            name = NAME_PREFIX + ++nameSuffix;
104    
105            if (Boolean.getBoolean(JmxSystemPropertyKeys.DISABLED)) {
106                LOG.info("JMX is disabled. Using DefaultLifecycleStrategy.");
107                lifecycleStrategy = new DefaultLifecycleStrategy();
108            } else {
109                try {
110                    LOG.info("JMX enabled. Using InstrumentationLifecycleStrategy.");
111                    lifecycleStrategy = new InstrumentationLifecycleStrategy();
112                } catch (NoClassDefFoundError e) {
113                    // if we can't instantiate the JMX enabled strategy then fallback to default
114                    // could be because of missing .jars on the classpath
115                    LOG.warn("Could not find needed classes for JMX lifecycle strategy."
116                        + " Needed class is in spring-context.jar using Spring 2.5 or newer ("
117                        + " spring-jmx.jar using Spring 2.0.x)."
118                        + " NoClassDefFoundError: " + e.getMessage());
119                } catch (Exception e) {
120                    LOG.warn("Could not create JMX lifecycle strategy, caused by: " + e.getMessage());
121                }
122                // if not created then fallback to default
123                if (lifecycleStrategy == null) {
124                    LOG.warn("Not possible to use JMX lifecycle strategy. Using DefaultLifecycleStrategy instead.");
125                    lifecycleStrategy = new DefaultLifecycleStrategy();
126                }
127            }
128        }
129    
130        /**
131         * Creates the {@link CamelContext} using the given JNDI context as the
132         * registry
133         */
134        public DefaultCamelContext(Context jndiContext) {
135            this();
136            setJndiContext(jndiContext);
137        }
138    
139        /**
140         * Creates the {@link CamelContext} using the given registry
141         */
142        public DefaultCamelContext(Registry registry) {
143            this();
144            this.registry = registry;
145        }
146    
147        public String getName() {
148            return name;
149        }
150    
151        /**
152         * Sets the name of the this context.
153         */
154        public void setName(String name) {
155            this.name = name;
156        }
157    
158        public void addComponent(String componentName, final Component component) {
159            if (component == null) {
160                throw new IllegalArgumentException("Component cannot be null");
161            }
162            synchronized (components) {
163                if (components.containsKey(componentName)) {
164                    throw new IllegalArgumentException("Component previously added: " + componentName);
165                }
166                component.setCamelContext(this);
167                components.put(componentName, component);
168            }
169        }
170    
171        public Component getComponent(String name) {
172            // synchronize the look up and auto create so that 2 threads can't
173            // concurrently auto create the same component.
174            synchronized (components) {
175                Component component = components.get(name);
176                if (component == null && autoCreateComponents) {
177                    try {
178                        component = getComponentResolver().resolveComponent(name, this);
179                        if (component != null) {
180                            addComponent(name, component);
181                            if (isStarted()) {
182                                // If the component is looked up after the context
183                                // is started,
184                                // lets start it up.
185                                startServices(component);
186                            }
187                        }
188                    } catch (Exception e) {
189                        throw new RuntimeCamelException("Could not auto create component: " + name, e);
190                    }
191                }
192                return component;
193            }
194        }
195    
196        public <T extends Component> T getComponent(String name, Class<T> componentType) {
197            Component component = getComponent(name);
198            if (componentType.isInstance(component)) {
199                return componentType.cast(component);
200            } else {
201                throw new IllegalArgumentException("The component is not of type: " + componentType + " but is: "
202                        + component);
203            }
204        }
205    
206        public Component removeComponent(String componentName) {
207            synchronized (components) {
208                return components.remove(componentName);
209            }
210        }
211    
212        public Component getOrCreateComponent(String componentName, Callable<Component> factory) {
213            synchronized (components) {
214                Component component = components.get(componentName);
215                if (component == null) {
216                    try {
217                        component = factory.call();
218                        if (component == null) {
219                            throw new RuntimeCamelException("Factory failed to create the " + componentName
220                                    + " component, it returned null.");
221                        }
222                        components.put(componentName, component);
223                        component.setCamelContext(this);
224                    } catch (Exception e) {
225                        throw new RuntimeCamelException("Factory failed to create the " + componentName
226                                + " component", e);
227                    }
228                }
229                return component;
230            }
231        }
232    
233        // Endpoint Management Methods
234        // -----------------------------------------------------------------------
235    
236        public Collection<Endpoint> getEndpoints() {
237            synchronized (endpoints) {
238                return new ArrayList<Endpoint>(endpoints.values());
239            }
240        }
241    
242        public Map<String, Endpoint> getEndpointMap() {
243            synchronized (endpoints) {
244                return new HashMap<String, Endpoint>(endpoints);
245            }
246        }
247    
248        public Collection<Endpoint> getEndpoints(String uri) {
249            Collection<Endpoint> answer = new ArrayList<Endpoint>();
250            Collection<Endpoint> coll;
251            synchronized (endpoints) {
252                Endpoint ep = endpoints.get(uri);
253                if (ep != null) {
254                    answer.add(ep);
255                    return answer;
256                }
257                coll = new ArrayList<Endpoint>(endpoints.values());
258            }
259            for (Endpoint ep : coll) {
260                if (!ep.isSingleton() && uri.equals(ep.getEndpointUri())) {
261                    answer.add(ep);
262                }
263            }
264            return answer;
265        }
266    
267        public Collection<Endpoint> getSingletonEndpoints() {
268            Collection<Endpoint> answer = new ArrayList<Endpoint>();
269            Collection<Endpoint> coll = getEndpoints();
270            for (Endpoint ep : coll) {
271                if (ep.isSingleton()) {
272                    answer.add(ep);
273                }
274            }
275            return answer;
276        }
277    
278        public Endpoint addEndpoint(String uri, Endpoint endpoint) throws Exception {
279            Endpoint oldEndpoint;
280            synchronized (endpoints) {
281                startServices(endpoint);
282                oldEndpoint = endpoints.remove(uri);
283                endpoints.put(getEndpointKey(uri, endpoint), endpoint);
284                if (oldEndpoint != null) {
285                    stopServices(oldEndpoint);
286                }
287            }
288            return oldEndpoint;
289        }
290    
291        public Collection<Endpoint> removeEndpoints(String uri) throws Exception {
292            Collection<Endpoint> answer = new ArrayList<Endpoint>();
293            synchronized (endpoints) {
294                Endpoint oldEndpoint = endpoints.remove(uri);
295                if (oldEndpoint != null) {
296                    answer.add(oldEndpoint);
297                    stopServices(oldEndpoint);
298                } else {
299                    for (Map.Entry entry : endpoints.entrySet()) {
300                        oldEndpoint = (Endpoint)entry.getValue();
301                        if (!oldEndpoint.isSingleton() && uri.equals(oldEndpoint.getEndpointUri())) {
302                            answer.add(oldEndpoint);
303                            stopServices(oldEndpoint);
304                            endpoints.remove(entry.getKey());
305                        }
306                    }
307                }
308            }
309            return answer;
310        }
311    
312        public Endpoint addSingletonEndpoint(String uri, Endpoint endpoint) throws Exception {
313            return addEndpoint(uri, endpoint);
314        }
315    
316        public Endpoint removeSingletonEndpoint(String uri) throws Exception {
317            Collection<Endpoint> answer = removeEndpoints(uri);
318            return (Endpoint) (answer.size() > 0 ? answer.toArray()[0] : null);
319        }
320    
321        public Endpoint getEndpoint(String uri) {
322            Endpoint<?> answer;
323            synchronized (endpoints) {
324                answer = endpoints.get(uri);
325                if (answer == null) {
326                    try {
327    
328                        // Use the URI prefix to find the component.
329                        String splitURI[] = ObjectHelper.splitOnCharacter(uri, ":", 2);
330                        if (splitURI[1] != null) {
331                            String scheme = splitURI[0];
332                            Component<?> component = getComponent(scheme);
333    
334                            // Ask the component to resolve the endpoint.
335                            if (component != null) {
336                                // Have the component create the endpoint if it can.
337                                answer = component.createEndpoint(uri);
338    
339                                if (answer != null && LOG.isDebugEnabled()) {
340                                    LOG.debug(uri + " converted to endpoint: " + answer + " by component: " + component);
341                                }
342                            }
343                        }
344                        if (answer == null) {
345                            answer = createEndpoint(uri);
346                        }
347    
348                        // If it's a singleton then auto register it.
349                        if (answer != null) {
350                            addService(answer);
351    
352                            endpoints.put(getEndpointKey(uri, answer), answer);
353                            lifecycleStrategy.onEndpointAdd(answer);
354                        }
355                    } catch (Exception e) {
356                        LOG.debug("Failed to resolve endpoint " + uri + ". Reason: " + e, e);
357                        throw new ResolveEndpointFailedException(uri, e);
358                    }
359                }
360            }
361            return answer;
362        }
363    
364        public <T extends Endpoint> T getEndpoint(String name, Class<T> endpointType) {
365            Endpoint endpoint = getEndpoint(name);
366            if (endpointType.isInstance(endpoint)) {
367                return endpointType.cast(endpoint);
368            } else {
369                throw new IllegalArgumentException("The endpoint is not of type: " + endpointType + " but is: "
370                        + endpoint);
371            }
372        }
373    
374        // Route Management Methods
375        // -----------------------------------------------------------------------
376        public List<Route> getRoutes() {
377            if (routes == null) {
378                routes = new ArrayList<Route>();
379            }
380            return routes;
381        }
382    
383        public void setRoutes(List<Route> routes) {
384            this.routes = routes;
385            throw new UnsupportedOperationException("overriding existing routes is not supported yet, use addRoutes instead");
386        }
387    
388        public void addRoutes(Collection<Route> routes) throws Exception {
389            if (this.routes == null) {
390                this.routes = new ArrayList<Route>();
391            }
392    
393            if (routes != null) {
394                this.routes.addAll(routes);
395    
396                lifecycleStrategy.onRoutesAdd(routes);
397                if (shouldStartRoutes()) {
398                    startRoutes(routes);
399                }
400            }
401        }
402    
403        public void addRoutes(Routes builder) throws Exception {
404            // lets now add the routes from the builder
405            builder.setContext(this);
406            List<Route> routeList = builder.getRouteList();
407            if (LOG.isDebugEnabled()) {
408                LOG.debug("Adding routes from: " + builder + " routes: " + routeList);
409            }
410            addRoutes(routeList);
411        }
412    
413        public void addRouteDefinitions(Collection<RouteType> routeDefinitions) throws Exception {
414            this.routeDefinitions.addAll(routeDefinitions);
415            if (shouldStartRoutes()) {
416                startRouteDefinitions(routeDefinitions);
417            }
418    
419        }
420    
421        /**
422         * Adds a service, starting it so that it will be stopped with this context
423         */
424        public void addService(Object object) throws Exception {
425            if (object instanceof Service) {
426                Service service = (Service) object;
427                getLifecycleStrategy().onServiceAdd(this, service);
428                service.start();
429                servicesToClose.add(service);
430            }
431        }
432    
433        // Helper methods
434        // -----------------------------------------------------------------------
435    
436        public Language resolveLanguage(String language) {
437            return getLanguageResolver().resolveLanguage(language, this);
438        }
439    
440        // Properties
441        // -----------------------------------------------------------------------
442        public ExchangeConverter getExchangeConverter() {
443            if (exchangeConverter == null) {
444                exchangeConverter = createExchangeConverter();
445            }
446            return exchangeConverter;
447        }
448    
449        public void setExchangeConverter(ExchangeConverter exchangeConverter) {
450            this.exchangeConverter = exchangeConverter;
451        }
452    
453        public TypeConverter getTypeConverter() {
454            if (typeConverter == null) {
455                typeConverter = createTypeConverter();
456            }
457            return typeConverter;
458        }
459    
460        public void setTypeConverter(TypeConverter typeConverter) {
461            this.typeConverter = typeConverter;
462        }
463    
464        public Injector getInjector() {
465            if (injector == null) {
466                injector = createInjector();
467            }
468            return injector;
469        }
470    
471        public void setInjector(Injector injector) {
472            this.injector = injector;
473        }
474    
475        public ComponentResolver getComponentResolver() {
476            if (componentResolver == null) {
477                componentResolver = createComponentResolver();
478            }
479            return componentResolver;
480        }
481    
482        public void setComponentResolver(ComponentResolver componentResolver) {
483            this.componentResolver = componentResolver;
484        }
485    
486        public LanguageResolver getLanguageResolver() {
487            return languageResolver;
488        }
489    
490        public void setLanguageResolver(LanguageResolver languageResolver) {
491            this.languageResolver = languageResolver;
492        }
493    
494        public boolean isAutoCreateComponents() {
495            return autoCreateComponents;
496        }
497    
498        public void setAutoCreateComponents(boolean autoCreateComponents) {
499            this.autoCreateComponents = autoCreateComponents;
500        }
501    
502        public Registry getRegistry() {
503            if (registry == null) {
504                registry = createRegistry();
505            }
506            return registry;
507        }
508    
509        /**
510         * Sets the registry to the given JNDI context
511         *
512         * @param jndiContext is the JNDI context to use as the registry
513         *
514         * @see #setRegistry(org.apache.camel.spi.Registry)
515         */
516        public void setJndiContext(Context jndiContext) {
517            setRegistry(new JndiRegistry(jndiContext));
518        }
519    
520        public void setRegistry(Registry registry) {
521            this.registry = registry;
522        }
523    
524        public LifecycleStrategy getLifecycleStrategy() {
525            return lifecycleStrategy;
526        }
527    
528        public void setLifecycleStrategy(LifecycleStrategy lifecycleStrategy) {
529            this.lifecycleStrategy = lifecycleStrategy;
530        }
531    
532        public List<RouteType> getRouteDefinitions() {
533            return routeDefinitions;
534        }
535    
536        public List<InterceptStrategy> getInterceptStrategies() {
537            return interceptStrategies;
538        }
539    
540        public void setInterceptStrategies(List<InterceptStrategy> interceptStrategies) {
541            this.interceptStrategies = interceptStrategies;
542        }
543    
544        public void addInterceptStrategy(InterceptStrategy interceptStrategy) {
545            getInterceptStrategies().add(interceptStrategy);
546        }
547    
548        /**
549         * Returns true if tracing has been enabled or disabled via the {@link #setTrace(Boolean)} method
550         * or it has not been specified then default to the <b>camel.trace</b> system property
551         */
552        public boolean getTrace() {
553            final Boolean value = getTracing();
554            if (value != null) {
555                return value;
556            } else {
557                return SystemHelper.isSystemProperty("camel.trace");
558            }
559        }
560    
561        public Boolean getTracing() {
562            return trace;
563        }
564    
565        public void setTrace(Boolean trace) {
566            this.trace = trace;
567        }
568    
569        /**
570         * Returns the delay in millis if delaying has been enabled or disabled via the {@link #setDelay(Long)} method
571         * or it has not been specified then default to the <b>camel.delay</b> system property
572         */
573        public long getDelay() {
574            final Long value = getDelaying();
575            if (value != null) {
576                return value;
577            } else {
578                String prop = SystemHelper.getSystemProperty("camel.delay");
579                return prop != null ? Long.getLong(prop) : 0;
580            }
581        }
582    
583        public Long getDelaying() {
584            return delay;
585        }
586    
587        public void setDelay(Long delay) {
588            this.delay = delay;
589        }
590    
591        public <E extends Exchange> ProducerTemplate<E> createProducerTemplate() {
592            return new DefaultProducerTemplate<E>(this);
593        }
594    
595        public ErrorHandlerBuilder getErrorHandlerBuilder() {
596            return errorHandlerBuilder;
597        }
598    
599        /**
600         * Sets the default error handler builder which is inherited by the routes
601         */
602        public void setErrorHandlerBuilder(ErrorHandlerBuilder errorHandlerBuilder) {
603            this.errorHandlerBuilder = errorHandlerBuilder;
604        }
605    
606        // Implementation methods
607        // -----------------------------------------------------------------------
608    
609        protected void doStart() throws Exception {
610            LOG.info("Apache Camel " + getVersion() + " (CamelContext:" + getName() + ") is starting");
611    
612            if (getTrace()) {
613                // only add a new tracer if not already configued
614                if (Tracer.getTracer(this) == null) {
615                    Tracer tracer = new Tracer();
616                    // lets see if we have a formatter if so use it
617                    TraceFormatter formatter = this.getRegistry().lookup("traceFormatter", TraceFormatter.class);
618                    if (formatter != null) {
619                        tracer.setFormatter(formatter);
620                    }
621                    addInterceptStrategy(tracer);
622                }
623            }
624    
625            if (getDelay() > 0) {
626                // only add a new delayer if not already configued
627                if (Delayer.getDelayer(this) == null) {
628                    addInterceptStrategy(new Delayer(getDelay()));
629                }
630            }
631    
632            lifecycleStrategy.onContextStart(this);
633    
634            forceLazyInitialization();
635            if (components != null) {
636                for (Component component : components.values()) {
637                    startServices(component);
638                }
639            }
640            startRouteDefinitions(routeDefinitions);
641            startRoutes(routes);
642            
643            LOG.info("Apache Camel " + getVersion() + " (CamelContext:" + getName() + ") started");
644        }
645    
646        protected void startRouteDefinitions(Collection<RouteType> list) throws Exception {
647            if (list != null) {
648                Collection<Route> routes = new ArrayList<Route>();
649                for (RouteType route : list) {
650                    route.addRoutes(this, routes);
651                }
652                addRoutes(routes);
653            }
654        }
655    
656        protected void doStop() throws Exception {
657            stopServices(servicesToClose);
658            if (components != null) {
659                for (Component component : components.values()) {
660                    stopServices(component);
661                }
662            }
663        }
664    
665        protected void startRoutes(Collection<Route> routeList) throws Exception {
666            if (routeList != null) {
667                for (Route<Exchange> route : routeList) {
668                    List<Service> services = route.getServicesForRoute();
669                    for (Service service : services) {
670                        addService(service);
671                    }
672                }
673            }
674        }
675    
676        /**
677         * Lets force some lazy initialization to occur upfront before we start any
678         * components and create routes
679         */
680        protected void forceLazyInitialization() {
681            getExchangeConverter();
682            getInjector();
683            getLanguageResolver();
684            getTypeConverter();
685        }
686    
687        /**
688         * Lazily create a default implementation
689         */
690        protected ExchangeConverter createExchangeConverter() {
691            return new DefaultExchangeConverter();
692        }
693    
694        /**
695         * Lazily create a default implementation
696         */
697        protected TypeConverter createTypeConverter() {
698            return new DefaultTypeConverter(getInjector());
699        }
700    
701        /**
702         * Lazily create a default implementation
703         */
704        protected Injector createInjector() {
705            FactoryFinder finder = createFactoryFinder();
706            try {
707                return (Injector) finder.newInstance("Injector");
708            } catch (NoFactoryAvailableException e) {
709                // lets use the default
710                return new ReflectionInjector();
711            } catch (IllegalAccessException e) {
712                throw new RuntimeCamelException(e);
713            } catch (InstantiationException e) {
714                throw new RuntimeCamelException(e);
715            } catch (IOException e) {
716                throw new RuntimeCamelException(e);
717            } catch (ClassNotFoundException e) {
718                throw new RuntimeCamelException(e);
719            }
720        }
721    
722        /**
723         * Lazily create a default implementation
724         */
725        protected ComponentResolver createComponentResolver() {
726            return new DefaultComponentResolver();
727        }
728    
729        /**
730         * Lazily create a default implementation
731         */
732        protected Registry createRegistry() {
733            return new JndiRegistry();
734        }
735    
736        /**
737         * A pluggable strategy to allow an endpoint to be created without requiring
738         * a component to be its factory, such as for looking up the URI inside some
739         * {@link Registry}
740         *
741         * @param uri the uri for the endpoint to be created
742         * @return the newly created endpoint or null if it could not be resolved
743         */
744        protected Endpoint createEndpoint(String uri) {
745            Object value = getRegistry().lookup(uri);
746            if (value instanceof Endpoint) {
747                return (Endpoint) value;
748            } else if (value instanceof Processor) {
749                return new ProcessorEndpoint(uri, this, (Processor) value);
750            } else if (value != null) {
751                return convertBeanToEndpoint(uri, value);
752            }
753            return null;
754        }
755    
756        /**
757         * Attempt to convert the bean from a {@link Registry} to an endpoint using
758         * some kind of transformation or wrapper
759         *
760         * @param uri  the uri for the endpoint (and name in the registry)
761         * @param bean the bean to be converted to an endpoint, which will be not null
762         * @return a new endpoint
763         */
764        protected Endpoint convertBeanToEndpoint(String uri, Object bean) {
765            throw new IllegalArgumentException("uri: " + uri + " bean: " + bean
766                    + " could not be converted to an Endpoint");
767        }
768    
769        /**
770         * Should we start newly added routes?
771         */
772        protected boolean shouldStartRoutes() {
773            return isStarted() && !isStarting();
774        }
775    
776        public void setDataFormats(Map<String, DataFormatType> dataFormats) {
777            this.dataFormats = dataFormats;
778        }
779    
780        public Map<String, DataFormatType> getDataFormats() {
781            return dataFormats;
782        }
783        
784        public void setFactoryFinderClass(Class<? extends FactoryFinder> finderClass) {
785            factoryFinderClass = finderClass;
786        }
787    
788        public FactoryFinder createFactoryFinder() {
789            try {
790                return factoryFinderClass.newInstance();
791            } catch (Exception e) {
792                throw new RuntimeCamelException(e);
793            }
794        }
795    
796        public FactoryFinder createFactoryFinder(String path) {
797            try {
798                Constructor<? extends FactoryFinder> constructor;
799                constructor = factoryFinderClass.getConstructor(String.class);
800                return constructor.newInstance(path);
801            } catch (Exception e) {
802                throw new RuntimeCamelException(e);
803            }
804            
805        }
806    
807    
808        protected synchronized String getEndpointKey(String uri, Endpoint endpoint) {
809            if (endpoint.isSingleton()) {
810                return uri;
811            } else {
812                // lets try find the first endpoint key which is free
813                for (int counter = 0; true; counter++) {
814                    String key = (counter > 0) ? uri + ":" + counter : uri;
815                    if (!endpoints.containsKey(key)) {
816                        return key;
817                    }
818                }
819            }
820        }
821    
822    
823    }