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.spi.CamelContextNameStrategy; 041import org.apache.camel.spi.NamespaceAware; 042import org.apache.camel.spring.CamelBeanPostProcessor; 043import org.apache.camel.spring.CamelConsumerTemplateFactoryBean; 044import org.apache.camel.spring.CamelContextFactoryBean; 045import org.apache.camel.spring.CamelEndpointFactoryBean; 046import org.apache.camel.spring.CamelFluentProducerTemplateFactoryBean; 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.SpringModelJAXBContextFactory; 053import org.apache.camel.spring.remoting.CamelProxyFactoryBean; 054import org.apache.camel.spring.remoting.CamelServiceExporter; 055import org.apache.camel.util.ObjectHelper; 056import org.apache.camel.util.StringHelper; 057import org.apache.camel.util.spring.KeyStoreParametersFactoryBean; 058import org.apache.camel.util.spring.SSLContextParametersFactoryBean; 059import org.apache.camel.util.spring.SecureRandomParametersFactoryBean; 060import org.slf4j.Logger; 061import org.slf4j.LoggerFactory; 062import org.springframework.beans.factory.BeanCreationException; 063import org.springframework.beans.factory.BeanDefinitionStoreException; 064import org.springframework.beans.factory.config.BeanDefinition; 065import org.springframework.beans.factory.config.RuntimeBeanReference; 066import org.springframework.beans.factory.parsing.BeanComponentDefinition; 067import org.springframework.beans.factory.support.BeanDefinitionBuilder; 068import org.springframework.beans.factory.xml.NamespaceHandlerSupport; 069import org.springframework.beans.factory.xml.ParserContext; 070 071/** 072 * Camel namespace for the spring XML configuration file. 073 */ 074public class CamelNamespaceHandler extends NamespaceHandlerSupport { 075 private static final String SPRING_NS = "http://camel.apache.org/schema/spring"; 076 private static final Logger LOG = LoggerFactory.getLogger(CamelNamespaceHandler.class); 077 protected BeanDefinitionParser endpointParser = new EndpointDefinitionParser(); 078 protected BeanDefinitionParser beanPostProcessorParser = new BeanDefinitionParser(CamelBeanPostProcessor.class, false); 079 protected Set<String> parserElementNames = new HashSet<>(); 080 protected Map<String, BeanDefinitionParser> parserMap = new HashMap<>(); 081 082 private JAXBContext jaxbContext; 083 private Map<String, BeanDefinition> autoRegisterMap = new HashMap<>(); 084 085 /** 086 * Prepares the nodes before parsing. 087 */ 088 public static void doBeforeParse(Node node) { 089 if (node.getNodeType() == Node.ELEMENT_NODE) { 090 091 // ensure namespace with versions etc is renamed to be same namespace so we can parse using this handler 092 Document doc = node.getOwnerDocument(); 093 if (node.getNamespaceURI().startsWith(SPRING_NS + "/v")) { 094 doc.renameNode(node, SPRING_NS, node.getNodeName()); 095 } 096 097 // remove whitespace noise from uri, xxxUri attributes, eg new lines, and tabs etc, which allows end users to format 098 // their Camel routes in more human readable format, but at runtime those attributes must be trimmed 099 // the parser removes most of the noise, but keeps double spaces in the attribute values 100 NamedNodeMap map = node.getAttributes(); 101 for (int i = 0; i < map.getLength(); i++) { 102 Node att = map.item(i); 103 if (att.getNodeName().equals("uri") || att.getNodeName().endsWith("Uri")) { 104 final String value = att.getNodeValue(); 105 String before = StringHelper.before(value, "?"); 106 String after = StringHelper.after(value, "?"); 107 108 if (before != null && after != null) { 109 // remove all double spaces in the uri parameters 110 String changed = after.replaceAll("\\s{2,}", ""); 111 if (!after.equals(changed)) { 112 String newAtr = before.trim() + "?" + changed.trim(); 113 LOG.debug("Removed whitespace noise from attribute {} -> {}", value, newAtr); 114 att.setNodeValue(newAtr); 115 } 116 } 117 } 118 } 119 } 120 NodeList list = node.getChildNodes(); 121 for (int i = 0; i < list.getLength(); ++i) { 122 doBeforeParse(list.item(i)); 123 } 124 } 125 126 public void init() { 127 // register restContext parser 128 registerParser("restContext", new RestContextDefinitionParser()); 129 // register routeContext parser 130 registerParser("routeContext", new RouteContextDefinitionParser()); 131 // register endpoint parser 132 registerParser("endpoint", endpointParser); 133 134 addBeanDefinitionParser("keyStoreParameters", KeyStoreParametersFactoryBean.class, true, true); 135 addBeanDefinitionParser("secureRandomParameters", SecureRandomParametersFactoryBean.class, true, true); 136 registerBeanDefinitionParser("sslContextParameters", new SSLContextParametersFactoryBeanBeanDefinitionParser()); 137 138 addBeanDefinitionParser("proxy", CamelProxyFactoryBean.class, true, false); 139 addBeanDefinitionParser("template", CamelProducerTemplateFactoryBean.class, true, false); 140 addBeanDefinitionParser("fluentTemplate", CamelFluentProducerTemplateFactoryBean.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, hystrix, service call configurations 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 // error handler 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("transformers", factoryBean.getTransformers()); 385 builder.addPropertyValue("validators", factoryBean.getValidators()); 386 builder.addPropertyValue("onCompletions", factoryBean.getOnCompletions()); 387 builder.addPropertyValue("onExceptions", factoryBean.getOnExceptions()); 388 builder.addPropertyValue("builderRefs", factoryBean.getBuilderRefs()); 389 builder.addPropertyValue("routeRefs", factoryBean.getRouteRefs()); 390 builder.addPropertyValue("restRefs", factoryBean.getRestRefs()); 391 builder.addPropertyValue("globalOptions", factoryBean.getGlobalOptions()); 392 builder.addPropertyValue("packageScan", factoryBean.getPackageScan()); 393 builder.addPropertyValue("contextScan", factoryBean.getContextScan()); 394 if (factoryBean.getPackages().length > 0) { 395 builder.addPropertyValue("packages", factoryBean.getPackages()); 396 } 397 builder.addPropertyValue("camelPropertyPlaceholder", factoryBean.getCamelPropertyPlaceholder()); 398 builder.addPropertyValue("camelJMXAgent", factoryBean.getCamelJMXAgent()); 399 builder.addPropertyValue("camelStreamCachingStrategy", factoryBean.getCamelStreamCachingStrategy()); 400 builder.addPropertyValue("threadPoolProfiles", factoryBean.getThreadPoolProfiles()); 401 builder.addPropertyValue("beansFactory", factoryBean.getBeansFactory()); 402 builder.addPropertyValue("beans", factoryBean.getBeans()); 403 builder.addPropertyValue("defaultServiceCallConfiguration", factoryBean.getDefaultServiceCallConfiguration()); 404 builder.addPropertyValue("serviceCallConfigurations", factoryBean.getServiceCallConfigurations()); 405 builder.addPropertyValue("defaultHystrixConfiguration", factoryBean.getDefaultHystrixConfiguration()); 406 builder.addPropertyValue("hystrixConfigurations", factoryBean.getHystrixConfigurations()); 407 // add any depends-on 408 addDependsOn(factoryBean, builder); 409 } 410 411 NodeList list = element.getChildNodes(); 412 int size = list.getLength(); 413 for (int i = 0; i < size; i++) { 414 Node child = list.item(i); 415 if (child instanceof Element) { 416 Element childElement = (Element) child; 417 String localName = child.getLocalName(); 418 if (localName.equals("endpoint")) { 419 registerEndpoint(childElement, parserContext, contextId); 420 } else if (localName.equals("routeBuilder")) { 421 addDependsOnToRouteBuilder(childElement, parserContext, contextId); 422 } else { 423 BeanDefinitionParser parser = parserMap.get(localName); 424 if (parser != null) { 425 BeanDefinition definition = parser.parse(childElement, parserContext); 426 String id = childElement.getAttribute("id"); 427 if (ObjectHelper.isNotEmpty(id)) { 428 parserContext.registerComponent(new BeanComponentDefinition(definition, id)); 429 // set the templates with the camel context 430 if (localName.equals("template") || localName.equals("fluentTemplate") || localName.equals("consumerTemplate") 431 || localName.equals("proxy") || localName.equals("export")) { 432 // set the camel context 433 definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId)); 434 } 435 } 436 } 437 } 438 } 439 } 440 441 // register templates if not already defined 442 registerTemplates(element, parserContext, contextId); 443 444 // lets inject the namespaces into any namespace aware POJOs 445 injectNamespaces(element, binder); 446 447 // inject bean post processor so we can support @Produce etc. 448 // no bean processor element so lets create it by our self 449 injectBeanPostProcessor(element, parserContext, contextId, builder); 450 } 451 } 452 453 protected void addDependsOn(CamelContextFactoryBean factoryBean, BeanDefinitionBuilder builder) { 454 String dependsOn = factoryBean.getDependsOn(); 455 if (ObjectHelper.isNotEmpty(dependsOn)) { 456 // comma, whitespace and semi colon is valid separators in Spring depends-on 457 String[] depends = dependsOn.split(",|;|\\s"); 458 if (depends == null) { 459 throw new IllegalArgumentException("Cannot separate depends-on, was: " + dependsOn); 460 } else { 461 for (String depend : depends) { 462 depend = depend.trim(); 463 LOG.debug("Adding dependsOn {} to CamelContext({})", depend, factoryBean.getId()); 464 builder.addDependsOn(depend); 465 } 466 } 467 } 468 } 469 470 private void addDependsOnToRouteBuilder(Element childElement, ParserContext parserContext, String contextId) { 471 // setting the depends-on explicitly is required since Spring 3.0 472 String routeBuilderName = childElement.getAttribute("ref"); 473 if (ObjectHelper.isNotEmpty(routeBuilderName)) { 474 // set depends-on to the context for a routeBuilder bean 475 try { 476 BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(routeBuilderName); 477 Method getDependsOn = definition.getClass().getMethod("getDependsOn", new Class[]{}); 478 String[] dependsOn = (String[])getDependsOn.invoke(definition); 479 if (dependsOn == null || dependsOn.length == 0) { 480 dependsOn = new String[]{contextId}; 481 } else { 482 String[] temp = new String[dependsOn.length + 1]; 483 System.arraycopy(dependsOn, 0, temp, 0, dependsOn.length); 484 temp[dependsOn.length] = contextId; 485 dependsOn = temp; 486 } 487 Method method = definition.getClass().getMethod("setDependsOn", String[].class); 488 method.invoke(definition, (Object)dependsOn); 489 } catch (Exception e) { 490 // Do nothing here 491 } 492 } 493 } 494 495 protected void injectNamespaces(Element element, Binder<Node> binder) { 496 NodeList list = element.getChildNodes(); 497 Namespaces namespaces = null; 498 int size = list.getLength(); 499 for (int i = 0; i < size; i++) { 500 Node child = list.item(i); 501 if (child instanceof Element) { 502 Element childElement = (Element) child; 503 Object object = binder.getJAXBNode(child); 504 if (object instanceof NamespaceAware) { 505 NamespaceAware namespaceAware = (NamespaceAware) object; 506 if (namespaces == null) { 507 namespaces = new Namespaces(element); 508 } 509 namespaces.configure(namespaceAware); 510 } 511 injectNamespaces(childElement, binder); 512 } 513 } 514 } 515 516 protected void injectBeanPostProcessor(Element element, ParserContext parserContext, String contextId, BeanDefinitionBuilder builder) { 517 Element childElement = element.getOwnerDocument().createElement("beanPostProcessor"); 518 element.appendChild(childElement); 519 520 String beanPostProcessorId = contextId + ":beanPostProcessor"; 521 childElement.setAttribute("id", beanPostProcessorId); 522 BeanDefinition definition = beanPostProcessorParser.parse(childElement, parserContext); 523 // only register to camel context id as a String. Then we can look it up later 524 // otherwise we get a circular reference in spring and it will not allow custom bean post processing 525 // see more at CAMEL-1663 526 definition.getPropertyValues().addPropertyValue("camelId", contextId); 527 builder.addPropertyReference("beanPostProcessor", beanPostProcessorId); 528 } 529 530 /** 531 * Used for auto registering producer, fluent producer and consumer templates if not already defined in XML. 532 */ 533 protected void registerTemplates(Element element, ParserContext parserContext, String contextId) { 534 boolean template = false; 535 boolean fluentTemplate = false; 536 boolean consumerTemplate = false; 537 538 NodeList list = element.getChildNodes(); 539 int size = list.getLength(); 540 for (int i = 0; i < size; i++) { 541 Node child = list.item(i); 542 if (child instanceof Element) { 543 Element childElement = (Element) child; 544 String localName = childElement.getLocalName(); 545 if ("template".equals(localName)) { 546 template = true; 547 } else if ("fluentTemplate".equals(localName)) { 548 fluentTemplate = true; 549 } else if ("consumerTemplate".equals(localName)) { 550 consumerTemplate = true; 551 } 552 } 553 } 554 555 if (!template) { 556 // either we have not used template before or we have auto registered it already and therefore we 557 // need it to allow to do it so it can remove the existing auto registered as there is now a clash id 558 // since we have multiple camel contexts 559 boolean existing = autoRegisterMap.get("template") != null; 560 boolean inUse = false; 561 try { 562 inUse = parserContext.getRegistry().isBeanNameInUse("template"); 563 } catch (BeanCreationException e) { 564 // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse 565 // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739) 566 LOG.debug("Error checking isBeanNameInUse(template). This exception will be ignored", e); 567 } 568 if (!inUse || existing) { 569 String id = "template"; 570 // auto create a template 571 Element templateElement = element.getOwnerDocument().createElement("template"); 572 templateElement.setAttribute("id", id); 573 BeanDefinitionParser parser = parserMap.get("template"); 574 BeanDefinition definition = parser.parse(templateElement, parserContext); 575 576 // auto register it 577 autoRegisterBeanDefinition(id, definition, parserContext, contextId); 578 } 579 } 580 581 if (!fluentTemplate) { 582 // either we have not used fluentTemplate before or we have auto registered it already and therefore we 583 // need it to allow to do it so it can remove the existing auto registered as there is now a clash id 584 // since we have multiple camel contexts 585 boolean existing = autoRegisterMap.get("fluentTemplate") != null; 586 boolean inUse = false; 587 try { 588 inUse = parserContext.getRegistry().isBeanNameInUse("fluentTemplate"); 589 } catch (BeanCreationException e) { 590 // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse 591 // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739) 592 LOG.debug("Error checking isBeanNameInUse(fluentTemplate). This exception will be ignored", e); 593 } 594 if (!inUse || existing) { 595 String id = "fluentTemplate"; 596 // auto create a fluentTemplate 597 Element templateElement = element.getOwnerDocument().createElement("fluentTemplate"); 598 templateElement.setAttribute("id", id); 599 BeanDefinitionParser parser = parserMap.get("fluentTemplate"); 600 BeanDefinition definition = parser.parse(templateElement, parserContext); 601 602 // auto register it 603 autoRegisterBeanDefinition(id, definition, parserContext, contextId); 604 } 605 } 606 607 if (!consumerTemplate) { 608 // either we have not used template before or we have auto registered it already and therefore we 609 // need it to allow to do it so it can remove the existing auto registered as there is now a clash id 610 // since we have multiple camel contexts 611 boolean existing = autoRegisterMap.get("consumerTemplate") != null; 612 boolean inUse = false; 613 try { 614 inUse = parserContext.getRegistry().isBeanNameInUse("consumerTemplate"); 615 } catch (BeanCreationException e) { 616 // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse 617 // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739) 618 LOG.debug("Error checking isBeanNameInUse(consumerTemplate). This exception will be ignored", e); 619 } 620 if (!inUse || existing) { 621 String id = "consumerTemplate"; 622 // auto create a template 623 Element templateElement = element.getOwnerDocument().createElement("consumerTemplate"); 624 templateElement.setAttribute("id", id); 625 BeanDefinitionParser parser = parserMap.get("consumerTemplate"); 626 BeanDefinition definition = parser.parse(templateElement, parserContext); 627 628 // auto register it 629 autoRegisterBeanDefinition(id, definition, parserContext, contextId); 630 } 631 } 632 633 } 634 635 private void autoRegisterBeanDefinition(String id, BeanDefinition definition, ParserContext parserContext, String contextId) { 636 // it is a bit cumbersome to work with the spring bean definition parser 637 // as we kinda need to eagerly register the bean definition on the parser context 638 // and then later we might find out that we should not have done that in case we have multiple camel contexts 639 // that would have a id clash by auto registering the same bean definition with the same id such as a producer template 640 641 // see if we have already auto registered this id 642 BeanDefinition existing = autoRegisterMap.get(id); 643 if (existing == null) { 644 // no then add it to the map and register it 645 autoRegisterMap.put(id, definition); 646 parserContext.registerComponent(new BeanComponentDefinition(definition, id)); 647 if (LOG.isDebugEnabled()) { 648 LOG.debug("Registered default: {} with id: {} on camel context: {}", definition.getBeanClassName(), id, contextId); 649 } 650 } else { 651 // ups we have already registered it before with same id, but on another camel context 652 // this is not good so we need to remove all traces of this auto registering. 653 // end user must manually add the needed XML elements and provide unique ids access all camel context himself. 654 LOG.debug("Unregistered default: {} with id: {} as we have multiple camel contexts and they must use unique ids." 655 + " You must define the definition in the XML file manually to avoid id clashes when using multiple camel contexts", 656 definition.getBeanClassName(), id); 657 658 parserContext.getRegistry().removeBeanDefinition(id); 659 } 660 } 661 662 private void registerEndpoint(Element childElement, ParserContext parserContext, String contextId) { 663 String id = childElement.getAttribute("id"); 664 // must have an id to be registered 665 if (ObjectHelper.isNotEmpty(id)) { 666 // skip underscore as they are internal naming and should not be registered 667 if (id.startsWith("_")) { 668 LOG.debug("Skip registering endpoint starting with underscore: {}", id); 669 return; 670 } 671 BeanDefinition definition = endpointParser.parse(childElement, parserContext); 672 definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId)); 673 // Need to add this dependency of CamelContext for Spring 3.0 674 try { 675 Method method = definition.getClass().getMethod("setDependsOn", String[].class); 676 method.invoke(definition, (Object) new String[]{contextId}); 677 } catch (Exception e) { 678 // Do nothing here 679 } 680 parserContext.registerBeanComponent(new BeanComponentDefinition(definition, id)); 681 } 682 } 683 684}