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