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