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