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