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