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