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 */ 017package org.apache.camel.spring.handler; 018 019import java.lang.reflect.Method; 020import java.util.HashMap; 021import java.util.HashSet; 022import java.util.Map; 023import java.util.Set; 024 025import javax.xml.bind.Binder; 026import javax.xml.bind.JAXBContext; 027import javax.xml.bind.JAXBException; 028 029import org.w3c.dom.Document; 030import org.w3c.dom.Element; 031import org.w3c.dom.NamedNodeMap; 032import org.w3c.dom.Node; 033import org.w3c.dom.NodeList; 034 035import org.apache.camel.builder.xml.Namespaces; 036import org.apache.camel.core.xml.CamelJMXAgentDefinition; 037import org.apache.camel.core.xml.CamelPropertyPlaceholderDefinition; 038import org.apache.camel.core.xml.CamelStreamCachingStrategyDefinition; 039import org.apache.camel.impl.DefaultCamelContextNameStrategy; 040import org.apache.camel.model.FromDefinition; 041import org.apache.camel.model.SendDefinition; 042import org.apache.camel.spi.CamelContextNameStrategy; 043import org.apache.camel.spi.NamespaceAware; 044import org.apache.camel.spring.CamelBeanPostProcessor; 045import org.apache.camel.spring.CamelConsumerTemplateFactoryBean; 046import org.apache.camel.spring.CamelContextFactoryBean; 047import org.apache.camel.spring.CamelEndpointFactoryBean; 048import org.apache.camel.spring.CamelProducerTemplateFactoryBean; 049import org.apache.camel.spring.CamelRedeliveryPolicyFactoryBean; 050import org.apache.camel.spring.CamelRestContextFactoryBean; 051import org.apache.camel.spring.CamelRouteContextFactoryBean; 052import org.apache.camel.spring.CamelThreadPoolFactoryBean; 053import org.apache.camel.spring.SpringModelJAXBContextFactory; 054import org.apache.camel.spring.remoting.CamelProxyFactoryBean; 055import org.apache.camel.spring.remoting.CamelServiceExporter; 056import org.apache.camel.util.ObjectHelper; 057import org.apache.camel.util.spring.KeyStoreParametersFactoryBean; 058import org.apache.camel.util.spring.SSLContextParametersFactoryBean; 059import org.apache.camel.util.spring.SecureRandomParametersFactoryBean; 060import org.apache.camel.view.ModelFileGenerator; 061import org.slf4j.Logger; 062import org.slf4j.LoggerFactory; 063import org.springframework.beans.factory.BeanCreationException; 064import org.springframework.beans.factory.BeanDefinitionStoreException; 065import org.springframework.beans.factory.config.BeanDefinition; 066import org.springframework.beans.factory.config.RuntimeBeanReference; 067import org.springframework.beans.factory.parsing.BeanComponentDefinition; 068import org.springframework.beans.factory.support.BeanDefinitionBuilder; 069import org.springframework.beans.factory.xml.NamespaceHandlerSupport; 070import org.springframework.beans.factory.xml.ParserContext; 071 072/** 073 * Camel namespace for the spring XML configuration file. 074 */ 075public class CamelNamespaceHandler extends NamespaceHandlerSupport { 076 private static final String SPRING_NS = "http://camel.apache.org/schema/spring"; 077 private static final Logger LOG = LoggerFactory.getLogger(CamelNamespaceHandler.class); 078 protected BeanDefinitionParser endpointParser = new EndpointDefinitionParser(); 079 protected BeanDefinitionParser beanPostProcessorParser = new BeanDefinitionParser(CamelBeanPostProcessor.class, false); 080 protected Set<String> parserElementNames = new HashSet<String>(); 081 protected Map<String, BeanDefinitionParser> parserMap = new HashMap<String, BeanDefinitionParser>(); 082 083 private JAXBContext jaxbContext; 084 private Map<String, BeanDefinition> autoRegisterMap = new HashMap<String, BeanDefinition>(); 085 086 /** 087 * Prepares the nodes before parsing. 088 */ 089 public static void doBeforeParse(Node node) { 090 if (node.getNodeType() == Node.ELEMENT_NODE) { 091 092 // ensure namespace with versions etc is renamed to be same namespace so we can parse using this handler 093 Document doc = node.getOwnerDocument(); 094 if (node.getNamespaceURI().startsWith(SPRING_NS + "/v")) { 095 doc.renameNode(node, SPRING_NS, node.getNodeName()); 096 } 097 098 // remove whitespace noise from uri, xxxUri attributes, eg new lines, and tabs etc, which allows end users to format 099 // their Camel routes in more human readable format, but at runtime those attributes must be trimmed 100 // the parser removes most of the noise, but keeps double spaces in the attribute values 101 NamedNodeMap map = node.getAttributes(); 102 for (int i = 0; i < map.getLength(); i++) { 103 Node att = map.item(i); 104 if (att.getNodeName().equals("uri") || att.getNodeName().endsWith("Uri")) { 105 106 String value = att.getNodeValue(); 107 // remove all double spaces 108 String changed = value.replaceAll("\\s{2,}", ""); 109 110 if (!value.equals(changed)) { 111 LOG.debug("Removed whitespace noise from attribute {} -> {}", value, changed); 112 att.setNodeValue(changed); 113 } 114 } 115 } 116 } 117 NodeList list = node.getChildNodes(); 118 for (int i = 0; i < list.getLength(); ++i) { 119 doBeforeParse(list.item(i)); 120 } 121 } 122 123 public ModelFileGenerator createModelFileGenerator() throws JAXBException { 124 return new ModelFileGenerator(getJaxbContext()); 125 } 126 127 public void init() { 128 // register restContext parser 129 registerParser("restContext", new RestContextDefinitionParser()); 130 // register routeContext parser 131 registerParser("routeContext", new RouteContextDefinitionParser()); 132 // register endpoint parser 133 registerParser("endpoint", endpointParser); 134 135 addBeanDefinitionParser("keyStoreParameters", KeyStoreParametersFactoryBean.class, true, true); 136 addBeanDefinitionParser("secureRandomParameters", SecureRandomParametersFactoryBean.class, true, true); 137 registerBeanDefinitionParser("sslContextParameters", new SSLContextParametersFactoryBeanBeanDefinitionParser()); 138 139 addBeanDefinitionParser("proxy", CamelProxyFactoryBean.class, true, false); 140 addBeanDefinitionParser("template", CamelProducerTemplateFactoryBean.class, true, false); 141 addBeanDefinitionParser("consumerTemplate", CamelConsumerTemplateFactoryBean.class, true, false); 142 addBeanDefinitionParser("export", CamelServiceExporter.class, true, false); 143 addBeanDefinitionParser("threadPool", CamelThreadPoolFactoryBean.class, true, true); 144 addBeanDefinitionParser("redeliveryPolicyProfile", CamelRedeliveryPolicyFactoryBean.class, true, true); 145 146 // jmx agent, stream caching, and property placeholder cannot be used outside of the camel context 147 addBeanDefinitionParser("jmxAgent", CamelJMXAgentDefinition.class, false, false); 148 addBeanDefinitionParser("streamCaching", CamelStreamCachingStrategyDefinition.class, false, false); 149 addBeanDefinitionParser("propertyPlaceholder", CamelPropertyPlaceholderDefinition.class, false, false); 150 151 // errorhandler could be the sub element of camelContext or defined outside camelContext 152 BeanDefinitionParser errorHandlerParser = new ErrorHandlerDefinitionParser(); 153 registerParser("errorHandler", errorHandlerParser); 154 parserMap.put("errorHandler", errorHandlerParser); 155 156 // camel context 157 boolean osgi = false; 158 Class<?> cl = CamelContextFactoryBean.class; 159 // These code will try to detected if we are in the OSGi environment. 160 // If so, camel will use the OSGi version of CamelContextFactoryBean to create the CamelContext. 161 try { 162 // Try to load the BundleActivator first 163 Class.forName("org.osgi.framework.BundleActivator"); 164 Class<?> c = Class.forName("org.apache.camel.osgi.Activator"); 165 Method mth = c.getDeclaredMethod("getBundle"); 166 Object bundle = mth.invoke(null); 167 if (bundle != null) { 168 cl = Class.forName("org.apache.camel.osgi.CamelContextFactoryBean"); 169 osgi = true; 170 } 171 } catch (Throwable t) { 172 // not running with camel-core-osgi so we fallback to the regular factory bean 173 LOG.trace("Cannot find class so assuming not running in OSGi container: " + t.getMessage()); 174 } 175 if (osgi) { 176 LOG.info("OSGi environment detected."); 177 } 178 LOG.debug("Using {} as CamelContextBeanDefinitionParser", cl.getCanonicalName()); 179 registerParser("camelContext", new CamelContextBeanDefinitionParser(cl)); 180 } 181 182 protected void addBeanDefinitionParser(String elementName, Class<?> type, boolean register, boolean assignId) { 183 BeanDefinitionParser parser = new BeanDefinitionParser(type, assignId); 184 if (register) { 185 registerParser(elementName, parser); 186 } 187 parserMap.put(elementName, parser); 188 } 189 190 protected void registerParser(String name, org.springframework.beans.factory.xml.BeanDefinitionParser parser) { 191 parserElementNames.add(name); 192 registerBeanDefinitionParser(name, parser); 193 } 194 195 protected Object parseUsingJaxb(Element element, ParserContext parserContext, Binder<Node> binder) { 196 try { 197 return binder.unmarshal(element); 198 } catch (JAXBException e) { 199 throw new BeanDefinitionStoreException("Failed to parse JAXB element", e); 200 } 201 } 202 203 public JAXBContext getJaxbContext() throws JAXBException { 204 if (jaxbContext == null) { 205 jaxbContext = new SpringModelJAXBContextFactory().newJAXBContext(); 206 } 207 return jaxbContext; 208 } 209 210 protected class SSLContextParametersFactoryBeanBeanDefinitionParser extends BeanDefinitionParser { 211 212 public SSLContextParametersFactoryBeanBeanDefinitionParser() { 213 super(SSLContextParametersFactoryBean.class, true); 214 } 215 216 @Override 217 protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { 218 doBeforeParse(element); 219 super.doParse(element, builder); 220 221 // Note: prefer to use doParse from parent and postProcess; however, parseUsingJaxb requires 222 // parserContext for no apparent reason. 223 Binder<Node> binder; 224 try { 225 binder = getJaxbContext().createBinder(); 226 } catch (JAXBException e) { 227 throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e); 228 } 229 230 Object value = parseUsingJaxb(element, parserContext, binder); 231 232 if (value instanceof SSLContextParametersFactoryBean) { 233 SSLContextParametersFactoryBean bean = (SSLContextParametersFactoryBean)value; 234 235 builder.addPropertyValue("cipherSuites", bean.getCipherSuites()); 236 builder.addPropertyValue("cipherSuitesFilter", bean.getCipherSuitesFilter()); 237 builder.addPropertyValue("secureSocketProtocols", bean.getSecureSocketProtocols()); 238 builder.addPropertyValue("secureSocketProtocolsFilter", bean.getSecureSocketProtocolsFilter()); 239 builder.addPropertyValue("keyManagers", bean.getKeyManagers()); 240 builder.addPropertyValue("trustManagers", bean.getTrustManagers()); 241 builder.addPropertyValue("secureRandom", bean.getSecureRandom()); 242 243 builder.addPropertyValue("clientParameters", bean.getClientParameters()); 244 builder.addPropertyValue("serverParameters", bean.getServerParameters()); 245 } else { 246 throw new BeanDefinitionStoreException("Parsed type is not of the expected type. Expected " 247 + SSLContextParametersFactoryBean.class.getName() + " but found " 248 + value.getClass().getName()); 249 } 250 } 251 } 252 253 protected class RouteContextDefinitionParser extends BeanDefinitionParser { 254 255 public RouteContextDefinitionParser() { 256 super(CamelRouteContextFactoryBean.class, false); 257 } 258 259 @Override 260 protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { 261 doBeforeParse(element); 262 super.doParse(element, parserContext, builder); 263 264 // now lets parse the routes with JAXB 265 Binder<Node> binder; 266 try { 267 binder = getJaxbContext().createBinder(); 268 } catch (JAXBException e) { 269 throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e); 270 } 271 Object value = parseUsingJaxb(element, parserContext, binder); 272 273 if (value instanceof CamelRouteContextFactoryBean) { 274 CamelRouteContextFactoryBean factoryBean = (CamelRouteContextFactoryBean) value; 275 builder.addPropertyValue("routes", factoryBean.getRoutes()); 276 } 277 278 // lets inject the namespaces into any namespace aware POJOs 279 injectNamespaces(element, binder); 280 } 281 } 282 283 protected class EndpointDefinitionParser extends BeanDefinitionParser { 284 285 public EndpointDefinitionParser() { 286 super(CamelEndpointFactoryBean.class, false); 287 } 288 289 @Override 290 protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { 291 doBeforeParse(element); 292 super.doParse(element, parserContext, builder); 293 294 // now lets parse the routes with JAXB 295 Binder<Node> binder; 296 try { 297 binder = getJaxbContext().createBinder(); 298 } catch (JAXBException e) { 299 throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e); 300 } 301 Object value = parseUsingJaxb(element, parserContext, binder); 302 303 if (value instanceof CamelEndpointFactoryBean) { 304 CamelEndpointFactoryBean factoryBean = (CamelEndpointFactoryBean) value; 305 builder.addPropertyValue("properties", factoryBean.getProperties()); 306 } 307 } 308 } 309 310 protected class RestContextDefinitionParser extends BeanDefinitionParser { 311 312 public RestContextDefinitionParser() { 313 super(CamelRestContextFactoryBean.class, false); 314 } 315 316 @Override 317 protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { 318 doBeforeParse(element); 319 super.doParse(element, parserContext, builder); 320 321 // now lets parse the routes with JAXB 322 Binder<Node> binder; 323 try { 324 binder = getJaxbContext().createBinder(); 325 } catch (JAXBException e) { 326 throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e); 327 } 328 Object value = parseUsingJaxb(element, parserContext, binder); 329 330 if (value instanceof CamelRestContextFactoryBean) { 331 CamelRestContextFactoryBean factoryBean = (CamelRestContextFactoryBean) value; 332 builder.addPropertyValue("rests", factoryBean.getRests()); 333 } 334 335 // lets inject the namespaces into any namespace aware POJOs 336 injectNamespaces(element, binder); 337 } 338 } 339 340 protected class CamelContextBeanDefinitionParser extends BeanDefinitionParser { 341 342 public CamelContextBeanDefinitionParser(Class<?> type) { 343 super(type, false); 344 } 345 346 @Override 347 protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { 348 doBeforeParse(element); 349 super.doParse(element, parserContext, builder); 350 351 String contextId = element.getAttribute("id"); 352 boolean implicitId = false; 353 354 // lets avoid folks having to explicitly give an ID to a camel context 355 if (ObjectHelper.isEmpty(contextId)) { 356 // if no explicit id was set then use a default auto generated name 357 CamelContextNameStrategy strategy = new DefaultCamelContextNameStrategy(); 358 contextId = strategy.getName(); 359 element.setAttributeNS(null, "id", contextId); 360 implicitId = true; 361 } 362 363 // now lets parse the routes with JAXB 364 Binder<Node> binder; 365 try { 366 binder = getJaxbContext().createBinder(); 367 } catch (JAXBException e) { 368 throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e); 369 } 370 Object value = parseUsingJaxb(element, parserContext, binder); 371 372 if (value instanceof CamelContextFactoryBean) { 373 // set the property value with the JAXB parsed value 374 CamelContextFactoryBean factoryBean = (CamelContextFactoryBean) value; 375 builder.addPropertyValue("id", contextId); 376 builder.addPropertyValue("implicitId", implicitId); 377 builder.addPropertyValue("restConfiguration", factoryBean.getRestConfiguration()); 378 builder.addPropertyValue("rests", factoryBean.getRests()); 379 builder.addPropertyValue("routes", factoryBean.getRoutes()); 380 builder.addPropertyValue("intercepts", factoryBean.getIntercepts()); 381 builder.addPropertyValue("interceptFroms", factoryBean.getInterceptFroms()); 382 builder.addPropertyValue("interceptSendToEndpoints", factoryBean.getInterceptSendToEndpoints()); 383 builder.addPropertyValue("dataFormats", factoryBean.getDataFormats()); 384 builder.addPropertyValue("onCompletions", factoryBean.getOnCompletions()); 385 builder.addPropertyValue("onExceptions", factoryBean.getOnExceptions()); 386 builder.addPropertyValue("builderRefs", factoryBean.getBuilderRefs()); 387 builder.addPropertyValue("routeRefs", factoryBean.getRouteRefs()); 388 builder.addPropertyValue("restRefs", factoryBean.getRestRefs()); 389 builder.addPropertyValue("properties", factoryBean.getProperties()); 390 builder.addPropertyValue("packageScan", factoryBean.getPackageScan()); 391 builder.addPropertyValue("contextScan", factoryBean.getContextScan()); 392 if (factoryBean.getPackages().length > 0) { 393 builder.addPropertyValue("packages", factoryBean.getPackages()); 394 } 395 builder.addPropertyValue("camelPropertyPlaceholder", factoryBean.getCamelPropertyPlaceholder()); 396 builder.addPropertyValue("camelJMXAgent", factoryBean.getCamelJMXAgent()); 397 builder.addPropertyValue("camelStreamCachingStrategy", factoryBean.getCamelStreamCachingStrategy()); 398 builder.addPropertyValue("threadPoolProfiles", factoryBean.getThreadPoolProfiles()); 399 // add any depends-on 400 addDependsOn(factoryBean, builder); 401 } 402 403 NodeList list = element.getChildNodes(); 404 int size = list.getLength(); 405 for (int i = 0; i < size; i++) { 406 Node child = list.item(i); 407 if (child instanceof Element) { 408 Element childElement = (Element) child; 409 String localName = child.getLocalName(); 410 if (localName.equals("endpoint")) { 411 registerEndpoint(childElement, parserContext, contextId); 412 } else if (localName.equals("routeBuilder")) { 413 addDependsOnToRouteBuilder(childElement, parserContext, contextId); 414 } else { 415 BeanDefinitionParser parser = parserMap.get(localName); 416 if (parser != null) { 417 BeanDefinition definition = parser.parse(childElement, parserContext); 418 String id = childElement.getAttribute("id"); 419 if (ObjectHelper.isNotEmpty(id)) { 420 parserContext.registerComponent(new BeanComponentDefinition(definition, id)); 421 // set the templates with the camel context 422 if (localName.equals("template") || localName.equals("consumerTemplate") 423 || localName.equals("proxy") || localName.equals("export")) { 424 // set the camel context 425 definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId)); 426 } 427 } 428 } 429 } 430 } 431 } 432 433 // register as endpoint defined indirectly in the routes by from/to types having id explicit set 434 registerEndpointsWithIdsDefinedInFromOrToTypes(element, parserContext, contextId, binder); 435 436 // register templates if not already defined 437 registerTemplates(element, parserContext, contextId); 438 439 // lets inject the namespaces into any namespace aware POJOs 440 injectNamespaces(element, binder); 441 442 // inject bean post processor so we can support @Produce etc. 443 // no bean processor element so lets create it by our self 444 injectBeanPostProcessor(element, parserContext, contextId, builder); 445 } 446 } 447 448 protected void addDependsOn(CamelContextFactoryBean factoryBean, BeanDefinitionBuilder builder) { 449 String dependsOn = factoryBean.getDependsOn(); 450 if (ObjectHelper.isNotEmpty(dependsOn)) { 451 // comma, whitespace and semi colon is valid separators in Spring depends-on 452 String[] depends = dependsOn.split(",|;|\\s"); 453 if (depends == null) { 454 throw new IllegalArgumentException("Cannot separate depends-on, was: " + dependsOn); 455 } else { 456 for (String depend : depends) { 457 depend = depend.trim(); 458 LOG.debug("Adding dependsOn {} to CamelContext({})", depend, factoryBean.getId()); 459 builder.addDependsOn(depend); 460 } 461 } 462 } 463 } 464 465 private void addDependsOnToRouteBuilder(Element childElement, ParserContext parserContext, String contextId) { 466 // setting the depends-on explicitly is required since Spring 3.0 467 String routeBuilderName = childElement.getAttribute("ref"); 468 if (ObjectHelper.isNotEmpty(routeBuilderName)) { 469 // set depends-on to the context for a routeBuilder bean 470 try { 471 BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(routeBuilderName); 472 Method getDependsOn = definition.getClass().getMethod("getDependsOn", new Class[]{}); 473 String[] dependsOn = (String[])getDependsOn.invoke(definition); 474 if (dependsOn == null || dependsOn.length == 0) { 475 dependsOn = new String[]{contextId}; 476 } else { 477 String[] temp = new String[dependsOn.length + 1]; 478 System.arraycopy(dependsOn, 0, temp, 0, dependsOn.length); 479 temp[dependsOn.length] = contextId; 480 dependsOn = temp; 481 } 482 Method method = definition.getClass().getMethod("setDependsOn", String[].class); 483 method.invoke(definition, (Object)dependsOn); 484 } catch (Exception e) { 485 // Do nothing here 486 } 487 } 488 } 489 490 protected void injectNamespaces(Element element, Binder<Node> binder) { 491 NodeList list = element.getChildNodes(); 492 Namespaces namespaces = null; 493 int size = list.getLength(); 494 for (int i = 0; i < size; i++) { 495 Node child = list.item(i); 496 if (child instanceof Element) { 497 Element childElement = (Element) child; 498 Object object = binder.getJAXBNode(child); 499 if (object instanceof NamespaceAware) { 500 NamespaceAware namespaceAware = (NamespaceAware) object; 501 if (namespaces == null) { 502 namespaces = new Namespaces(element); 503 } 504 namespaces.configure(namespaceAware); 505 } 506 injectNamespaces(childElement, binder); 507 } 508 } 509 } 510 511 protected void injectBeanPostProcessor(Element element, ParserContext parserContext, String contextId, BeanDefinitionBuilder builder) { 512 Element childElement = element.getOwnerDocument().createElement("beanPostProcessor"); 513 element.appendChild(childElement); 514 515 String beanPostProcessorId = contextId + ":beanPostProcessor"; 516 childElement.setAttribute("id", beanPostProcessorId); 517 BeanDefinition definition = beanPostProcessorParser.parse(childElement, parserContext); 518 // only register to camel context id as a String. Then we can look it up later 519 // otherwise we get a circular reference in spring and it will not allow custom bean post processing 520 // see more at CAMEL-1663 521 definition.getPropertyValues().addPropertyValue("camelId", contextId); 522 builder.addPropertyReference("beanPostProcessor", beanPostProcessorId); 523 } 524 525 /** 526 * Used for auto registering endpoints from the <tt>from</tt> or <tt>to</tt> DSL if they have an id attribute set 527 */ 528 protected void registerEndpointsWithIdsDefinedInFromOrToTypes(Element element, ParserContext parserContext, String contextId, Binder<Node> binder) { 529 NodeList list = element.getChildNodes(); 530 int size = list.getLength(); 531 for (int i = 0; i < size; i++) { 532 Node child = list.item(i); 533 if (child instanceof Element) { 534 Element childElement = (Element) child; 535 Object object = binder.getJAXBNode(child); 536 // we only want from/to types to be registered as endpoints 537 if (object instanceof FromDefinition || object instanceof SendDefinition) { 538 registerEndpoint(childElement, parserContext, contextId); 539 } 540 // recursive 541 registerEndpointsWithIdsDefinedInFromOrToTypes(childElement, parserContext, contextId, binder); 542 } 543 } 544 } 545 546 /** 547 * Used for auto registering producer and consumer templates if not already defined in XML. 548 */ 549 protected void registerTemplates(Element element, ParserContext parserContext, String contextId) { 550 boolean template = false; 551 boolean consumerTemplate = false; 552 553 NodeList list = element.getChildNodes(); 554 int size = list.getLength(); 555 for (int i = 0; i < size; i++) { 556 Node child = list.item(i); 557 if (child instanceof Element) { 558 Element childElement = (Element) child; 559 String localName = childElement.getLocalName(); 560 if ("template".equals(localName)) { 561 template = true; 562 } else if ("consumerTemplate".equals(localName)) { 563 consumerTemplate = true; 564 } 565 } 566 } 567 568 if (!template) { 569 // either we have not used template before or we have auto registered it already and therefore we 570 // need it to allow to do it so it can remove the existing auto registered as there is now a clash id 571 // since we have multiple camel contexts 572 boolean existing = autoRegisterMap.get("template") != null; 573 boolean inUse = false; 574 try { 575 inUse = parserContext.getRegistry().isBeanNameInUse("template"); 576 } catch (BeanCreationException e) { 577 // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse 578 // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739) 579 LOG.debug("Error checking isBeanNameInUse(template). This exception will be ignored", e); 580 } 581 if (!inUse || existing) { 582 String id = "template"; 583 // auto create a template 584 Element templateElement = element.getOwnerDocument().createElement("template"); 585 templateElement.setAttribute("id", id); 586 BeanDefinitionParser parser = parserMap.get("template"); 587 BeanDefinition definition = parser.parse(templateElement, parserContext); 588 589 // auto register it 590 autoRegisterBeanDefinition(id, definition, parserContext, contextId); 591 } 592 } 593 594 if (!consumerTemplate) { 595 // either we have not used template before or we have auto registered it already and therefore we 596 // need it to allow to do it so it can remove the existing auto registered as there is now a clash id 597 // since we have multiple camel contexts 598 boolean existing = autoRegisterMap.get("consumerTemplate") != null; 599 boolean inUse = false; 600 try { 601 inUse = parserContext.getRegistry().isBeanNameInUse("consumerTemplate"); 602 } catch (BeanCreationException e) { 603 // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse 604 // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739) 605 LOG.debug("Error checking isBeanNameInUse(consumerTemplate). This exception will be ignored", e); 606 } 607 if (!inUse || existing) { 608 String id = "consumerTemplate"; 609 // auto create a template 610 Element templateElement = element.getOwnerDocument().createElement("consumerTemplate"); 611 templateElement.setAttribute("id", id); 612 BeanDefinitionParser parser = parserMap.get("consumerTemplate"); 613 BeanDefinition definition = parser.parse(templateElement, parserContext); 614 615 // auto register it 616 autoRegisterBeanDefinition(id, definition, parserContext, contextId); 617 } 618 } 619 620 } 621 622 private void autoRegisterBeanDefinition(String id, BeanDefinition definition, ParserContext parserContext, String contextId) { 623 // it is a bit cumbersome to work with the spring bean definition parser 624 // as we kinda need to eagerly register the bean definition on the parser context 625 // and then later we might find out that we should not have done that in case we have multiple camel contexts 626 // that would have a id clash by auto registering the same bean definition with the same id such as a producer template 627 628 // see if we have already auto registered this id 629 BeanDefinition existing = autoRegisterMap.get(id); 630 if (existing == null) { 631 // no then add it to the map and register it 632 autoRegisterMap.put(id, definition); 633 parserContext.registerComponent(new BeanComponentDefinition(definition, id)); 634 if (LOG.isDebugEnabled()) { 635 LOG.debug("Registered default: {} with id: {} on camel context: {}", new Object[]{definition.getBeanClassName(), id, contextId}); 636 } 637 } else { 638 // ups we have already registered it before with same id, but on another camel context 639 // this is not good so we need to remove all traces of this auto registering. 640 // end user must manually add the needed XML elements and provide unique ids access all camel context himself. 641 LOG.debug("Unregistered default: {} with id: {} as we have multiple camel contexts and they must use unique ids." 642 + " You must define the definition in the XML file manually to avoid id clashes when using multiple camel contexts", 643 definition.getBeanClassName(), id); 644 645 parserContext.getRegistry().removeBeanDefinition(id); 646 } 647 } 648 649 private void registerEndpoint(Element childElement, ParserContext parserContext, String contextId) { 650 String id = childElement.getAttribute("id"); 651 // must have an id to be registered 652 if (ObjectHelper.isNotEmpty(id)) { 653 BeanDefinition definition = endpointParser.parse(childElement, parserContext); 654 definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId)); 655 // Need to add this dependency of CamelContext for Spring 3.0 656 try { 657 Method method = definition.getClass().getMethod("setDependsOn", String[].class); 658 method.invoke(definition, (Object) new String[]{contextId}); 659 } catch (Exception e) { 660 // Do nothing here 661 } 662 parserContext.registerBeanComponent(new BeanComponentDefinition(definition, id)); 663 } 664 } 665 666}