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