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.builder.xml.Namespaces;
033    import org.apache.camel.model.dataformat.ArtixDSDataFormat;
034    import org.apache.camel.model.dataformat.JaxbDataFormat;
035    import org.apache.camel.model.dataformat.SerializationDataFormat;
036    import org.apache.camel.model.dataformat.XMLBeansDataFormat;
037    import org.apache.camel.model.loadbalancer.RandomLoadBalanceStrategy;
038    import org.apache.camel.model.loadbalancer.RoundRobinLoadBalanceStrategy;
039    import org.apache.camel.model.loadbalancer.StickyLoadBalanceStrategy;
040    import org.apache.camel.model.loadbalancer.TopicLoadBalanceStrategy;
041    import org.apache.camel.spi.NamespaceAware;
042    import org.apache.camel.spring.CamelBeanPostProcessor;
043    import org.apache.camel.spring.CamelContextFactoryBean;
044    import org.apache.camel.spring.CamelTemplateFactoryBean;
045    import org.apache.camel.spring.EndpointFactoryBean;
046    import org.apache.camel.spring.remoting.CamelProxyFactoryBean;
047    import org.apache.camel.spring.remoting.CamelServiceExporter;
048    import org.apache.camel.util.ObjectHelper;
049    import org.springframework.beans.factory.BeanDefinitionStoreException;
050    import org.springframework.beans.factory.config.BeanDefinition;
051    import org.springframework.beans.factory.config.RuntimeBeanReference;
052    import org.springframework.beans.factory.parsing.BeanComponentDefinition;
053    import org.springframework.beans.factory.support.BeanDefinitionBuilder;
054    import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
055    import org.springframework.beans.factory.xml.ParserContext;
056    
057    
058    public class CamelNamespaceHandler extends NamespaceHandlerSupport {
059        public static final String JAXB_PACKAGES = "org.apache.camel.spring:org.apache.camel.model:org.apache.camel.model.config:"
060                                                   + "org.apache.camel.model.dataformat:org.apache.camel.model.language:org.apache.camel.model.loadbalancer";
061        protected BeanDefinitionParser endpointParser = new BeanDefinitionParser(EndpointFactoryBean.class);
062        protected BeanDefinitionParser beanPostProcessorParser = new BeanDefinitionParser(
063                                                                                          CamelBeanPostProcessor.class);
064        protected Set<String> parserElementNames = new HashSet<String>();
065        private JAXBContext jaxbContext;
066        private Map<String, BeanDefinitionParser> parserMap = new HashMap<String, BeanDefinitionParser>();
067        private Binder<Node> binder;
068    
069        public void init() {
070            // remoting
071            addBeanDefinitionParser("proxy", CamelProxyFactoryBean.class);
072            addBeanDefinitionParser("template", CamelTemplateFactoryBean.class);
073            addBeanDefinitionParser("export", CamelServiceExporter.class);
074    
075            // data types
076            addBeanDefinitionParser("artixDS", ArtixDSDataFormat.class);
077            addBeanDefinitionParser("jaxb", JaxbDataFormat.class);
078            addBeanDefinitionParser("serialization", SerializationDataFormat.class);
079            addBeanDefinitionParser("xmlBeans", XMLBeansDataFormat.class);
080    
081            // load balancers
082            addBeanDefinitionParser("roundRobin", RoundRobinLoadBalanceStrategy.class);
083            addBeanDefinitionParser("random", RandomLoadBalanceStrategy.class);
084            addBeanDefinitionParser("sticky", StickyLoadBalanceStrategy.class);
085            addBeanDefinitionParser("topic", TopicLoadBalanceStrategy.class);
086    
087            // TODO switch to use the above mechanism?
088            registerParser("endpoint", endpointParser);
089    
090            registerParser("camelContext", new CamelContextBeanDefinitionParser(CamelContextFactoryBean.class));
091        }
092    
093        private void addBeanDefinitionParser(String elementName, Class<?> type) {
094            BeanDefinitionParser parser = new BeanDefinitionParser(type);
095            registerParser(elementName, parser);
096            parserMap.put(elementName, parser);
097        }
098    
099        protected void createBeanPostProcessor(ParserContext parserContext, String contextId, Element childElement) {
100            String beanPostProcessorId = contextId + ":beanPostProcessor";
101            childElement.setAttribute("id", beanPostProcessorId);
102            BeanDefinition definition = beanPostProcessorParser.parse(childElement, parserContext);
103            definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
104        }
105    
106        protected void registerScriptParser(String elementName, String engineName) {
107            registerParser(elementName, new ScriptDefinitionParser(engineName));
108        }
109    
110        protected void registerParser(String name,
111                                      org.springframework.beans.factory.xml.BeanDefinitionParser parser) {
112            parserElementNames.add(name);
113            registerBeanDefinitionParser(name, parser);
114        }
115    
116        public Set<String> getParserElementNames() {
117            return parserElementNames;
118        }
119    
120        protected Object parseUsingJaxb(Element element, ParserContext parserContext) {
121            try {
122                binder = getJaxbContext().createBinder();
123                return binder.unmarshal(element);
124                /*
125                 * Unmarshaller unmarshaller =
126                 * getJaxbContext().createUnmarshaller(); return
127                 * unmarshaller.unmarshal(element);
128                 */
129            } catch (JAXBException e) {
130                throw new BeanDefinitionStoreException("Failed to parse JAXB element: " + e, e);
131            }
132        }
133    
134        protected JAXBContext getJaxbContext() throws JAXBException {
135            if (jaxbContext == null) {
136                jaxbContext = createJaxbContext();
137            }
138            return jaxbContext;
139        }
140    
141        protected JAXBContext createJaxbContext() throws JAXBException {
142            return JAXBContext.newInstance(JAXB_PACKAGES);
143        }
144    
145        protected class CamelContextBeanDefinitionParser extends BeanDefinitionParser {
146            public CamelContextBeanDefinitionParser(Class type) {
147                super(type);
148            }
149    
150            @Override
151            protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
152                super.doParse(element, parserContext, builder);
153    
154                String contextId = element.getAttribute("id");
155    
156                // lets avoid folks having to explicitly give an ID to a camel
157                // context
158                if (ObjectHelper.isNullOrBlank(contextId)) {
159                    contextId = "camelContext";
160                    element.setAttribute("id", contextId);
161                }
162    
163                // now lets parse the routes
164                Object value = parseUsingJaxb(element, parserContext);
165                if (value instanceof CamelContextFactoryBean) {
166                    CamelContextFactoryBean factoryBean = (CamelContextFactoryBean)value;
167                    builder.addPropertyValue("id", contextId);
168                    builder.addPropertyValue("routes", factoryBean.getRoutes());
169                    builder.addPropertyValue("builderRefs", factoryBean.getBuilderRefs());
170    
171                    if (factoryBean.getPackages().length > 0) {
172                        builder.addPropertyValue("packages", factoryBean.getPackages());
173                    }
174                }
175    
176                boolean createdBeanPostProcessor = false;
177                NodeList list = element.getChildNodes();
178                int size = list.getLength();
179                for (int i = 0; i < size; i++) {
180                    Node child = list.item(i);
181                    if (child instanceof Element) {
182                        Element childElement = (Element)child;
183                        String localName = child.getLocalName();
184                        if (localName.equals("beanPostProcessor")) {
185                            createBeanPostProcessor(parserContext, contextId, childElement);
186                            createdBeanPostProcessor = true;
187                        } else if (localName.equals("endpoint")) {
188                            BeanDefinition definition = endpointParser.parse(childElement, parserContext);
189                            String id = childElement.getAttribute("id");
190                            if (ObjectHelper.isNotNullAndNonEmpty(id)) {
191                                // TODO we can zap this?
192                                definition.getPropertyValues()
193                                    .addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
194                                // definition.getPropertyValues().addPropertyValue("context",
195                                // builder.getBeanDefinition());
196                                parserContext.registerComponent(new BeanComponentDefinition(definition, id));
197                            }
198                        } else {
199                            BeanDefinitionParser parser = parserMap.get(localName);
200                            if (parser != null) {
201                                BeanDefinition definition = parser.parse(childElement, parserContext);
202                                String id = childElement.getAttribute("id");
203                                if (ObjectHelper.isNotNullAndNonEmpty(id)) {
204                                    parserContext.registerComponent(new BeanComponentDefinition(definition, id));
205                                }
206                            }
207                        }
208                    }
209                }
210                // lets inject the namespaces into any namespace aware POJOs
211                injectNamespaces(element);
212                if (!createdBeanPostProcessor) {
213                    // no bean processor element so lets add a fake one
214                    Element childElement = element.getOwnerDocument().createElement("beanPostProcessor");
215                    element.appendChild(childElement);
216                    createBeanPostProcessor(parserContext, contextId, childElement);
217                }
218            }
219        }
220    
221        protected void injectNamespaces(Element element) {
222            NodeList list = element.getChildNodes();
223            Namespaces namespaces = null;
224            int size = list.getLength();
225            for (int i = 0; i < size; i++) {
226                Node child = list.item(i);
227                if (child instanceof Element) {
228                    Element childElement = (Element)child;
229                    Object object = binder.getJAXBNode(child);
230                    if (object instanceof NamespaceAware) {
231                        NamespaceAware namespaceAware = (NamespaceAware)object;
232                        if (namespaces == null) {
233                            namespaces = new Namespaces(element);
234                        }
235                        namespaces.configure(namespaceAware);
236                    }
237                    injectNamespaces(childElement);
238                }
239            }
240        }
241    }