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 if (value instanceof CamelContextFactoryBean) { 390 // set the property value with the JAXB parsed value 391 CamelContextFactoryBean factoryBean = (CamelContextFactoryBean) value; 392 builder.addPropertyValue("id", contextId); 393 builder.addPropertyValue("implicitId", implicitId); 394 builder.addPropertyValue("restConfiguration", factoryBean.getRestConfiguration()); 395 builder.addPropertyValue("rests", factoryBean.getRests()); 396 builder.addPropertyValue("routeTemplates", factoryBean.getRouteTemplates()); 397 builder.addPropertyValue("routes", factoryBean.getRoutes()); 398 builder.addPropertyValue("intercepts", factoryBean.getIntercepts()); 399 builder.addPropertyValue("interceptFroms", factoryBean.getInterceptFroms()); 400 builder.addPropertyValue("interceptSendToEndpoints", factoryBean.getInterceptSendToEndpoints()); 401 builder.addPropertyValue("dataFormats", factoryBean.getDataFormats()); 402 builder.addPropertyValue("transformers", factoryBean.getTransformers()); 403 builder.addPropertyValue("validators", factoryBean.getValidators()); 404 builder.addPropertyValue("onCompletions", factoryBean.getOnCompletions()); 405 builder.addPropertyValue("onExceptions", factoryBean.getOnExceptions()); 406 builder.addPropertyValue("routeTemplateRefs", factoryBean.getRouteTemplateRefs()); 407 builder.addPropertyValue("builderRefs", factoryBean.getBuilderRefs()); 408 builder.addPropertyValue("routeRefs", factoryBean.getRouteRefs()); 409 builder.addPropertyValue("restRefs", factoryBean.getRestRefs()); 410 builder.addPropertyValue("globalOptions", factoryBean.getGlobalOptions()); 411 builder.addPropertyValue("packageScan", factoryBean.getPackageScan()); 412 builder.addPropertyValue("contextScan", factoryBean.getContextScan()); 413 if (factoryBean.getPackages().length > 0) { 414 builder.addPropertyValue("packages", factoryBean.getPackages()); 415 } 416 builder.addPropertyValue("camelPropertyPlaceholder", factoryBean.getCamelPropertyPlaceholder()); 417 builder.addPropertyValue("camelJMXAgent", factoryBean.getCamelJMXAgent()); 418 builder.addPropertyValue("camelStreamCachingStrategy", factoryBean.getCamelStreamCachingStrategy()); 419 builder.addPropertyValue("camelRouteController", factoryBean.getCamelRouteController()); 420 builder.addPropertyValue("threadPoolProfiles", factoryBean.getThreadPoolProfiles()); 421 builder.addPropertyValue("beansFactory", factoryBean.getBeansFactory()); 422 builder.addPropertyValue("beans", factoryBean.getBeans()); 423 builder.addPropertyValue("defaultServiceCallConfiguration", factoryBean.getDefaultServiceCallConfiguration()); 424 builder.addPropertyValue("serviceCallConfigurations", factoryBean.getServiceCallConfigurations()); 425 builder.addPropertyValue("defaultHystrixConfiguration", factoryBean.getDefaultHystrixConfiguration()); 426 builder.addPropertyValue("hystrixConfigurations", factoryBean.getHystrixConfigurations()); 427 // add any depends-on 428 addDependsOn(factoryBean, builder); 429 } 430 431 NodeList list = element.getChildNodes(); 432 int size = list.getLength(); 433 for (int i = 0; i < size; i++) { 434 Node child = list.item(i); 435 if (child instanceof Element) { 436 Element childElement = (Element) child; 437 String localName = child.getLocalName(); 438 if (localName.equals("endpoint")) { 439 registerEndpoint(childElement, parserContext, contextId); 440 } else if (localName.equals("routeBuilder")) { 441 addDependsOnToRouteBuilder(childElement, parserContext, contextId); 442 } else { 443 BeanDefinitionParser parser = parserMap.get(localName); 444 if (parser != null) { 445 BeanDefinition definition = parser.parse(childElement, parserContext); 446 String id = childElement.getAttribute("id"); 447 if (ObjectHelper.isNotEmpty(id)) { 448 parserContext.registerComponent(new BeanComponentDefinition(definition, id)); 449 // set the templates with the camel context 450 if (localName.equals("template") || localName.equals("fluentTemplate") 451 || localName.equals("consumerTemplate") 452 || localName.equals("proxy") || localName.equals("export")) { 453 // set the camel context 454 definition.getPropertyValues().addPropertyValue("camelContext", 455 new RuntimeBeanReference(contextId)); 456 } 457 } 458 } 459 } 460 } 461 } 462 463 // register templates if not already defined 464 registerTemplates(element, parserContext, contextId); 465 466 // lets inject the namespaces into any namespace aware POJOs 467 injectNamespaces(element, binder); 468 469 // inject bean post processor so we can support @Produce etc. 470 // no bean processor element so lets create it by our self 471 injectBeanPostProcessor(element, parserContext, contextId, builder); 472 } 473 } 474 475 protected void addDependsOn(CamelContextFactoryBean factoryBean, BeanDefinitionBuilder builder) { 476 String dependsOn = factoryBean.getDependsOn(); 477 if (ObjectHelper.isNotEmpty(dependsOn)) { 478 // comma, whitespace and semi colon is valid separators in Spring depends-on 479 String[] depends = dependsOn.split(",|;|\\s"); 480 if (depends == null) { 481 throw new IllegalArgumentException("Cannot separate depends-on, was: " + dependsOn); 482 } else { 483 for (String depend : depends) { 484 depend = depend.trim(); 485 LOG.debug("Adding dependsOn {} to CamelContext({})", depend, factoryBean.getId()); 486 builder.addDependsOn(depend); 487 } 488 } 489 } 490 } 491 492 private void addDependsOnToRouteBuilder(Element childElement, ParserContext parserContext, String contextId) { 493 // setting the depends-on explicitly is required since Spring 3.0 494 String routeBuilderName = childElement.getAttribute("ref"); 495 if (ObjectHelper.isNotEmpty(routeBuilderName)) { 496 // set depends-on to the context for a routeBuilder bean 497 try { 498 BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(routeBuilderName); 499 Method getDependsOn = definition.getClass().getMethod("getDependsOn", new Class[] {}); 500 String[] dependsOn = (String[]) getDependsOn.invoke(definition); 501 if (dependsOn == null || dependsOn.length == 0) { 502 dependsOn = new String[] { contextId }; 503 } else { 504 String[] temp = new String[dependsOn.length + 1]; 505 System.arraycopy(dependsOn, 0, temp, 0, dependsOn.length); 506 temp[dependsOn.length] = contextId; 507 dependsOn = temp; 508 } 509 Method method = definition.getClass().getMethod("setDependsOn", String[].class); 510 method.invoke(definition, (Object) dependsOn); 511 } catch (Exception e) { 512 // Do nothing here 513 } 514 } 515 } 516 517 protected void injectNamespaces(Element element, Binder<Node> binder) { 518 NodeList list = element.getChildNodes(); 519 Namespaces namespaces = null; 520 int size = list.getLength(); 521 for (int i = 0; i < size; i++) { 522 Node child = list.item(i); 523 if (child instanceof Element) { 524 Element childElement = (Element) child; 525 Object object = binder.getJAXBNode(child); 526 if (object instanceof NamespaceAware) { 527 NamespaceAware namespaceAware = (NamespaceAware) object; 528 if (namespaces == null) { 529 namespaces = NamespacesHelper.namespaces(element); 530 } 531 namespaces.configure(namespaceAware); 532 } 533 injectNamespaces(childElement, binder); 534 } 535 } 536 } 537 538 protected void injectBeanPostProcessor( 539 Element element, ParserContext parserContext, String contextId, BeanDefinitionBuilder builder) { 540 Element childElement = element.getOwnerDocument().createElement("beanPostProcessor"); 541 element.appendChild(childElement); 542 543 String beanPostProcessorId = contextId + ":beanPostProcessor"; 544 childElement.setAttribute("id", beanPostProcessorId); 545 BeanDefinition definition = beanPostProcessorParser.parse(childElement, parserContext); 546 // only register to camel context id as a String. Then we can look it up later 547 // otherwise we get a circular reference in spring and it will not allow custom bean post processing 548 // see more at CAMEL-1663 549 definition.getPropertyValues().addPropertyValue("camelId", contextId); 550 builder.addPropertyReference("beanPostProcessor", beanPostProcessorId); 551 } 552 553 /** 554 * Used for auto registering producer, fluent producer and consumer templates if not already defined in XML. 555 */ 556 protected void registerTemplates(Element element, ParserContext parserContext, String contextId) { 557 boolean template = false; 558 boolean fluentTemplate = false; 559 boolean consumerTemplate = false; 560 561 NodeList list = element.getChildNodes(); 562 int size = list.getLength(); 563 for (int i = 0; i < size; i++) { 564 Node child = list.item(i); 565 if (child instanceof Element) { 566 Element childElement = (Element) child; 567 String localName = childElement.getLocalName(); 568 if ("template".equals(localName)) { 569 template = true; 570 } else if ("fluentTemplate".equals(localName)) { 571 fluentTemplate = true; 572 } else if ("consumerTemplate".equals(localName)) { 573 consumerTemplate = true; 574 } 575 } 576 } 577 578 if (!template) { 579 // either we have not used template before or we have auto registered it already and therefore we 580 // need it to allow to do it so it can remove the existing auto registered as there is now a clash id 581 // since we have multiple camel contexts 582 boolean existing = autoRegisterMap.get("template") != null; 583 boolean inUse = false; 584 try { 585 inUse = parserContext.getRegistry().isBeanNameInUse("template"); 586 } catch (BeanCreationException e) { 587 // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse 588 // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739) 589 LOG.debug("Error checking isBeanNameInUse(template). This exception will be ignored", e); 590 } 591 if (!inUse || existing) { 592 String id = "template"; 593 // auto create a template 594 Element templateElement = element.getOwnerDocument().createElement("template"); 595 templateElement.setAttribute("id", id); 596 BeanDefinitionParser parser = parserMap.get("template"); 597 BeanDefinition definition = parser.parse(templateElement, parserContext); 598 599 // auto register it 600 autoRegisterBeanDefinition(id, definition, parserContext, contextId); 601 } 602 } 603 604 if (!fluentTemplate) { 605 // either we have not used fluentTemplate before or we have auto registered it already and therefore we 606 // need it to allow to do it so it can remove the existing auto registered as there is now a clash id 607 // since we have multiple camel contexts 608 boolean existing = autoRegisterMap.get("fluentTemplate") != null; 609 boolean inUse = false; 610 try { 611 inUse = parserContext.getRegistry().isBeanNameInUse("fluentTemplate"); 612 } catch (BeanCreationException e) { 613 // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse 614 // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739) 615 LOG.debug("Error checking isBeanNameInUse(fluentTemplate). This exception will be ignored", e); 616 } 617 if (!inUse || existing) { 618 String id = "fluentTemplate"; 619 // auto create a fluentTemplate 620 Element templateElement = element.getOwnerDocument().createElement("fluentTemplate"); 621 templateElement.setAttribute("id", id); 622 BeanDefinitionParser parser = parserMap.get("fluentTemplate"); 623 BeanDefinition definition = parser.parse(templateElement, parserContext); 624 625 // auto register it 626 autoRegisterBeanDefinition(id, definition, parserContext, contextId); 627 } 628 } 629 630 if (!consumerTemplate) { 631 // either we have not used template before or we have auto registered it already and therefore we 632 // need it to allow to do it so it can remove the existing auto registered as there is now a clash id 633 // since we have multiple camel contexts 634 boolean existing = autoRegisterMap.get("consumerTemplate") != null; 635 boolean inUse = false; 636 try { 637 inUse = parserContext.getRegistry().isBeanNameInUse("consumerTemplate"); 638 } catch (BeanCreationException e) { 639 // Spring Eclipse Tooling may throw an exception when you edit the Spring XML online in Eclipse 640 // when the isBeanNameInUse method is invoked, so ignore this and continue (CAMEL-2739) 641 LOG.debug("Error checking isBeanNameInUse(consumerTemplate). This exception will be ignored", e); 642 } 643 if (!inUse || existing) { 644 String id = "consumerTemplate"; 645 // auto create a template 646 Element templateElement = element.getOwnerDocument().createElement("consumerTemplate"); 647 templateElement.setAttribute("id", id); 648 BeanDefinitionParser parser = parserMap.get("consumerTemplate"); 649 BeanDefinition definition = parser.parse(templateElement, parserContext); 650 651 // auto register it 652 autoRegisterBeanDefinition(id, definition, parserContext, contextId); 653 } 654 } 655 656 } 657 658 private void autoRegisterBeanDefinition( 659 String id, BeanDefinition definition, ParserContext parserContext, String contextId) { 660 // it is a bit cumbersome to work with the spring bean definition parser 661 // as we kinda need to eagerly register the bean definition on the parser context 662 // and then later we might find out that we should not have done that in case we have multiple camel contexts 663 // that would have a id clash by auto registering the same bean definition with the same id such as a producer template 664 665 // see if we have already auto registered this id 666 BeanDefinition existing = autoRegisterMap.get(id); 667 if (existing == null) { 668 // no then add it to the map and register it 669 autoRegisterMap.put(id, definition); 670 parserContext.registerComponent(new BeanComponentDefinition(definition, id)); 671 if (LOG.isDebugEnabled()) { 672 LOG.debug("Registered default: {} with id: {} on camel context: {}", definition.getBeanClassName(), id, 673 contextId); 674 } 675 } else { 676 // ups we have already registered it before with same id, but on another camel context 677 // this is not good so we need to remove all traces of this auto registering. 678 // end user must manually add the needed XML elements and provide unique ids access all camel context himself. 679 LOG.debug("Unregistered default: {} with id: {} as we have multiple camel contexts and they must use unique ids." 680 + " You must define the definition in the XML file manually to avoid id clashes when using multiple camel contexts", 681 definition.getBeanClassName(), id); 682 683 parserContext.getRegistry().removeBeanDefinition(id); 684 } 685 } 686 687 private void registerEndpoint(Element childElement, ParserContext parserContext, String contextId) { 688 String id = childElement.getAttribute("id"); 689 // must have an id to be registered 690 if (ObjectHelper.isNotEmpty(id)) { 691 // skip underscore as they are internal naming and should not be registered 692 if (id.startsWith("_")) { 693 LOG.debug("Skip registering endpoint starting with underscore: {}", id); 694 return; 695 } 696 BeanDefinition definition = endpointParser.parse(childElement, parserContext); 697 definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId)); 698 // Need to add this dependency of CamelContext for Spring 3.0 699 try { 700 Method method = definition.getClass().getMethod("setDependsOn", String[].class); 701 method.invoke(definition, (Object) new String[] { contextId }); 702 } catch (Exception e) { 703 // Do nothing here 704 } 705 parserContext.registerBeanComponent(new BeanComponentDefinition(definition, id)); 706 } 707 } 708 709}