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 */
017package org.apache.camel.spring.handler;
018
019import java.lang.reflect.Method;
020import java.util.HashMap;
021import java.util.HashSet;
022import java.util.Map;
023import java.util.Set;
024
025import javax.xml.bind.Binder;
026import javax.xml.bind.JAXBContext;
027import javax.xml.bind.JAXBException;
028
029import org.w3c.dom.Document;
030import org.w3c.dom.Element;
031import org.w3c.dom.NamedNodeMap;
032import org.w3c.dom.Node;
033import org.w3c.dom.NodeList;
034
035import org.apache.camel.core.xml.CamelJMXAgentDefinition;
036import org.apache.camel.core.xml.CamelPropertyPlaceholderDefinition;
037import org.apache.camel.core.xml.CamelRouteControllerDefinition;
038import org.apache.camel.core.xml.CamelStreamCachingStrategyDefinition;
039import org.apache.camel.impl.engine.DefaultCamelContextNameStrategy;
040import org.apache.camel.spi.CamelContextNameStrategy;
041import org.apache.camel.spi.NamespaceAware;
042import org.apache.camel.spring.CamelBeanPostProcessor;
043import org.apache.camel.spring.CamelConsumerTemplateFactoryBean;
044import org.apache.camel.spring.CamelContextFactoryBean;
045import org.apache.camel.spring.CamelEndpointFactoryBean;
046import org.apache.camel.spring.CamelFluentProducerTemplateFactoryBean;
047import org.apache.camel.spring.CamelProducerTemplateFactoryBean;
048import org.apache.camel.spring.CamelRedeliveryPolicyFactoryBean;
049import org.apache.camel.spring.CamelRestContextFactoryBean;
050import org.apache.camel.spring.CamelRouteContextFactoryBean;
051import org.apache.camel.spring.CamelThreadPoolFactoryBean;
052import org.apache.camel.spring.SpringModelJAXBContextFactory;
053import org.apache.camel.spring.remoting.CamelProxyFactoryBean;
054import org.apache.camel.spring.remoting.CamelServiceExporter;
055import org.apache.camel.support.builder.Namespaces;
056import org.apache.camel.support.builder.xml.NamespacesHelper;
057import org.apache.camel.util.ObjectHelper;
058import org.apache.camel.util.StringHelper;
059import org.apache.camel.util.spring.KeyStoreParametersFactoryBean;
060import org.apache.camel.util.spring.SSLContextParametersFactoryBean;
061import org.apache.camel.util.spring.SecureRandomParametersFactoryBean;
062import org.slf4j.Logger;
063import org.slf4j.LoggerFactory;
064import org.springframework.beans.factory.BeanCreationException;
065import org.springframework.beans.factory.BeanDefinitionStoreException;
066import org.springframework.beans.factory.config.BeanDefinition;
067import org.springframework.beans.factory.config.RuntimeBeanReference;
068import org.springframework.beans.factory.parsing.BeanComponentDefinition;
069import org.springframework.beans.factory.support.BeanDefinitionBuilder;
070import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
071import org.springframework.beans.factory.xml.ParserContext;
072
073/**
074 * Camel namespace for the spring XML configuration file.
075 */
076public class CamelNamespaceHandler extends NamespaceHandlerSupport {
077    private static final String SPRING_NS = "http://camel.apache.org/schema/spring";
078    private static final Logger LOG = LoggerFactory.getLogger(CamelNamespaceHandler.class);
079    protected BeanDefinitionParser endpointParser = new EndpointDefinitionParser();
080    protected BeanDefinitionParser beanPostProcessorParser = new BeanDefinitionParser(CamelBeanPostProcessor.class, false);
081    protected Set<String> parserElementNames = new HashSet<>();
082    protected Map<String, BeanDefinitionParser> parserMap = new HashMap<>();
083    
084    private JAXBContext jaxbContext;
085    private Map<String, BeanDefinition> autoRegisterMap = new HashMap<>();
086
087    /**
088     * Prepares the nodes before parsing.
089     */
090    public static void doBeforeParse(Node node) {
091        if (node.getNodeType() == Node.ELEMENT_NODE) {
092
093            // ensure namespace with versions etc is renamed to be same namespace so we can parse using this handler
094            Document doc = node.getOwnerDocument();
095            if (node.getNamespaceURI().startsWith(SPRING_NS + "/v")) {
096                doc.renameNode(node, SPRING_NS, node.getNodeName());
097            }
098
099            // remove whitespace noise from uri, xxxUri attributes, eg new lines, and tabs etc, which allows end users to format
100            // their Camel routes in more human readable format, but at runtime those attributes must be trimmed
101            // the parser removes most of the noise, but keeps double spaces in the attribute values
102            NamedNodeMap map = node.getAttributes();
103            for (int i = 0; i < map.getLength(); i++) {
104                Node att = map.item(i);
105                if (att.getNodeName().equals("uri") || att.getNodeName().endsWith("Uri")) {
106                    final String value = att.getNodeValue();
107                    String before = StringHelper.before(value, "?");
108                    String after = StringHelper.after(value, "?");
109
110                    if (before != null && after != null) {
111                        // remove all double spaces in the uri parameters
112                        String changed = after.replaceAll("\\s{2,}", "");
113                        if (!after.equals(changed)) {
114                            String newAtr = before.trim() + "?" + changed.trim();
115                            LOG.debug("Removed whitespace noise from attribute {} -> {}", value, newAtr);
116                            att.setNodeValue(newAtr);
117                        }
118                    }
119                }
120            }
121        }
122        NodeList list = node.getChildNodes();
123        for (int i = 0; i < list.getLength(); ++i) {
124            doBeforeParse(list.item(i));
125        }
126    }
127
128    @Override
129    public void init() {
130        // register restContext parser
131        registerParser("restContext", new RestContextDefinitionParser());
132        // register routeContext parser
133        registerParser("routeContext", new RouteContextDefinitionParser());
134        // register endpoint parser
135        registerParser("endpoint", endpointParser);
136
137        addBeanDefinitionParser("keyStoreParameters", KeyStoreParametersFactoryBean.class, true, true);
138        addBeanDefinitionParser("secureRandomParameters", SecureRandomParametersFactoryBean.class, true, true);
139        registerBeanDefinitionParser("sslContextParameters", new SSLContextParametersFactoryBeanBeanDefinitionParser());
140
141        addBeanDefinitionParser("proxy", CamelProxyFactoryBean.class, true, false);
142        addBeanDefinitionParser("template", CamelProducerTemplateFactoryBean.class, true, false);
143        addBeanDefinitionParser("fluentTemplate", CamelFluentProducerTemplateFactoryBean.class, true, false);
144        addBeanDefinitionParser("consumerTemplate", CamelConsumerTemplateFactoryBean.class, true, false);
145        addBeanDefinitionParser("export", CamelServiceExporter.class, true, false);
146        addBeanDefinitionParser("threadPool", CamelThreadPoolFactoryBean.class, true, true);
147        addBeanDefinitionParser("redeliveryPolicyProfile", CamelRedeliveryPolicyFactoryBean.class, true, true);
148
149        // jmx agent, stream caching, hystrix, service call configurations and property placeholder cannot be used outside of the camel context
150        addBeanDefinitionParser("jmxAgent", CamelJMXAgentDefinition.class, false, false);
151        addBeanDefinitionParser("streamCaching", CamelStreamCachingStrategyDefinition.class, false, false);
152        addBeanDefinitionParser("propertyPlaceholder", CamelPropertyPlaceholderDefinition.class, false, false);
153        addBeanDefinitionParser("routeController", CamelRouteControllerDefinition.class, false, false);
154
155        // error handler could be the sub element of camelContext or defined outside camelContext
156        BeanDefinitionParser errorHandlerParser = new ErrorHandlerDefinitionParser();
157        registerParser("errorHandler", errorHandlerParser);
158        parserMap.put("errorHandler", errorHandlerParser);
159
160        // camel context
161        Class<?> cl = CamelContextFactoryBean.class;
162        registerParser("camelContext", new CamelContextBeanDefinitionParser(cl));
163    }
164
165    protected void addBeanDefinitionParser(String elementName, Class<?> type, boolean register, boolean assignId) {
166        BeanDefinitionParser parser = new BeanDefinitionParser(type, assignId);
167        if (register) {
168            registerParser(elementName, parser);
169        }
170        parserMap.put(elementName, parser);
171    }
172
173    protected void registerParser(String name, org.springframework.beans.factory.xml.BeanDefinitionParser parser) {
174        parserElementNames.add(name);
175        registerBeanDefinitionParser(name, parser);
176    }
177
178    protected Object parseUsingJaxb(Element element, ParserContext parserContext, Binder<Node> binder) {
179        try {
180            return binder.unmarshal(element);
181        } catch (JAXBException e) {
182            throw new BeanDefinitionStoreException("Failed to parse JAXB element", e);
183        }
184    }
185
186    public JAXBContext getJaxbContext() throws JAXBException {
187        if (jaxbContext == null) {
188            jaxbContext = new SpringModelJAXBContextFactory().newJAXBContext();
189        }
190        return jaxbContext;
191    }
192    
193    protected class SSLContextParametersFactoryBeanBeanDefinitionParser extends BeanDefinitionParser {
194
195        public SSLContextParametersFactoryBeanBeanDefinitionParser() {
196            super(SSLContextParametersFactoryBean.class, true);
197        }
198
199        @Override
200        protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
201            doBeforeParse(element);
202            super.doParse(element, builder);
203            
204            // Note: prefer to use doParse from parent and postProcess; however, parseUsingJaxb requires 
205            // parserContext for no apparent reason.
206            Binder<Node> binder;
207            try {
208                binder = getJaxbContext().createBinder();
209            } catch (JAXBException e) {
210                throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e);
211            }
212            
213            Object value = parseUsingJaxb(element, parserContext, binder);
214            
215            if (value instanceof SSLContextParametersFactoryBean) {
216                SSLContextParametersFactoryBean bean = (SSLContextParametersFactoryBean)value;
217                
218                builder.addPropertyValue("cipherSuites", bean.getCipherSuites());
219                builder.addPropertyValue("cipherSuitesFilter", bean.getCipherSuitesFilter());
220                builder.addPropertyValue("secureSocketProtocols", bean.getSecureSocketProtocols());
221                builder.addPropertyValue("secureSocketProtocolsFilter", bean.getSecureSocketProtocolsFilter());
222                builder.addPropertyValue("keyManagers", bean.getKeyManagers());
223                builder.addPropertyValue("trustManagers", bean.getTrustManagers());
224                builder.addPropertyValue("secureRandom", bean.getSecureRandom());
225                
226                builder.addPropertyValue("clientParameters", bean.getClientParameters());
227                builder.addPropertyValue("serverParameters", bean.getServerParameters());
228            } else {
229                throw new BeanDefinitionStoreException("Parsed type is not of the expected type. Expected "
230                                                       + SSLContextParametersFactoryBean.class.getName() + " but found "
231                                                       + value.getClass().getName());
232            }
233        }
234    }
235
236    protected class RouteContextDefinitionParser extends BeanDefinitionParser {
237
238        public RouteContextDefinitionParser() {
239            super(CamelRouteContextFactoryBean.class, false);
240        }
241
242        @Override
243        protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
244            doBeforeParse(element);
245            super.doParse(element, parserContext, builder);
246
247            // now lets parse the routes with JAXB
248            Binder<Node> binder;
249            try {
250                binder = getJaxbContext().createBinder();
251            } catch (JAXBException e) {
252                throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e);
253            }
254            Object value = parseUsingJaxb(element, parserContext, binder);
255
256            if (value instanceof CamelRouteContextFactoryBean) {
257                CamelRouteContextFactoryBean factoryBean = (CamelRouteContextFactoryBean) value;
258                builder.addPropertyValue("routes", factoryBean.getRoutes());
259            }
260
261            // lets inject the namespaces into any namespace aware POJOs
262            injectNamespaces(element, binder);
263        }
264    }
265
266    protected class EndpointDefinitionParser extends BeanDefinitionParser {
267
268        public EndpointDefinitionParser() {
269            super(CamelEndpointFactoryBean.class, false);
270        }
271
272        @Override
273        protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
274            doBeforeParse(element);
275            super.doParse(element, parserContext, builder);
276
277            // now lets parse the routes with JAXB
278            Binder<Node> binder;
279            try {
280                binder = getJaxbContext().createBinder();
281            } catch (JAXBException e) {
282                throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e);
283            }
284            Object value = parseUsingJaxb(element, parserContext, binder);
285
286            if (value instanceof CamelEndpointFactoryBean) {
287                CamelEndpointFactoryBean factoryBean = (CamelEndpointFactoryBean) value;
288                builder.addPropertyValue("properties", factoryBean.getProperties());
289            }
290        }
291    }
292
293    protected class RestContextDefinitionParser extends BeanDefinitionParser {
294
295        public RestContextDefinitionParser() {
296            super(CamelRestContextFactoryBean.class, false);
297        }
298
299        @Override
300        protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
301            doBeforeParse(element);
302            super.doParse(element, parserContext, builder);
303
304            // now lets parse the routes with JAXB
305            Binder<Node> binder;
306            try {
307                binder = getJaxbContext().createBinder();
308            } catch (JAXBException e) {
309                throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e);
310            }
311            Object value = parseUsingJaxb(element, parserContext, binder);
312
313            if (value instanceof CamelRestContextFactoryBean) {
314                CamelRestContextFactoryBean factoryBean = (CamelRestContextFactoryBean) value;
315                builder.addPropertyValue("rests", factoryBean.getRests());
316            }
317
318            // lets inject the namespaces into any namespace aware POJOs
319            injectNamespaces(element, binder);
320        }
321    }
322
323    protected class CamelContextBeanDefinitionParser extends BeanDefinitionParser {
324
325        public CamelContextBeanDefinitionParser(Class<?> type) {
326            super(type, false);
327        }
328
329        @Override
330        protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
331            doBeforeParse(element);
332            super.doParse(element, parserContext, builder);
333
334            String contextId = element.getAttribute("id");
335            boolean implicitId = false;
336
337            // lets avoid folks having to explicitly give an ID to a camel context
338            if (ObjectHelper.isEmpty(contextId)) {
339                // if no explicit id was set then use a default auto generated name
340                CamelContextNameStrategy strategy = new DefaultCamelContextNameStrategy();
341                contextId = strategy.getName();
342                element.setAttributeNS(null, "id", contextId);
343                implicitId = true;
344            }
345
346            // now lets parse the routes with JAXB
347            Binder<Node> binder;
348            try {
349                binder = getJaxbContext().createBinder();
350            } catch (JAXBException e) {
351                throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e);
352            }
353            Object value = parseUsingJaxb(element, parserContext, binder);
354
355            if (value instanceof CamelContextFactoryBean) {
356                // set the property value with the JAXB parsed value
357                CamelContextFactoryBean factoryBean = (CamelContextFactoryBean) value;
358                builder.addPropertyValue("id", contextId);
359                builder.addPropertyValue("implicitId", implicitId);
360                builder.addPropertyValue("restConfiguration", factoryBean.getRestConfiguration());
361                builder.addPropertyValue("rests", factoryBean.getRests());
362                builder.addPropertyValue("routes", factoryBean.getRoutes());
363                builder.addPropertyValue("intercepts", factoryBean.getIntercepts());
364                builder.addPropertyValue("interceptFroms", factoryBean.getInterceptFroms());
365                builder.addPropertyValue("interceptSendToEndpoints", factoryBean.getInterceptSendToEndpoints());
366                builder.addPropertyValue("dataFormats", factoryBean.getDataFormats());
367                builder.addPropertyValue("transformers", factoryBean.getTransformers());
368                builder.addPropertyValue("validators", factoryBean.getValidators());
369                builder.addPropertyValue("onCompletions", factoryBean.getOnCompletions());
370                builder.addPropertyValue("onExceptions", factoryBean.getOnExceptions());
371                builder.addPropertyValue("builderRefs", factoryBean.getBuilderRefs());
372                builder.addPropertyValue("routeRefs", factoryBean.getRouteRefs());
373                builder.addPropertyValue("restRefs", factoryBean.getRestRefs());
374                builder.addPropertyValue("globalOptions", factoryBean.getGlobalOptions());
375                builder.addPropertyValue("packageScan", factoryBean.getPackageScan());
376                builder.addPropertyValue("contextScan", factoryBean.getContextScan());
377                if (factoryBean.getPackages().length > 0) {
378                    builder.addPropertyValue("packages", factoryBean.getPackages());
379                }
380                builder.addPropertyValue("camelPropertyPlaceholder", factoryBean.getCamelPropertyPlaceholder());
381                builder.addPropertyValue("camelJMXAgent", factoryBean.getCamelJMXAgent());
382                builder.addPropertyValue("camelStreamCachingStrategy", factoryBean.getCamelStreamCachingStrategy());
383                builder.addPropertyValue("camelRouteController", factoryBean.getCamelRouteController());
384                builder.addPropertyValue("threadPoolProfiles", factoryBean.getThreadPoolProfiles());
385                builder.addPropertyValue("beansFactory", factoryBean.getBeansFactory());
386                builder.addPropertyValue("beans", factoryBean.getBeans());
387                builder.addPropertyValue("defaultServiceCallConfiguration", factoryBean.getDefaultServiceCallConfiguration());
388                builder.addPropertyValue("serviceCallConfigurations", factoryBean.getServiceCallConfigurations());
389                builder.addPropertyValue("defaultHystrixConfiguration", factoryBean.getDefaultHystrixConfiguration());
390                builder.addPropertyValue("hystrixConfigurations", factoryBean.getHystrixConfigurations());
391                // add any depends-on
392                addDependsOn(factoryBean, builder);
393            }
394
395            NodeList list = element.getChildNodes();
396            int size = list.getLength();
397            for (int i = 0; i < size; i++) {
398                Node child = list.item(i);
399                if (child instanceof Element) {
400                    Element childElement = (Element) child;
401                    String localName = child.getLocalName();
402                    if (localName.equals("endpoint")) {
403                        registerEndpoint(childElement, parserContext, contextId);
404                    } else if (localName.equals("routeBuilder")) {
405                        addDependsOnToRouteBuilder(childElement, parserContext, contextId);
406                    } else {
407                        BeanDefinitionParser parser = parserMap.get(localName);
408                        if (parser != null) {
409                            BeanDefinition definition = parser.parse(childElement, parserContext);
410                            String id = childElement.getAttribute("id");
411                            if (ObjectHelper.isNotEmpty(id)) {
412                                parserContext.registerComponent(new BeanComponentDefinition(definition, id));
413                                // set the templates with the camel context
414                                if (localName.equals("template") || localName.equals("fluentTemplate") || localName.equals("consumerTemplate")
415                                        || localName.equals("proxy") || localName.equals("export")) {
416                                    // set the camel context
417                                    definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
418                                }
419                            }
420                        }
421                    }
422                }
423            }
424
425            // register templates if not already defined
426            registerTemplates(element, parserContext, contextId);
427
428            // lets inject the namespaces into any namespace aware POJOs
429            injectNamespaces(element, binder);
430
431            // inject bean post processor so we can support @Produce etc.
432            // no bean processor element so lets create it by our self
433            injectBeanPostProcessor(element, parserContext, contextId, builder);
434        }
435    }
436
437    protected void addDependsOn(CamelContextFactoryBean factoryBean, BeanDefinitionBuilder builder) {
438        String dependsOn = factoryBean.getDependsOn();
439        if (ObjectHelper.isNotEmpty(dependsOn)) {
440            // comma, whitespace and semi colon is valid separators in Spring depends-on
441            String[] depends = dependsOn.split(",|;|\\s");
442            if (depends == null) {
443                throw new IllegalArgumentException("Cannot separate depends-on, was: " + dependsOn);
444            } else {
445                for (String depend : depends) {
446                    depend = depend.trim();
447                    LOG.debug("Adding dependsOn {} to CamelContext({})", depend, factoryBean.getId());
448                    builder.addDependsOn(depend);
449                }
450            }
451        }
452    }
453
454    private void addDependsOnToRouteBuilder(Element childElement, ParserContext parserContext, String contextId) {
455        // setting the depends-on explicitly is required since Spring 3.0
456        String routeBuilderName = childElement.getAttribute("ref");
457        if (ObjectHelper.isNotEmpty(routeBuilderName)) {
458            // set depends-on to the context for a routeBuilder bean
459            try {
460                BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(routeBuilderName);
461                Method getDependsOn = definition.getClass().getMethod("getDependsOn", new Class[]{});
462                String[] dependsOn = (String[])getDependsOn.invoke(definition);
463                if (dependsOn == null || dependsOn.length == 0) {
464                    dependsOn = new String[]{contextId};
465                } else {
466                    String[] temp = new String[dependsOn.length + 1];
467                    System.arraycopy(dependsOn, 0, temp, 0, dependsOn.length);
468                    temp[dependsOn.length] = contextId;
469                    dependsOn = temp;
470                }
471                Method method = definition.getClass().getMethod("setDependsOn", String[].class);
472                method.invoke(definition, (Object)dependsOn);
473            } catch (Exception e) {
474                // Do nothing here
475            }
476        }
477    }
478
479    protected void injectNamespaces(Element element, Binder<Node> binder) {
480        NodeList list = element.getChildNodes();
481        Namespaces namespaces = null;
482        int size = list.getLength();
483        for (int i = 0; i < size; i++) {
484            Node child = list.item(i);
485            if (child instanceof Element) {
486                Element childElement = (Element) child;
487                Object object = binder.getJAXBNode(child);
488                if (object instanceof NamespaceAware) {
489                    NamespaceAware namespaceAware = (NamespaceAware) object;
490                    if (namespaces == null) {
491                        namespaces = NamespacesHelper.namespaces(element);
492                    }
493                    namespaces.configure(namespaceAware);
494                }
495                injectNamespaces(childElement, binder);
496            }
497        }
498    }
499
500    protected void injectBeanPostProcessor(Element element, ParserContext parserContext, String contextId, BeanDefinitionBuilder builder) {
501        Element childElement = element.getOwnerDocument().createElement("beanPostProcessor");
502        element.appendChild(childElement);
503
504        String beanPostProcessorId = contextId + ":beanPostProcessor";
505        childElement.setAttribute("id", beanPostProcessorId);
506        BeanDefinition definition = beanPostProcessorParser.parse(childElement, parserContext);
507        // only register to camel context id as a String. Then we can look it up later
508        // otherwise we get a circular reference in spring and it will not allow custom bean post processing
509        // see more at CAMEL-1663
510        definition.getPropertyValues().addPropertyValue("camelId", contextId);
511        builder.addPropertyReference("beanPostProcessor", beanPostProcessorId);
512    }
513
514    /**
515     * Used for auto registering producer, fluent producer and consumer templates if not already defined in XML.
516     */
517    protected void registerTemplates(Element element, ParserContext parserContext, String contextId) {
518        boolean template = false;
519        boolean fluentTemplate = false;
520        boolean consumerTemplate = false;
521
522        NodeList list = element.getChildNodes();
523        int size = list.getLength();
524        for (int i = 0; i < size; i++) {
525            Node child = list.item(i);
526            if (child instanceof Element) {
527                Element childElement = (Element) child;
528                String localName = childElement.getLocalName();
529                if ("template".equals(localName)) {
530                    template = true;
531                } else if ("fluentTemplate".equals(localName)) {
532                    fluentTemplate = true;
533                } else if ("consumerTemplate".equals(localName)) {
534                    consumerTemplate = true;
535                }
536            }
537        }
538
539        if (!template) {
540            // either we have not used template before or we have auto registered it already and therefore we
541            // need it to allow to do it so it can remove the existing auto registered as there is now a clash id
542            // since we have multiple camel contexts
543            boolean existing = autoRegisterMap.get("template") != null;
544            boolean inUse = false;
545            try {
546                inUse = parserContext.getRegistry().isBeanNameInUse("template");
547            } catch (BeanCreationException e) {
548                // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse
549                // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739)
550                LOG.debug("Error checking isBeanNameInUse(template). This exception will be ignored", e);
551            }
552            if (!inUse || existing) {
553                String id = "template";
554                // auto create a template
555                Element templateElement = element.getOwnerDocument().createElement("template");
556                templateElement.setAttribute("id", id);
557                BeanDefinitionParser parser = parserMap.get("template");
558                BeanDefinition definition = parser.parse(templateElement, parserContext);
559
560                // auto register it
561                autoRegisterBeanDefinition(id, definition, parserContext, contextId);
562            }
563        }
564
565        if (!fluentTemplate) {
566            // either we have not used fluentTemplate before or we have auto registered it already and therefore we
567            // need it to allow to do it so it can remove the existing auto registered as there is now a clash id
568            // since we have multiple camel contexts
569            boolean existing = autoRegisterMap.get("fluentTemplate") != null;
570            boolean inUse = false;
571            try {
572                inUse = parserContext.getRegistry().isBeanNameInUse("fluentTemplate");
573            } catch (BeanCreationException e) {
574                // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse
575                // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739)
576                LOG.debug("Error checking isBeanNameInUse(fluentTemplate). This exception will be ignored", e);
577            }
578            if (!inUse || existing) {
579                String id = "fluentTemplate";
580                // auto create a fluentTemplate
581                Element templateElement = element.getOwnerDocument().createElement("fluentTemplate");
582                templateElement.setAttribute("id", id);
583                BeanDefinitionParser parser = parserMap.get("fluentTemplate");
584                BeanDefinition definition = parser.parse(templateElement, parserContext);
585
586                // auto register it
587                autoRegisterBeanDefinition(id, definition, parserContext, contextId);
588            }
589        }
590
591        if (!consumerTemplate) {
592            // either we have not used template before or we have auto registered it already and therefore we
593            // need it to allow to do it so it can remove the existing auto registered as there is now a clash id
594            // since we have multiple camel contexts
595            boolean existing = autoRegisterMap.get("consumerTemplate") != null;
596            boolean inUse = false;
597            try {
598                inUse = parserContext.getRegistry().isBeanNameInUse("consumerTemplate");
599            } catch (BeanCreationException e) {
600                // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse
601                // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739)
602                LOG.debug("Error checking isBeanNameInUse(consumerTemplate). This exception will be ignored", e);
603            }
604            if (!inUse || existing) {
605                String id = "consumerTemplate";
606                // auto create a template
607                Element templateElement = element.getOwnerDocument().createElement("consumerTemplate");
608                templateElement.setAttribute("id", id);
609                BeanDefinitionParser parser = parserMap.get("consumerTemplate");
610                BeanDefinition definition = parser.parse(templateElement, parserContext);
611
612                // auto register it
613                autoRegisterBeanDefinition(id, definition, parserContext, contextId);
614            }
615        }
616
617    }
618
619    private void autoRegisterBeanDefinition(String id, BeanDefinition definition, ParserContext parserContext, String contextId) {
620        // it is a bit cumbersome to work with the spring bean definition parser
621        // as we kinda need to eagerly register the bean definition on the parser context
622        // and then later we might find out that we should not have done that in case we have multiple camel contexts
623        // that would have a id clash by auto registering the same bean definition with the same id such as a producer template
624
625        // see if we have already auto registered this id
626        BeanDefinition existing = autoRegisterMap.get(id);
627        if (existing == null) {
628            // no then add it to the map and register it
629            autoRegisterMap.put(id, definition);
630            parserContext.registerComponent(new BeanComponentDefinition(definition, id));
631            if (LOG.isDebugEnabled()) {
632                LOG.debug("Registered default: {} with id: {} on camel context: {}", definition.getBeanClassName(), id, contextId);
633            }
634        } else {
635            // ups we have already registered it before with same id, but on another camel context
636            // this is not good so we need to remove all traces of this auto registering.
637            // end user must manually add the needed XML elements and provide unique ids access all camel context himself.
638            LOG.debug("Unregistered default: {} with id: {} as we have multiple camel contexts and they must use unique ids."
639                    + " You must define the definition in the XML file manually to avoid id clashes when using multiple camel contexts",
640                    definition.getBeanClassName(), id);
641
642            parserContext.getRegistry().removeBeanDefinition(id);
643        }
644    }
645
646    private void registerEndpoint(Element childElement, ParserContext parserContext, String contextId) {
647        String id = childElement.getAttribute("id");
648        // must have an id to be registered
649        if (ObjectHelper.isNotEmpty(id)) {
650            // skip underscore as they are internal naming and should not be registered
651            if (id.startsWith("_")) {
652                LOG.debug("Skip registering endpoint starting with underscore: {}", id);
653                return;
654            }
655            BeanDefinition definition = endpointParser.parse(childElement, parserContext);
656            definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
657            // Need to add this dependency of CamelContext for Spring 3.0
658            try {
659                Method method = definition.getClass().getMethod("setDependsOn", String[].class);
660                method.invoke(definition, (Object) new String[]{contextId});
661            } catch (Exception e) {
662                // Do nothing here
663            }
664            parserContext.registerBeanComponent(new BeanComponentDefinition(definition, id));
665        }
666    }
667
668}