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