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