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