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     */
017    package org.apache.camel.spring.handler;
018    
019    import java.lang.reflect.Method;
020    import java.util.HashMap;
021    import java.util.HashSet;
022    import java.util.Map;
023    import java.util.Set;
024    
025    import javax.xml.bind.Binder;
026    import javax.xml.bind.JAXBContext;
027    import javax.xml.bind.JAXBException;
028    
029    import org.w3c.dom.Document;
030    import org.w3c.dom.Element;
031    import org.w3c.dom.Node;
032    import org.w3c.dom.NodeList;
033    
034    import org.apache.camel.builder.xml.Namespaces;
035    import org.apache.camel.model.FromDefinition;
036    import org.apache.camel.model.SendDefinition;
037    import org.apache.camel.spi.NamespaceAware;
038    import org.apache.camel.spring.CamelBeanPostProcessor;
039    import org.apache.camel.spring.CamelConsumerTemplateFactoryBean;
040    import org.apache.camel.spring.CamelContextFactoryBean;
041    import org.apache.camel.spring.CamelEndpointFactoryBean;
042    import org.apache.camel.spring.CamelJMXAgentDefinition;
043    import org.apache.camel.spring.CamelProducerTemplateFactoryBean;
044    import org.apache.camel.spring.CamelPropertyPlaceholderDefinition;
045    import org.apache.camel.spring.CamelRouteContextFactoryBean;
046    import org.apache.camel.spring.CamelThreadPoolFactoryBean;
047    import org.apache.camel.spring.remoting.CamelProxyFactoryBean;
048    import org.apache.camel.spring.remoting.CamelServiceExporter;
049    import org.apache.camel.util.ObjectHelper;
050    import org.apache.camel.view.ModelFileGenerator;
051    import org.apache.commons.logging.Log;
052    import org.apache.commons.logging.LogFactory;
053    import org.springframework.beans.factory.BeanCreationException;
054    import org.springframework.beans.factory.BeanDefinitionStoreException;
055    import org.springframework.beans.factory.config.BeanDefinition;
056    import org.springframework.beans.factory.config.RuntimeBeanReference;
057    import org.springframework.beans.factory.parsing.BeanComponentDefinition;
058    import org.springframework.beans.factory.support.BeanDefinitionBuilder;
059    import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
060    import org.springframework.beans.factory.xml.ParserContext;
061    
062    /**
063     * Camel namespace for the spring XML configuration file.
064     */
065    public class CamelNamespaceHandler extends NamespaceHandlerSupport {
066        private static final String SPRING_NS = "http://camel.apache.org/schema/spring";
067        private static final Log LOG = LogFactory.getLog(CamelNamespaceHandler.class);
068        protected BeanDefinitionParser endpointParser = new BeanDefinitionParser(CamelEndpointFactoryBean.class);
069        protected BeanDefinitionParser beanPostProcessorParser = new BeanDefinitionParser(CamelBeanPostProcessor.class);
070        protected Set<String> parserElementNames = new HashSet<String>();
071        private JAXBContext jaxbContext;
072        private Map<String, BeanDefinitionParser> parserMap = new HashMap<String, BeanDefinitionParser>();
073        private Map<String, BeanDefinition> autoRegisterMap = new HashMap<String, BeanDefinition>();
074    
075        public static void renameNamespaceRecursive(Node node) {
076            if (node.getNodeType() == Node.ELEMENT_NODE) {
077                Document doc = node.getOwnerDocument();
078                if (node.getNamespaceURI().startsWith(SPRING_NS + "/v")) {
079                    doc.renameNode(node, SPRING_NS, node.getNodeName());
080                }
081            }
082            NodeList list = node.getChildNodes();
083            for (int i = 0; i < list.getLength(); ++i) {
084                renameNamespaceRecursive(list.item(i));
085            }
086        }
087    
088        public ModelFileGenerator createModelFileGenerator() throws JAXBException {
089            return new ModelFileGenerator(getJaxbContext());
090        }
091    
092        public void init() {
093            // register routeContext parser
094            registerParser("routeContext", new RouteContextDefinitionParser());
095    
096            addBeanDefinitionParser("proxy", CamelProxyFactoryBean.class, true);
097            addBeanDefinitionParser("template", CamelProducerTemplateFactoryBean.class, true);
098            addBeanDefinitionParser("consumerTemplate", CamelConsumerTemplateFactoryBean.class, true);
099            addBeanDefinitionParser("export", CamelServiceExporter.class, true);
100            addBeanDefinitionParser("endpoint", CamelEndpointFactoryBean.class, true);
101            addBeanDefinitionParser("threadPool", CamelThreadPoolFactoryBean.class, true);
102    
103            // jmx agent and property placeholder cannot be used outside of the camel context
104            addBeanDefinitionParser("jmxAgent", CamelJMXAgentDefinition.class, false);
105            addBeanDefinitionParser("propertyPlaceholder", CamelPropertyPlaceholderDefinition.class, false);
106    
107            // errorhandler could be the sub element of camelContext or defined outside camelContext
108            BeanDefinitionParser errorHandlerParser = new ErrorHandlerDefinitionParser();
109            registerParser("errorHandler", errorHandlerParser);
110            parserMap.put("errorHandler", errorHandlerParser);
111    
112            // camel context
113            boolean osgi = false;
114            Class cl = CamelContextFactoryBean.class;
115            try {
116                cl = Class.forName("org.apache.camel.osgi.CamelContextFactoryBean");
117                osgi = true;
118            } catch (Throwable t) {
119                // not running with camel-osgi so we fallback to the regular factory bean
120                LOG.trace("Cannot find class so assuming not running in OSGi container: " + t.getMessage());
121            }
122            if (osgi) {
123                LOG.info("camel-osgi.jar/camel-spring-osgi.jar detected in classpath");
124            } else {
125                LOG.info("camel-osgi.jar/camel-spring-osgi.jar not detected in classpath");
126            }
127            if (LOG.isDebugEnabled()) {
128                LOG.debug("Using " + cl.getCanonicalName() + " as CamelContextBeanDefinitionParser");
129            }
130            registerParser("camelContext", new CamelContextBeanDefinitionParser(cl));
131        }
132    
133        private void addBeanDefinitionParser(String elementName, Class<?> type, boolean register) {
134            BeanDefinitionParser parser = new BeanDefinitionParser(type);
135            if (register) {
136                registerParser(elementName, parser);
137            }
138            parserMap.put(elementName, parser);
139        }
140    
141        protected void createBeanPostProcessor(ParserContext parserContext, String contextId, Element childElement, BeanDefinitionBuilder parentBuilder) {
142            String beanPostProcessorId = contextId + ":beanPostProcessor";
143            childElement.setAttribute("id", beanPostProcessorId);
144            BeanDefinition definition = beanPostProcessorParser.parse(childElement, parserContext);
145            // only register to camel context id as a String. Then we can look it up later
146            // otherwise we get a circular reference in spring and it will not allow custom bean post processing
147            // see more at CAMEL-1663
148            definition.getPropertyValues().addPropertyValue("camelId", contextId);
149            parentBuilder.addPropertyReference("beanPostProcessor", beanPostProcessorId);
150        }
151    
152        protected void registerParser(String name, org.springframework.beans.factory.xml.BeanDefinitionParser parser) {
153            parserElementNames.add(name);
154            registerBeanDefinitionParser(name, parser);
155        }
156    
157        protected Object parseUsingJaxb(Element element, ParserContext parserContext, Binder<Node> binder) {
158            try {
159                return binder.unmarshal(element);
160            } catch (JAXBException e) {
161                throw new BeanDefinitionStoreException("Failed to parse JAXB element", e);
162            }
163        }
164    
165        public JAXBContext getJaxbContext() throws JAXBException {
166            if (jaxbContext == null) {
167                jaxbContext = createJaxbContext();
168            }
169            return jaxbContext;
170        }
171    
172        protected JAXBContext createJaxbContext() throws JAXBException {
173            StringBuilder packages = new StringBuilder();
174            for (Class cl : getJaxbPackages()) {
175                if (packages.length() > 0) {
176                    packages.append(":");
177                }
178                packages.append(cl.getName().substring(0, cl.getName().lastIndexOf('.')));
179            }
180            return JAXBContext.newInstance(packages.toString(), getClass().getClassLoader());
181        }
182    
183        protected Set<Class> getJaxbPackages() {
184            Set<Class> classes = new HashSet<Class>();
185            classes.add(org.apache.camel.spring.CamelContextFactoryBean.class);
186            classes.add(org.apache.camel.ExchangePattern.class);
187            classes.add(org.apache.camel.model.RouteDefinition.class);
188            classes.add(org.apache.camel.model.config.StreamResequencerConfig.class);
189            classes.add(org.apache.camel.model.dataformat.DataFormatsDefinition.class);
190            classes.add(org.apache.camel.model.language.ExpressionDefinition.class);
191            classes.add(org.apache.camel.model.loadbalancer.RoundRobinLoadBalancerDefinition.class);
192            return classes;
193        }
194    
195        protected class RouteContextDefinitionParser extends BeanDefinitionParser {
196    
197            public RouteContextDefinitionParser() {
198                super(CamelRouteContextFactoryBean.class);
199            }
200    
201            @Override
202            protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
203                renameNamespaceRecursive(element);
204                super.doParse(element, parserContext, builder);
205    
206                // now lets parse the routes with JAXB
207                Binder<Node> binder;
208                try {
209                    binder = getJaxbContext().createBinder();
210                } catch (JAXBException e) {
211                    throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e);
212                }
213                Object value = parseUsingJaxb(element, parserContext, binder);
214    
215                if (value instanceof CamelRouteContextFactoryBean) {
216                    CamelRouteContextFactoryBean factoryBean = (CamelRouteContextFactoryBean)value;
217                    builder.addPropertyValue("routes", factoryBean.getRoutes());
218                }
219            }
220        }
221    
222    
223        protected class CamelContextBeanDefinitionParser extends BeanDefinitionParser {
224    
225            public CamelContextBeanDefinitionParser(Class type) {
226                super(type);
227            }
228    
229            @Override
230            protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
231                renameNamespaceRecursive(element);
232                super.doParse(element, parserContext, builder);
233    
234                String contextId = element.getAttribute("id");
235    
236                // lets avoid folks having to explicitly give an ID to a camel context
237                if (ObjectHelper.isEmpty(contextId)) {
238                    contextId = "camelContext";
239                    element.setAttribute("id", contextId);
240                }
241    
242                // now lets parse the routes with JAXB
243                Binder<Node> binder;
244                try {
245                    binder = getJaxbContext().createBinder();
246                } catch (JAXBException e) {
247                    throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e);
248                }
249                Object value = parseUsingJaxb(element, parserContext, binder);
250                
251                if (value instanceof CamelContextFactoryBean) {
252                    // set the property value with the JAXB parsed value
253                    CamelContextFactoryBean factoryBean = (CamelContextFactoryBean)value;
254                    builder.addPropertyValue("id", contextId);
255                    builder.addPropertyValue("routes", factoryBean.getRoutes());
256                    builder.addPropertyValue("intercepts", factoryBean.getIntercepts());
257                    builder.addPropertyValue("interceptFroms", factoryBean.getInterceptFroms());
258                    builder.addPropertyValue("interceptSendToEndpoints", factoryBean.getInterceptSendToEndpoints());
259                    builder.addPropertyValue("dataFormats", factoryBean.getDataFormats());
260                    builder.addPropertyValue("onCompletions", factoryBean.getOnCompletions());
261                    builder.addPropertyValue("onExceptions", factoryBean.getOnExceptions());
262                    builder.addPropertyValue("builderRefs", factoryBean.getBuilderRefs());
263                    builder.addPropertyValue("routeRefs", factoryBean.getRouteRefs());
264                    builder.addPropertyValue("properties", factoryBean.getProperties());
265                    builder.addPropertyValue("packageScan", factoryBean.getPackageScan());
266                    if (factoryBean.getPackages().length > 0) {
267                        builder.addPropertyValue("packages", factoryBean.getPackages());
268                    }
269                    builder.addPropertyValue("camelPropertyPlaceholder", factoryBean.getCamelPropertyPlaceholder());
270                    builder.addPropertyValue("camelJMXAgent", factoryBean.getCamelJMXAgent());
271                    builder.addPropertyValue("threadPoolProfiles", factoryBean.getThreadPoolProfiles());
272                    // add any depends-on
273                    addDependsOn(factoryBean, builder);
274                }
275    
276                boolean createdBeanPostProcessor = false;
277                NodeList list = element.getChildNodes();
278                int size = list.getLength();
279                for (int i = 0; i < size; i++) {
280                    Node child = list.item(i);
281                    if (child instanceof Element) {
282                        Element childElement = (Element)child;
283                        String localName = child.getLocalName();
284                        if (localName.equals("beanPostProcessor")) {
285                            createBeanPostProcessor(parserContext, contextId, childElement, builder);
286                            createdBeanPostProcessor = true;
287                        } else if (localName.equals("endpoint")) {
288                            registerEndpoint(childElement, parserContext, contextId);
289                        } else {
290                            BeanDefinitionParser parser = parserMap.get(localName);
291                            if (parser != null) {
292                                BeanDefinition definition = parser.parse(childElement, parserContext);
293                                String id = childElement.getAttribute("id");
294                                if (ObjectHelper.isNotEmpty(id)) {
295                                    parserContext.registerComponent(new BeanComponentDefinition(definition, id));
296                                    // set the templates with the camel context
297                                    if (localName.equals("template") || localName.equals("consumerTemplate")
298                                        || localName.equals("proxy") || localName.equals("export")) {
299                                        // set the camel context
300                                        definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
301                                    }
302                                }
303                            }
304                        }
305                    }
306                }
307    
308                // register as endpoint defined indirectly in the routes by from/to types having id explicit set
309                registerEndpointsWithIdsDefinedInFromOrToTypes(element, parserContext, contextId, binder);
310    
311                // register templates if not already defined
312                registerTemplates(element, parserContext, contextId);
313    
314                // lets inject the namespaces into any namespace aware POJOs
315                injectNamespaces(element, binder);
316                if (!createdBeanPostProcessor) {
317                    // no bean processor element so lets create it by our self
318                    Element childElement = element.getOwnerDocument().createElement("beanPostProcessor");
319                    element.appendChild(childElement);
320                    createBeanPostProcessor(parserContext, contextId, childElement, builder);
321                }
322            }
323        }
324    
325        protected void addDependsOn(CamelContextFactoryBean factoryBean, BeanDefinitionBuilder builder) {
326            String dependsOn = factoryBean.getDependsOn();
327            if (ObjectHelper.isNotEmpty(dependsOn)) {
328                // comma, whitespace and semi colon is valid separators in Spring depends-on
329                String[] depends = dependsOn.split(",|;|\\s");
330                if (depends == null) {
331                    throw new IllegalArgumentException("Cannot separate depends-on, was: " + dependsOn);
332                } else {
333                    for (String depend : depends) {
334                        depend = depend.trim();
335                        if (LOG.isDebugEnabled()) {
336                            LOG.debug("Adding dependsOn " + depend + " to CamelContext(" + factoryBean.getId() + ")");
337                        }
338                        builder.addDependsOn(depend);
339                    }
340                }
341            }
342        }
343    
344        protected void injectNamespaces(Element element, Binder<Node> binder) {
345            NodeList list = element.getChildNodes();
346            Namespaces namespaces = null;
347            int size = list.getLength();
348            for (int i = 0; i < size; i++) {
349                Node child = list.item(i);
350                if (child instanceof Element) {
351                    Element childElement = (Element)child;
352                    Object object = binder.getJAXBNode(child);
353                    if (object instanceof NamespaceAware) {
354                        NamespaceAware namespaceAware = (NamespaceAware)object;
355                        if (namespaces == null) {
356                            namespaces = new Namespaces(element);
357                        }
358                        namespaces.configure(namespaceAware);
359                    }
360                    injectNamespaces(childElement, binder);
361                }
362            }
363        }
364    
365        /**
366         * Used for auto registering endpoints from the <tt>from</tt> or <tt>to</tt> DSL if they have an id attribute set
367         */
368        protected void registerEndpointsWithIdsDefinedInFromOrToTypes(Element element, ParserContext parserContext, String contextId, Binder<Node> binder) {
369            NodeList list = element.getChildNodes();
370            int size = list.getLength();
371            for (int i = 0; i < size; i++) {
372                Node child = list.item(i);
373                if (child instanceof Element) {
374                    Element childElement = (Element)child;
375                    Object object = binder.getJAXBNode(child);
376                    // we only want from/to types to be registered as endpoints
377                    if (object instanceof FromDefinition || object instanceof SendDefinition) {
378                        registerEndpoint(childElement, parserContext, contextId);
379                    }
380                    // recursive
381                    registerEndpointsWithIdsDefinedInFromOrToTypes(childElement, parserContext, contextId, binder);
382                }
383            }
384        }
385    
386        /**
387         * Used for auto registering producer and consumer templates if not already defined in XML.
388         */
389        protected void registerTemplates(Element element, ParserContext parserContext, String contextId) {
390            boolean template = false;
391            boolean consumerTemplate = false;
392    
393            NodeList list = element.getChildNodes();
394            int size = list.getLength();
395            for (int i = 0; i < size; i++) {
396                Node child = list.item(i);
397                if (child instanceof Element) {
398                    Element childElement = (Element)child;
399                    String localName = childElement.getLocalName();
400                    if ("template".equals(localName)) {
401                        template = true;
402                    } else if ("consumerTemplate".equals(localName)) {
403                        consumerTemplate = true;
404                    }
405                }
406            }
407    
408            if (!template) {
409                // either we have not used template before or we have auto registered it already and therefore we
410                // need it to allow to do it so it can remove the existing auto registered as there is now a clash id
411                // since we have multiple camel contexts
412                boolean existing = autoRegisterMap.get("template") != null;
413                boolean inUse = false;
414                try {
415                    inUse = parserContext.getRegistry().isBeanNameInUse("template");
416                } catch (BeanCreationException e) {
417                    // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse
418                    // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739)
419                    LOG.debug("Error checking isBeanNameInUse(template). This exception will be ignored", e);
420                }
421                if (!inUse || existing) {
422                    String id = "template";
423                    // auto create a template
424                    Element templateElement = element.getOwnerDocument().createElement("template");
425                    templateElement.setAttribute("id", id);
426                    BeanDefinitionParser parser = parserMap.get("template");
427                    BeanDefinition definition = parser.parse(templateElement, parserContext);
428    
429                    // auto register it
430                    autoRegisterBeanDefinition(id, definition, parserContext, contextId);
431                }
432            }
433    
434            if (!consumerTemplate) {
435                // either we have not used template before or we have auto registered it already and therefore we
436                // need it to allow to do it so it can remove the existing auto registered as there is now a clash id
437                // since we have multiple camel contexts
438                boolean existing = autoRegisterMap.get("consumerTemplate") != null;
439                boolean inUse = false;
440                try {
441                    inUse = parserContext.getRegistry().isBeanNameInUse("consumerTemplate");
442                } catch (BeanCreationException e) {
443                    // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse
444                    // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739)
445                    LOG.debug("Error checking isBeanNameInUse(consumerTemplate). This exception will be ignored", e);
446                }
447                if (!inUse || existing) {
448                    String id = "consumerTemplate";
449                    // auto create a template
450                    Element templateElement = element.getOwnerDocument().createElement("consumerTemplate");
451                    templateElement.setAttribute("id", id);
452                    BeanDefinitionParser parser = parserMap.get("consumerTemplate");
453                    BeanDefinition definition = parser.parse(templateElement, parserContext);
454    
455                    // auto register it
456                    autoRegisterBeanDefinition(id, definition, parserContext, contextId);
457                }
458            }
459    
460        }
461    
462        private void autoRegisterBeanDefinition(String id, BeanDefinition definition, ParserContext parserContext, String contextId) {
463            // it is a bit cumbersome to work with the spring bean definition parser
464            // as we kinda need to eagerly register the bean definition on the parser context
465            // and then later we might find out that we should not have done that in case we have multiple camel contexts
466            // that would have a id clash by auto registering the same bean definition with the same id such as a producer template
467    
468            // see if we have already auto registered this id
469            BeanDefinition existing = autoRegisterMap.get(id);
470            if (existing == null) {
471                // no then add it to the map and register it
472                autoRegisterMap.put(id, definition);
473                parserContext.registerComponent(new BeanComponentDefinition(definition, id));
474                if (LOG.isDebugEnabled()) {
475                    LOG.debug("Registered default: " + definition.getBeanClassName() + " with id: " + id + " on camel context: " + contextId);
476                }
477            } else {
478                // ups we have already registered it before with same id, but on another camel context
479                // this is not good so we need to remove all traces of this auto registering.
480                // end user must manually add the needed XML elements and provide unique ids access all camel context himself.
481                if (LOG.isDebugEnabled()) {
482                    LOG.debug("Unregistered default: " + definition.getBeanClassName() + " with id: " + id
483                        + " as we have multiple camel contexts and they must use unique ids."
484                        + " You must define the definition in the XML file manually to avoid id clashes when using multiple camel contexts");
485                }
486    
487                parserContext.getRegistry().removeBeanDefinition(id);
488            }
489        }
490    
491        private void registerEndpoint(Element childElement, ParserContext parserContext, String contextId) {
492            String id = childElement.getAttribute("id");
493            // must have an id to be registered
494            if (ObjectHelper.isNotEmpty(id)) {
495                BeanDefinition definition = endpointParser.parse(childElement, parserContext);
496                definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
497                // Need to add this dependency of CamelContext for Spring 3.0
498                try {
499                    Method method = definition.getClass().getMethod("setDependsOn", String[].class);
500                    method.invoke(definition, (Object)new String[]{contextId});
501                } catch (Exception e) {
502                    // Do nothing here
503                }
504                parserContext.registerBeanComponent(new BeanComponentDefinition(definition, id));
505            }
506        }
507        
508    }