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