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