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    
028    import org.w3c.dom.Element;
029    import org.w3c.dom.Node;
030    import org.w3c.dom.NodeList;
031    
032    import org.apache.camel.ExchangePattern;
033    import org.apache.camel.builder.xml.Namespaces;
034    import org.apache.camel.model.dataformat.ArtixDSDataFormat;
035    import org.apache.camel.model.dataformat.JaxbDataFormat;
036    import org.apache.camel.model.dataformat.SerializationDataFormat;
037    import org.apache.camel.model.dataformat.XMLBeansDataFormat;
038    import org.apache.camel.model.loadbalancer.RandomLoadBalanceStrategy;
039    import org.apache.camel.model.loadbalancer.RoundRobinLoadBalanceStrategy;
040    import org.apache.camel.model.loadbalancer.StickyLoadBalanceStrategy;
041    import org.apache.camel.model.loadbalancer.TopicLoadBalanceStrategy;
042    import org.apache.camel.spi.NamespaceAware;
043    import org.apache.camel.spring.CamelBeanPostProcessor;
044    import org.apache.camel.spring.CamelContextFactoryBean;
045    import org.apache.camel.spring.CamelJMXAgentType;
046    import org.apache.camel.spring.CamelTemplateFactoryBean;
047    import org.apache.camel.spring.EndpointFactoryBean;
048    import org.apache.camel.spring.remoting.CamelProxyFactoryBean;
049    import org.apache.camel.spring.remoting.CamelServiceExporter;
050    import org.apache.camel.util.ObjectHelper;
051    import org.apache.camel.view.ModelFileGenerator;
052    import org.springframework.beans.factory.BeanDefinitionStoreException;
053    import org.springframework.beans.factory.config.BeanDefinition;
054    import org.springframework.beans.factory.config.RuntimeBeanReference;
055    import org.springframework.beans.factory.parsing.BeanComponentDefinition;
056    import org.springframework.beans.factory.support.BeanDefinitionBuilder;
057    import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
058    import org.springframework.beans.factory.xml.ParserContext;
059    
060    
061    
062    /**
063     * Camel namespace for the spring XML configuration file.
064     */
065    public class CamelNamespaceHandler extends NamespaceHandlerSupport {
066    
067        protected BeanDefinitionParser endpointParser = new BeanDefinitionParser(EndpointFactoryBean.class);
068        protected BeanDefinitionParser beanPostProcessorParser = new BeanDefinitionParser(CamelBeanPostProcessor.class);
069        protected Set<String> parserElementNames = new HashSet<String>();
070        protected Binder<Node> binder;
071        private JAXBContext jaxbContext;
072        private Map<String, BeanDefinitionParser> parserMap = new HashMap<String, BeanDefinitionParser>();
073    
074    
075        public ModelFileGenerator createModelFileGenerator() throws JAXBException {
076            return new ModelFileGenerator(getJaxbContext());
077        }
078    
079    
080        public void init() {
081            // remoting
082            addBeanDefinitionParser("proxy", CamelProxyFactoryBean.class);
083            addBeanDefinitionParser("template", CamelTemplateFactoryBean.class);
084            addBeanDefinitionParser("export", CamelServiceExporter.class);
085    
086            // data types
087            addBeanDefinitionParser("artixDS", ArtixDSDataFormat.class);
088            addBeanDefinitionParser("jaxb", JaxbDataFormat.class);
089            addBeanDefinitionParser("serialization", SerializationDataFormat.class);
090            addBeanDefinitionParser("xmlBeans", XMLBeansDataFormat.class);
091    
092            // load balancers
093            addBeanDefinitionParser("roundRobin", RoundRobinLoadBalanceStrategy.class);
094            addBeanDefinitionParser("random", RandomLoadBalanceStrategy.class);
095            addBeanDefinitionParser("sticky", StickyLoadBalanceStrategy.class);
096            addBeanDefinitionParser("topic", TopicLoadBalanceStrategy.class);
097    
098            // jmx agent
099            addBeanDefinitionParser("jmxAgent", CamelJMXAgentType.class);
100    
101            // TODO switch to use the above mechanism?
102            registerParser("endpoint", endpointParser);
103    
104            Class cl = CamelContextFactoryBean.class;
105            try {
106                cl = Class.forName("org.apache.camel.osgi.CamelContextFactoryBean");
107            } catch (Throwable t) {
108            }
109            registerParser("camelContext", new CamelContextBeanDefinitionParser(cl));
110        }
111    
112        private void addBeanDefinitionParser(String elementName, Class<?> type) {
113            BeanDefinitionParser parser = new BeanDefinitionParser(type);
114            registerParser(elementName, parser);
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            definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
123            parentBuilder.addPropertyReference("beanPostProcessor", beanPostProcessorId);
124        }
125    
126        protected void registerScriptParser(String elementName, String engineName) {
127            registerParser(elementName, new ScriptDefinitionParser(engineName));
128        }
129    
130        protected void registerParser(String name,
131                                      org.springframework.beans.factory.xml.BeanDefinitionParser parser) {
132            parserElementNames.add(name);
133            registerBeanDefinitionParser(name, parser);
134        }
135    
136        public Set<String> getParserElementNames() {
137            return parserElementNames;
138        }
139    
140        protected Object parseUsingJaxb(Element element, ParserContext parserContext) {
141            try {
142                binder = getJaxbContext().createBinder();
143                return binder.unmarshal(element);
144                /*
145                 * Unmarshaller unmarshaller =
146                 * getJaxbContext().createUnmarshaller(); return
147                 * unmarshaller.unmarshal(element);
148                 */
149            } catch (JAXBException e) {
150                throw new BeanDefinitionStoreException("Failed to parse JAXB element: " + e, e);
151            }
152        }
153    
154        public JAXBContext getJaxbContext() throws JAXBException {
155            if (jaxbContext == null) {
156                jaxbContext = createJaxbContext();
157            }
158            return jaxbContext;
159        }
160    
161        protected JAXBContext createJaxbContext() throws JAXBException {
162            StringBuilder packages = new StringBuilder();
163            for (Class cl : getJaxbPackages()) {
164                if (packages.length() > 0) {
165                    packages.append(":");
166                }
167                packages.append(cl.getName().substring(0, cl.getName().lastIndexOf('.')));
168            }
169            return JAXBContext.newInstance(packages.toString(), getClass().getClassLoader());
170        }
171    
172        protected Set<Class> getJaxbPackages() {
173            Set<Class> classes = new HashSet<Class>();
174            classes.add(org.apache.camel.spring.CamelContextFactoryBean.class);
175            classes.add(ExchangePattern.class);
176            classes.add(org.apache.camel.model.RouteType.class);
177            classes.add(org.apache.camel.model.config.StreamResequencerConfig.class);
178            classes.add(org.apache.camel.model.dataformat.DataFormatType.class);
179            classes.add(org.apache.camel.model.language.ExpressionType.class);
180            classes.add(org.apache.camel.model.loadbalancer.LoadBalancerType.class);
181            return classes;
182        }
183    
184        protected class CamelContextBeanDefinitionParser extends BeanDefinitionParser {
185            public CamelContextBeanDefinitionParser(Class type) {
186                super(type);
187            }
188    
189            @Override
190            protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
191                super.doParse(element, parserContext, builder);
192    
193                String contextId = element.getAttribute("id");
194    
195                // lets avoid folks having to explicitly give an ID to a camel
196                // context
197                if (ObjectHelper.isNullOrBlank(contextId)) {
198                    contextId = "camelContext";
199                    element.setAttribute("id", contextId);
200                }
201    
202                // now lets parse the routes
203                Object value = parseUsingJaxb(element, parserContext);
204                if (value instanceof CamelContextFactoryBean) {
205                    CamelContextFactoryBean factoryBean = (CamelContextFactoryBean)value;
206                    builder.addPropertyValue("id", contextId);
207                    builder.addPropertyValue("routes", factoryBean.getRoutes());
208                    builder.addPropertyValue("intercepts", factoryBean.getIntercepts());
209                    builder.addPropertyValue("dataFormats", factoryBean.getDataFormats());
210                    builder.addPropertyValue("builderRefs", factoryBean.getBuilderRefs());
211    
212                    if (factoryBean.getPackages().length > 0) {
213                        builder.addPropertyValue("packages", factoryBean.getPackages());
214                    }
215                }
216    
217                boolean createdBeanPostProcessor = false;
218                NodeList list = element.getChildNodes();
219                int size = list.getLength();
220                for (int i = 0; i < size; i++) {
221                    Node child = list.item(i);
222                    if (child instanceof Element) {
223                        Element childElement = (Element)child;
224                        String localName = child.getLocalName();
225                        if (localName.equals("beanPostProcessor")) {
226                            createBeanPostProcessor(parserContext, contextId, childElement, builder);
227                            createdBeanPostProcessor = true;
228                        } else if (localName.equals("endpoint")) {
229                            BeanDefinition definition = endpointParser.parse(childElement, parserContext);
230                            String id = childElement.getAttribute("id");
231                            if (ObjectHelper.isNotNullAndNonEmpty(id)) {
232                                // TODO we can zap this?
233                                definition.getPropertyValues()
234                                    .addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
235                                // definition.getPropertyValues().addPropertyValue("context",
236                                // builder.getBeanDefinition());
237                                parserContext.registerComponent(new BeanComponentDefinition(definition, id));
238                            }
239                        } else {
240                            BeanDefinitionParser parser = parserMap.get(localName);
241                            if (parser != null) {
242                                BeanDefinition definition = parser.parse(childElement, parserContext);
243                                String id = childElement.getAttribute("id");
244                                if (ObjectHelper.isNotNullAndNonEmpty(id)) {
245                                    parserContext.registerComponent(new BeanComponentDefinition(definition, id));
246                                    if (localName.equals("jmxAgent")) {
247                                        builder.addPropertyReference("camelJMXAgent", id);
248                                    }
249                                }
250                            }
251    
252                        }
253                    }
254                }
255                // lets inject the namespaces into any namespace aware POJOs
256                injectNamespaces(element);
257                if (!createdBeanPostProcessor) {
258                    // no bean processor element so lets create it by ourself
259                    Element childElement = element.getOwnerDocument().createElement("beanPostProcessor");
260                    element.appendChild(childElement);
261                    createBeanPostProcessor(parserContext, contextId, childElement, builder);
262                }
263            }
264        }
265    
266        protected void injectNamespaces(Element element) {
267            NodeList list = element.getChildNodes();
268            Namespaces namespaces = null;
269            int size = list.getLength();
270            for (int i = 0; i < size; i++) {
271                Node child = list.item(i);
272                if (child instanceof Element) {
273                    Element childElement = (Element)child;
274                    Object object = binder.getJAXBNode(child);
275                    if (object instanceof NamespaceAware) {
276                        NamespaceAware namespaceAware = (NamespaceAware)object;
277                        if (namespaces == null) {
278                            namespaces = new Namespaces(element);
279                        }
280                        namespaces.configure(namespaceAware);
281                    }
282                    injectNamespaces(childElement);
283                }
284            }
285        }
286    }