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.util.HashMap;
020    import java.util.HashSet;
021    import java.util.Map;
022    import java.util.Set;
023    
024    import javax.xml.bind.Binder;
025    import javax.xml.bind.JAXBContext;
026    import javax.xml.bind.JAXBException;
027    import org.w3c.dom.Element;
028    import org.w3c.dom.Node;
029    import org.w3c.dom.NodeList;
030    
031    import org.apache.camel.builder.xml.Namespaces;
032    import org.apache.camel.model.FromDefinition;
033    import org.apache.camel.model.SendDefinition;
034    import org.apache.camel.spi.NamespaceAware;
035    import org.apache.camel.spring.CamelBeanPostProcessor;
036    import org.apache.camel.spring.CamelConsumerTemplateFactoryBean;
037    import org.apache.camel.spring.CamelContextFactoryBean;
038    import org.apache.camel.spring.CamelEndpointFactoryBean;
039    import org.apache.camel.spring.CamelJMXAgentDefinition;
040    import org.apache.camel.spring.CamelProducerTemplateFactoryBean;
041    import org.apache.camel.spring.remoting.CamelProxyFactoryBean;
042    import org.apache.camel.spring.remoting.CamelServiceExporter;
043    import org.apache.camel.util.ObjectHelper;
044    import org.apache.camel.view.ModelFileGenerator;
045    import org.apache.commons.logging.Log;
046    import org.apache.commons.logging.LogFactory;
047    import org.springframework.beans.factory.BeanDefinitionStoreException;
048    import org.springframework.beans.factory.config.BeanDefinition;
049    import org.springframework.beans.factory.config.RuntimeBeanReference;
050    import org.springframework.beans.factory.parsing.BeanComponentDefinition;
051    import org.springframework.beans.factory.support.BeanDefinitionBuilder;
052    import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
053    import org.springframework.beans.factory.xml.ParserContext;
054    
055    /**
056     * Camel namespace for the spring XML configuration file.
057     */
058    public class CamelNamespaceHandler extends NamespaceHandlerSupport {
059    
060        private static final Log LOG = LogFactory.getLog(CamelNamespaceHandler.class);
061        protected BeanDefinitionParser endpointParser = new BeanDefinitionParser(CamelEndpointFactoryBean.class);
062        protected BeanDefinitionParser beanPostProcessorParser = new BeanDefinitionParser(CamelBeanPostProcessor.class);
063        protected Set<String> parserElementNames = new HashSet<String>();
064        protected Binder<Node> binder;
065        private JAXBContext jaxbContext;
066        private Map<String, BeanDefinitionParser> parserMap = new HashMap<String, BeanDefinitionParser>();
067        private Map<String, BeanDefinition> autoRegisterMap = new HashMap<String, BeanDefinition>();
068    
069        public ModelFileGenerator createModelFileGenerator() throws JAXBException {
070            return new ModelFileGenerator(getJaxbContext());
071        }
072    
073        public void init() {
074            // These elements parser should be used inside the camel context
075            addBeanDefinitionParser("proxy", CamelProxyFactoryBean.class, false);
076            addBeanDefinitionParser("template", CamelProducerTemplateFactoryBean.class, false);
077            addBeanDefinitionParser("consumerTemplate", CamelConsumerTemplateFactoryBean.class, false);
078            addBeanDefinitionParser("export", CamelServiceExporter.class, false);
079           
080            // jmx agent cannot be used outside of the camel context
081            addBeanDefinitionParser("jmxAgent", CamelJMXAgentDefinition.class, false);
082    
083            // endpoint
084            // This element cannot be used out side of camel context
085            addBeanDefinitionParser("endpoint", CamelEndpointFactoryBean.class, false);
086    
087            // camel context
088            boolean osgi = false;
089            Class cl = CamelContextFactoryBean.class;
090            try {
091                cl = Class.forName("org.apache.camel.osgi.CamelContextFactoryBean");
092                osgi = true;
093            } catch (Throwable t) {
094                // not running with camel-osgi so we fallback to the regular factory bean
095                LOG.trace("Cannot find class so assuming not running in OSGI container: " + t.getMessage());
096            }
097    
098            if (osgi) {
099                LOG.info("camel-osgi.jar detected in classpath");
100            } else {
101                LOG.info("camel-osgi.jar not detected in classpath");
102            }
103    
104            if (LOG.isDebugEnabled()) {
105                LOG.debug("Using " + cl.getCanonicalName() + " as CamelContextBeanDefinitionParser");
106            }
107            registerParser("camelContext", new CamelContextBeanDefinitionParser(cl));
108        }
109    
110        private void addBeanDefinitionParser(String elementName, Class<?> type, boolean register) {
111            BeanDefinitionParser parser = new BeanDefinitionParser(type);
112            if (register) {
113                registerParser(elementName, parser);
114            }
115            parserMap.put(elementName, parser);
116        }
117    
118        protected void createBeanPostProcessor(ParserContext parserContext, String contextId, Element childElement, BeanDefinitionBuilder parentBuilder) {
119            String beanPostProcessorId = contextId + ":beanPostProcessor";
120            childElement.setAttribute("id", beanPostProcessorId);
121            BeanDefinition definition = beanPostProcessorParser.parse(childElement, parserContext);
122            // only register to camel context id as a String. Then we can look it up later
123            // otherwise we get a circular reference in spring and it will not allow custom bean post processing
124            // see more at CAMEL-1663
125            definition.getPropertyValues().addPropertyValue("camelId", contextId);
126            parentBuilder.addPropertyReference("beanPostProcessor", beanPostProcessorId);
127        }
128    
129        protected void registerScriptParser(String elementName, String engineName) {
130            registerParser(elementName, new ScriptDefinitionParser(engineName));
131        }
132    
133        protected void registerParser(String name, org.springframework.beans.factory.xml.BeanDefinitionParser parser) {
134            parserElementNames.add(name);
135            registerBeanDefinitionParser(name, parser);
136        }
137    
138        public Set<String> getParserElementNames() {
139            return parserElementNames;
140        }
141    
142        protected Object parseUsingJaxb(Element element, ParserContext parserContext) {
143            try {
144                binder = getJaxbContext().createBinder();
145                return binder.unmarshal(element);
146            } catch (JAXBException e) {
147                throw new BeanDefinitionStoreException("Failed to parse JAXB element: " + e, e);
148            }
149        }
150    
151        public JAXBContext getJaxbContext() throws JAXBException {
152            if (jaxbContext == null) {
153                jaxbContext = createJaxbContext();
154            }
155            return jaxbContext;
156        }
157    
158        protected JAXBContext createJaxbContext() throws JAXBException {
159            StringBuilder packages = new StringBuilder();
160            for (Class cl : getJaxbPackages()) {
161                if (packages.length() > 0) {
162                    packages.append(":");
163                }
164                packages.append(cl.getName().substring(0, cl.getName().lastIndexOf('.')));
165            }
166            return JAXBContext.newInstance(packages.toString(), getClass().getClassLoader());
167        }
168    
169        protected Set<Class> getJaxbPackages() {
170            Set<Class> classes = new HashSet<Class>();
171            classes.add(org.apache.camel.spring.CamelContextFactoryBean.class);
172            classes.add(org.apache.camel.ExchangePattern.class);
173            classes.add(org.apache.camel.model.RouteDefinition.class);
174            classes.add(org.apache.camel.model.config.StreamResequencerConfig.class);
175            classes.add(org.apache.camel.model.dataformat.DataFormatsDefinition.class);
176            classes.add(org.apache.camel.model.language.ExpressionDefinition.class);
177            classes.add(org.apache.camel.model.loadbalancer.RoundRobinLoadBalancerDefinition.class);
178            return classes;
179        }
180    
181        protected class CamelContextBeanDefinitionParser extends BeanDefinitionParser {
182            public CamelContextBeanDefinitionParser(Class type) {
183                super(type);
184            }
185    
186            @Override
187            protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
188                super.doParse(element, parserContext, builder);
189    
190                String contextId = element.getAttribute("id");
191    
192                // lets avoid folks having to explicitly give an ID to a camel context
193                if (ObjectHelper.isEmpty(contextId)) {
194                    contextId = "camelContext";
195                    element.setAttribute("id", contextId);
196                }
197    
198                // now lets parse the routes with JAXB
199                Object value = parseUsingJaxb(element, parserContext);
200                
201                if (value instanceof CamelContextFactoryBean) {
202                    // set the property value with the JAXB parsed value
203                    CamelContextFactoryBean factoryBean = (CamelContextFactoryBean)value;
204                    builder.addPropertyValue("id", contextId);
205                    builder.addPropertyValue("routes", factoryBean.getRoutes());
206                    builder.addPropertyValue("intercepts", factoryBean.getIntercepts());
207                    builder.addPropertyValue("interceptFroms", factoryBean.getInterceptFroms());
208                    builder.addPropertyValue("interceptSendToEndpoints", factoryBean.getInterceptSendToEndpoints());
209                    builder.addPropertyValue("dataFormats", factoryBean.getDataFormats());
210                    builder.addPropertyValue("onCompletions", factoryBean.getOnCompletions());
211                    builder.addPropertyValue("onExceptions", factoryBean.getOnExceptions());
212                    builder.addPropertyValue("builderRefs", factoryBean.getBuilderRefs());
213                    builder.addPropertyValue("properties", factoryBean.getProperties());
214                    builder.addPropertyValue("packageScan", factoryBean.getPackageScan());
215                    if (factoryBean.getPackages().length > 0) {
216                        builder.addPropertyValue("packages", factoryBean.getPackages());
217                    }
218                }
219    
220                boolean createdBeanPostProcessor = false;
221                NodeList list = element.getChildNodes();
222                int size = list.getLength();
223                for (int i = 0; i < size; i++) {
224                    Node child = list.item(i);
225                    if (child instanceof Element) {
226                        Element childElement = (Element)child;
227                        String localName = child.getLocalName();
228                        if (localName.equals("beanPostProcessor")) {
229                            createBeanPostProcessor(parserContext, contextId, childElement, builder);
230                            createdBeanPostProcessor = true;
231                        } else if (localName.equals("endpoint")) {
232                            registerEndpoint(childElement, parserContext, contextId);
233                        } else {
234                            BeanDefinitionParser parser = parserMap.get(localName);
235                            if (parser != null) {
236                                BeanDefinition definition = parser.parse(childElement, parserContext);
237                                String id = childElement.getAttribute("id");
238                                if (ObjectHelper.isNotEmpty(id)) {
239                                    parserContext.registerComponent(new BeanComponentDefinition(definition, id));
240                                    if (localName.equals("jmxAgent")) {
241                                        builder.addPropertyReference("camelJMXAgent", id);
242                                    }
243                                    // set the templates with the camel context 
244                                    if (localName.equals("template") || localName.equals("consumerTemplate")
245                                        || localName.equals("proxy") || localName.equals("export")) {
246                                        // set the camel context 
247                                        definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
248                                    }   
249                                }
250                            }
251                        }
252                    }
253                }
254               
255    
256                // register as endpoint defined indirectly in the routes by from/to types having id explict set
257                registerEndpointsWithIdsDefinedInFromOrToTypes(element, parserContext, contextId);
258    
259                // register templates if not already defined
260                registerTemplates(element, parserContext, contextId);
261    
262                // lets inject the namespaces into any namespace aware POJOs
263                injectNamespaces(element);
264                if (!createdBeanPostProcessor) {
265                    // no bean processor element so lets create it by ourself
266                    Element childElement = element.getOwnerDocument().createElement("beanPostProcessor");
267                    element.appendChild(childElement);
268                    createBeanPostProcessor(parserContext, contextId, childElement, builder);
269                }
270            }
271    
272        }
273    
274        protected void injectNamespaces(Element element) {
275            NodeList list = element.getChildNodes();
276            Namespaces namespaces = null;
277            int size = list.getLength();
278            for (int i = 0; i < size; i++) {
279                Node child = list.item(i);
280                if (child instanceof Element) {
281                    Element childElement = (Element)child;
282                    Object object = binder.getJAXBNode(child);
283                    if (object instanceof NamespaceAware) {
284                        NamespaceAware namespaceAware = (NamespaceAware)object;
285                        if (namespaces == null) {
286                            namespaces = new Namespaces(element);
287                        }
288                        namespaces.configure(namespaceAware);
289                    }
290                    injectNamespaces(childElement);
291                }
292            }
293        }
294    
295        /**
296         * Used for auto registering endpoints from the <tt>from</tt> or <tt>to</tt> DSL if they have an id attribute set
297         */
298        protected void registerEndpointsWithIdsDefinedInFromOrToTypes(Element element, ParserContext parserContext, String contextId) {
299            NodeList list = element.getChildNodes();
300            int size = list.getLength();
301            for (int i = 0; i < size; i++) {
302                Node child = list.item(i);
303                if (child instanceof Element) {
304                    Element childElement = (Element)child;
305                    Object object = binder.getJAXBNode(child);
306                    // we only want from/to types to be registered as endpoints
307                    if (object instanceof FromDefinition || object instanceof SendDefinition) {
308                        registerEndpoint(childElement, parserContext, contextId);
309                    }
310                    // recursive
311                    registerEndpointsWithIdsDefinedInFromOrToTypes(childElement, parserContext, contextId);
312                }
313            }
314        }
315    
316        /**
317         * Used for auto registering producer and consumer templates if not already defined in XML.
318         */
319        protected void registerTemplates(Element element, ParserContext parserContext, String contextId) {
320            boolean template = false;
321            boolean consumerTemplate = false;
322    
323            NodeList list = element.getChildNodes();
324            int size = list.getLength();
325            for (int i = 0; i < size; i++) {
326                Node child = list.item(i);
327                if (child instanceof Element) {
328                    Element childElement = (Element)child;
329                    String localName = childElement.getLocalName();
330                    if ("template".equals(localName)) {
331                        template = true;
332                    } else if ("consumerTemplate".equals(localName)) {
333                        consumerTemplate = true;
334                    }
335                }
336            }
337    
338            // either we have not used templat before or we have auto registered it already and therefore we
339            // need it to allow to do it so it can remove the existing auto registered as there is now a clash id
340            // since we have multiple camel contexts
341            boolean canDoTemplate = autoRegisterMap.get("template") != null
342                    || !parserContext.getRegistry().isBeanNameInUse("template");
343            if (!template && canDoTemplate) {
344                String id = "template";
345                // auto create a template
346                Element templateElement = element.getOwnerDocument().createElement("template");
347                templateElement.setAttribute("id", id);
348                BeanDefinitionParser parser = parserMap.get("template");
349                BeanDefinition definition = parser.parse(templateElement, parserContext);
350    
351                // auto register it
352                autoRegisterBeanDefinition(id, definition, parserContext, contextId);
353            }
354    
355            // either we have not used templat before or we have auto registered it already and therefore we
356            // need it to allow to do it so it can remove the existing auto registered as there is now a clash id
357            // since we have multiple camel contexts
358            boolean canDoConsumerTemplate = autoRegisterMap.get("consumerTemplate") != null
359                    || !parserContext.getRegistry().isBeanNameInUse("consumerTemplate");
360            if (!consumerTemplate && canDoConsumerTemplate) {
361                String id = "consumerTemplate";
362                // auto create a template
363                Element templateElement = element.getOwnerDocument().createElement("consumerTemplate");
364                templateElement.setAttribute("id", id);
365                BeanDefinitionParser parser = parserMap.get("consumerTemplate");
366                BeanDefinition definition = parser.parse(templateElement, parserContext);
367    
368                // auto register it
369                autoRegisterBeanDefinition(id, definition, parserContext, contextId);
370            }
371    
372        }
373    
374        private void autoRegisterBeanDefinition(String id, BeanDefinition definition, ParserContext parserContext, String contextId) {
375            // it is a bit cumbersome to work with the spring bean definition parser
376            // as we kinda need to eagerly register the bean definition on the parser context
377            // and then later we might find out that we should not have done that in case we have multiple camel contexts
378            // that would have a id clash by auto regsitering the same bean definition with the same id such as a producer template
379    
380            // see if we have already auto registered this id
381            BeanDefinition existing = autoRegisterMap.get(id);
382            if (existing == null) {
383                // no then add it to the map and register it
384                autoRegisterMap.put(id, definition);
385                parserContext.registerComponent(new BeanComponentDefinition(definition, id));
386                if (LOG.isDebugEnabled()) {
387                    LOG.debug("Registered default: " + definition.getBeanClassName() + " with id: " + id + " on camel context: " + contextId);
388                }
389            } else {
390                // ups we have already registered it before with same id, but on another camel context
391                // this is not good so we need to remove all traces of this auto registering.
392                // end user must manually add the needed XML elements and provide unique ids access all camel context himself.
393                if (LOG.isDebugEnabled()) {
394                    LOG.debug("Unregistered default: " + definition.getBeanClassName() + " with id: " + id
395                        + " as we have multiple camel contexts and they must use unique ids."
396                        + " You must define the defintion in the XML file manually to avoid id clashes when using multiple camel contexts");
397                }
398    
399                parserContext.getRegistry().removeBeanDefinition(id);
400            }
401        }
402    
403        private void registerEndpoint(Element childElement, ParserContext parserContext, String contextId) {
404            String id = childElement.getAttribute("id");
405            // must have an id to be registered
406            if (ObjectHelper.isNotEmpty(id)) {
407                BeanDefinition definition = endpointParser.parse(childElement, parserContext);
408                definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
409                parserContext.registerComponent(new BeanComponentDefinition(definition, id));
410            }
411        }
412        
413    }