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.blueprint.handler; 018 019import java.io.UnsupportedEncodingException; 020import java.lang.reflect.Field; 021import java.lang.reflect.Method; 022import java.lang.reflect.Modifier; 023import java.net.URI; 024import java.net.URISyntaxException; 025import java.net.URL; 026import java.util.Arrays; 027import java.util.HashSet; 028import java.util.List; 029import java.util.Map; 030import java.util.Set; 031import java.util.concurrent.Callable; 032 033import javax.xml.bind.Binder; 034import javax.xml.bind.JAXBContext; 035import javax.xml.bind.JAXBException; 036 037import org.w3c.dom.Document; 038import org.w3c.dom.Element; 039import org.w3c.dom.NamedNodeMap; 040import org.w3c.dom.Node; 041import org.w3c.dom.NodeList; 042 043import org.apache.aries.blueprint.BeanProcessor; 044import org.apache.aries.blueprint.ComponentDefinitionRegistry; 045import org.apache.aries.blueprint.ComponentDefinitionRegistryProcessor; 046import org.apache.aries.blueprint.NamespaceHandler; 047import org.apache.aries.blueprint.ParserContext; 048import org.apache.aries.blueprint.PassThroughMetadata; 049import org.apache.aries.blueprint.mutable.MutableBeanMetadata; 050import org.apache.aries.blueprint.mutable.MutablePassThroughMetadata; 051import org.apache.aries.blueprint.mutable.MutableRefMetadata; 052import org.apache.aries.blueprint.mutable.MutableReferenceMetadata; 053import org.apache.camel.BeanInject; 054import org.apache.camel.CamelContext; 055import org.apache.camel.Endpoint; 056import org.apache.camel.EndpointInject; 057import org.apache.camel.Produce; 058import org.apache.camel.PropertyInject; 059import org.apache.camel.blueprint.BlueprintCamelContext; 060import org.apache.camel.blueprint.BlueprintCamelStateService; 061import org.apache.camel.blueprint.BlueprintModelJAXBContextFactory; 062import org.apache.camel.blueprint.CamelContextFactoryBean; 063import org.apache.camel.blueprint.CamelEndpointFactoryBean; 064import org.apache.camel.blueprint.CamelRestContextFactoryBean; 065import org.apache.camel.blueprint.CamelRouteContextFactoryBean; 066import org.apache.camel.core.xml.AbstractCamelFactoryBean; 067import org.apache.camel.impl.engine.CamelPostProcessorHelper; 068import org.apache.camel.impl.engine.DefaultCamelContextNameStrategy; 069import org.apache.camel.model.AggregateDefinition; 070import org.apache.camel.model.CatchDefinition; 071import org.apache.camel.model.DataFormatDefinition; 072import org.apache.camel.model.ExpressionNode; 073import org.apache.camel.model.ExpressionSubElementDefinition; 074import org.apache.camel.model.FromDefinition; 075import org.apache.camel.model.MarshalDefinition; 076import org.apache.camel.model.Model; 077import org.apache.camel.model.OnExceptionDefinition; 078import org.apache.camel.model.ProcessorDefinition; 079import org.apache.camel.model.ResequenceDefinition; 080import org.apache.camel.model.RouteDefinition; 081import org.apache.camel.model.SendDefinition; 082import org.apache.camel.model.SortDefinition; 083import org.apache.camel.model.ToDefinition; 084import org.apache.camel.model.ToDynamicDefinition; 085import org.apache.camel.model.UnmarshalDefinition; 086import org.apache.camel.model.WireTapDefinition; 087import org.apache.camel.model.language.ExpressionDefinition; 088import org.apache.camel.model.rest.RestBindingMode; 089import org.apache.camel.model.rest.RestDefinition; 090import org.apache.camel.model.rest.VerbDefinition; 091import org.apache.camel.spi.CamelContextNameStrategy; 092import org.apache.camel.spi.ComponentResolver; 093import org.apache.camel.spi.DataFormatResolver; 094import org.apache.camel.spi.LanguageResolver; 095import org.apache.camel.spi.NamespaceAware; 096import org.apache.camel.spi.PropertiesComponent; 097import org.apache.camel.support.ObjectHelper; 098import org.apache.camel.support.builder.Namespaces; 099import org.apache.camel.support.builder.xml.NamespacesHelper; 100import org.apache.camel.support.jsse.KeyStoreParameters; 101import org.apache.camel.support.jsse.SSLContextParameters; 102import org.apache.camel.support.jsse.SecureRandomParameters; 103import org.apache.camel.util.StringHelper; 104import org.apache.camel.util.URISupport; 105import org.apache.camel.util.blueprint.KeyStoreParametersFactoryBean; 106import org.apache.camel.util.blueprint.SSLContextParametersFactoryBean; 107import org.apache.camel.util.blueprint.SecureRandomParametersFactoryBean; 108import org.osgi.framework.Bundle; 109import org.osgi.service.blueprint.container.BlueprintContainer; 110import org.osgi.service.blueprint.container.ComponentDefinitionException; 111import org.osgi.service.blueprint.reflect.BeanMetadata; 112import org.osgi.service.blueprint.reflect.ComponentMetadata; 113import org.osgi.service.blueprint.reflect.Metadata; 114import org.osgi.service.blueprint.reflect.RefMetadata; 115import org.slf4j.Logger; 116import org.slf4j.LoggerFactory; 117 118import static org.osgi.service.blueprint.reflect.ComponentMetadata.ACTIVATION_LAZY; 119import static org.osgi.service.blueprint.reflect.ServiceReferenceMetadata.AVAILABILITY_MANDATORY; 120import static org.osgi.service.blueprint.reflect.ServiceReferenceMetadata.AVAILABILITY_OPTIONAL; 121 122/** 123 * Camel {@link NamespaceHandler} to parse the Camel related namespaces. 124 */ 125public class CamelNamespaceHandler implements NamespaceHandler { 126 127 public static final String BLUEPRINT_NS = "http://camel.apache.org/schema/blueprint"; 128 public static final String SPRING_NS = "http://camel.apache.org/schema/spring"; 129 130 private static final String CAMEL_CONTEXT = "camelContext"; 131 private static final String ROUTE_CONTEXT = "routeContext"; 132 private static final String REST_CONTEXT = "restContext"; 133 private static final String ENDPOINT = "endpoint"; 134 private static final String KEY_STORE_PARAMETERS = "keyStoreParameters"; 135 private static final String SECURE_RANDOM_PARAMETERS = "secureRandomParameters"; 136 private static final String SSL_CONTEXT_PARAMETERS = "sslContextParameters"; 137 138 private static final Logger LOG = LoggerFactory.getLogger(CamelNamespaceHandler.class); 139 140 private JAXBContext jaxbContext; 141 142 /** 143 * Prepares the nodes before parsing. 144 */ 145 public static void doBeforeParse(Node node, String fromNamespace, String toNamespace) { 146 if (node.getNodeType() == Node.ELEMENT_NODE) { 147 Document doc = node.getOwnerDocument(); 148 if (node.getNamespaceURI().equals(fromNamespace)) { 149 doc.renameNode(node, toNamespace, node.getLocalName()); 150 } 151 152 // remove whitespace noise from uri, xxxUri attributes, eg new lines, and tabs etc, which allows end users to format 153 // their Camel routes in more human readable format, but at runtime those attributes must be trimmed 154 // the parser removes most of the noise, but keeps double spaces in the attribute values 155 NamedNodeMap map = node.getAttributes(); 156 for (int i = 0; i < map.getLength(); i++) { 157 Node att = map.item(i); 158 if (att.getNodeName().equals("uri") || att.getNodeName().endsWith("Uri")) { 159 final String value = att.getNodeValue(); 160 String before = StringHelper.before(value, "?"); 161 String after = StringHelper.after(value, "?"); 162 163 if (before != null && after != null) { 164 // remove all double spaces in the uri parameters 165 String changed = after.replaceAll("\\s{2,}", ""); 166 if (!after.equals(changed)) { 167 String newAtr = before.trim() + "?" + changed.trim(); 168 LOG.debug("Removed whitespace noise from attribute {} -> {}", value, newAtr); 169 att.setNodeValue(newAtr); 170 } 171 } 172 } 173 } 174 } 175 NodeList list = node.getChildNodes(); 176 for (int i = 0; i < list.getLength(); ++i) { 177 doBeforeParse(list.item(i), fromNamespace, toNamespace); 178 } 179 } 180 181 @Override 182 public URL getSchemaLocation(String namespace) { 183 if (BLUEPRINT_NS.equals(namespace)) { 184 return getClass().getClassLoader().getResource("camel-blueprint.xsd"); 185 } 186 return null; 187 } 188 189 @Override 190 @SuppressWarnings({"rawtypes"}) 191 public Set<Class> getManagedClasses() { 192 return new HashSet<>(Arrays.asList(BlueprintCamelContext.class)); 193 } 194 195 @Override 196 public Metadata parse(Element element, ParserContext context) { 197 LOG.trace("Parsing element {}", element); 198 199 try { 200 // as the camel-core model namespace is Spring we need to rename from blueprint to spring 201 doBeforeParse(element, BLUEPRINT_NS, SPRING_NS); 202 203 if (element.getLocalName().equals(CAMEL_CONTEXT)) { 204 return parseCamelContextNode(element, context); 205 } 206 if (element.getLocalName().equals(ROUTE_CONTEXT)) { 207 return parseRouteContextNode(element, context); 208 } 209 if (element.getLocalName().equals(REST_CONTEXT)) { 210 return parseRestContextNode(element, context); 211 } 212 if (element.getLocalName().equals(ENDPOINT)) { 213 return parseEndpointNode(element, context); 214 } 215 if (element.getLocalName().equals(KEY_STORE_PARAMETERS)) { 216 return parseKeyStoreParametersNode(element, context); 217 } 218 if (element.getLocalName().equals(SECURE_RANDOM_PARAMETERS)) { 219 return parseSecureRandomParametersNode(element, context); 220 } 221 if (element.getLocalName().equals(SSL_CONTEXT_PARAMETERS)) { 222 return parseSSLContextParametersNode(element, context); 223 } 224 } finally { 225 // make sure to rename back so we leave the DOM as-is 226 doBeforeParse(element, SPRING_NS, BLUEPRINT_NS); 227 } 228 229 return null; 230 } 231 232 private Metadata parseCamelContextNode(Element element, ParserContext context) { 233 LOG.trace("Parsing CamelContext {}", element); 234 // Find the id, generate one if needed 235 String contextId = element.getAttribute("id"); 236 boolean implicitId = false; 237 238 // let's avoid folks having to explicitly give an ID to a camel context 239 if (org.apache.camel.util.ObjectHelper.isEmpty(contextId)) { 240 // if no explicit id was set then use a default auto generated name 241 CamelContextNameStrategy strategy = new DefaultCamelContextNameStrategy(); 242 contextId = strategy.getName(); 243 element.setAttributeNS(null, "id", contextId); 244 implicitId = true; 245 } 246 247 // now let's parse the routes with JAXB 248 Binder<Node> binder; 249 try { 250 binder = getJaxbContext().createBinder(); 251 } catch (JAXBException e) { 252 throw new ComponentDefinitionException("Failed to create the JAXB binder : " + e, e); 253 } 254 Object value = parseUsingJaxb(element, context, binder); 255 if (!(value instanceof CamelContextFactoryBean)) { 256 throw new ComponentDefinitionException("Expected an instance of " + CamelContextFactoryBean.class); 257 } 258 259 CamelContextFactoryBean ccfb = (CamelContextFactoryBean) value; 260 ccfb.setImplicitId(implicitId); 261 262 MutablePassThroughMetadata factory = context.createMetadata(MutablePassThroughMetadata.class); 263 factory.setId(".camelBlueprint.passThrough." + contextId); 264 factory.setObject(new PassThroughCallable<>(value)); 265 266 MutableBeanMetadata factory2 = context.createMetadata(MutableBeanMetadata.class); 267 factory2.setId(".camelBlueprint.factory." + contextId); 268 factory2.setFactoryComponent(factory); 269 factory2.setFactoryMethod("call"); 270 factory2.setInitMethod("afterPropertiesSet"); 271 factory2.setDestroyMethod("destroy"); 272 factory2.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); 273 factory2.addProperty("bundleContext", createRef(context, "blueprintBundleContext")); 274 // We need to add other components which the camel context dependsOn 275 if (org.apache.camel.util.ObjectHelper.isNotEmpty(ccfb.getDependsOn())) { 276 factory2.setDependsOn(Arrays.asList(ccfb.getDependsOn().split(" |,"))); 277 } 278 context.getComponentDefinitionRegistry().registerComponentDefinition(factory2); 279 280 MutableBeanMetadata ctx = context.createMetadata(MutableBeanMetadata.class); 281 ctx.setId(contextId); 282 ctx.setRuntimeClass(BlueprintCamelContext.class); 283 ctx.setFactoryComponent(factory2); 284 ctx.setFactoryMethod("getContext"); 285 ctx.addProperty("bundleStateService", createRef(context, ".camelBlueprint.bundleStateService")); 286 ctx.setInitMethod("init"); 287 ctx.setDestroyMethod("destroy"); 288 289 // Register factory beans 290 registerBeans(context, contextId, ccfb.getThreadPools()); 291 registerBeans(context, contextId, ccfb.getEndpoints()); 292 registerBeans(context, contextId, ccfb.getRedeliveryPolicies()); 293 registerBeans(context, contextId, ccfb.getBeansFactory()); 294 295 // Register single CamelBundleStateService - shared for all bundles and all Blueprint Camel contexts 296 registerBundleStateService(context); 297 298 // Register processors 299 MutablePassThroughMetadata beanProcessorFactory = context.createMetadata(MutablePassThroughMetadata.class); 300 beanProcessorFactory.setId(".camelBlueprint.processor.bean.passThrough." + contextId); 301 beanProcessorFactory.setObject(new PassThroughCallable<Object>(new CamelInjector(contextId))); 302 303 MutableBeanMetadata beanProcessor = context.createMetadata(MutableBeanMetadata.class); 304 beanProcessor.setId(".camelBlueprint.processor.bean." + contextId); 305 beanProcessor.setRuntimeClass(CamelInjector.class); 306 beanProcessor.setFactoryComponent(beanProcessorFactory); 307 beanProcessor.setFactoryMethod("call"); 308 beanProcessor.setProcessor(true); 309 beanProcessor.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); 310 context.getComponentDefinitionRegistry().registerComponentDefinition(beanProcessor); 311 312 MutablePassThroughMetadata regProcessorFactory = context.createMetadata(MutablePassThroughMetadata.class); 313 regProcessorFactory.setId(".camelBlueprint.processor.registry.passThrough." + contextId); 314 regProcessorFactory.setObject(new PassThroughCallable<Object>(new CamelDependenciesFinder(contextId, context))); 315 316 MutableBeanMetadata regProcessor = context.createMetadata(MutableBeanMetadata.class); 317 regProcessor.setId(".camelBlueprint.processor.registry." + contextId); 318 regProcessor.setRuntimeClass(CamelDependenciesFinder.class); 319 regProcessor.setFactoryComponent(regProcessorFactory); 320 regProcessor.setFactoryMethod("call"); 321 regProcessor.setProcessor(true); 322 regProcessor.addDependsOn(".camelBlueprint.processor.bean." + contextId); 323 regProcessor.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); 324 context.getComponentDefinitionRegistry().registerComponentDefinition(regProcessor); 325 326 // lets inject the namespaces into any namespace aware POJOs 327 injectNamespaces(element, binder); 328 329 LOG.trace("Parsing CamelContext done, returning {}", ctx); 330 return ctx; 331 } 332 333 protected void injectNamespaces(Element element, Binder<Node> binder) { 334 NodeList list = element.getChildNodes(); 335 Namespaces namespaces = null; 336 int size = list.getLength(); 337 for (int i = 0; i < size; i++) { 338 Node child = list.item(i); 339 if (child instanceof Element) { 340 Element childElement = (Element) child; 341 Object object = binder.getJAXBNode(child); 342 if (object instanceof NamespaceAware) { 343 NamespaceAware namespaceAware = (NamespaceAware) object; 344 if (namespaces == null) { 345 namespaces = NamespacesHelper.namespaces(element); 346 } 347 namespaces.configure(namespaceAware); 348 } 349 injectNamespaces(childElement, binder); 350 } 351 } 352 } 353 354 private Metadata parseRouteContextNode(Element element, ParserContext context) { 355 LOG.trace("Parsing RouteContext {}", element); 356 // now parse the routes with JAXB 357 Binder<Node> binder; 358 try { 359 binder = getJaxbContext().createBinder(); 360 } catch (JAXBException e) { 361 362 throw new ComponentDefinitionException("Failed to create the JAXB binder : " + e, e); 363 } 364 Object value = parseUsingJaxb(element, context, binder); 365 if (!(value instanceof CamelRouteContextFactoryBean)) { 366 throw new ComponentDefinitionException("Expected an instance of " + CamelRouteContextFactoryBean.class); 367 } 368 369 CamelRouteContextFactoryBean rcfb = (CamelRouteContextFactoryBean) value; 370 String id = rcfb.getId(); 371 372 MutablePassThroughMetadata factory = context.createMetadata(MutablePassThroughMetadata.class); 373 factory.setId(".camelBlueprint.passThrough." + id); 374 factory.setObject(new PassThroughCallable<Object>(rcfb)); 375 376 MutableBeanMetadata factory2 = context.createMetadata(MutableBeanMetadata.class); 377 factory2.setId(".camelBlueprint.factory." + id); 378 factory2.setFactoryComponent(factory); 379 factory2.setFactoryMethod("call"); 380 381 MutableBeanMetadata ctx = context.createMetadata(MutableBeanMetadata.class); 382 ctx.setId(id); 383 ctx.setRuntimeClass(List.class); 384 ctx.setFactoryComponent(factory2); 385 ctx.setFactoryMethod("getRoutes"); 386 // must be lazy as we want CamelContext to be activated first 387 ctx.setActivation(ACTIVATION_LAZY); 388 389 // lets inject the namespaces into any namespace aware POJOs 390 injectNamespaces(element, binder); 391 392 LOG.trace("Parsing RouteContext {} done, returning {}", element, ctx); 393 return ctx; 394 } 395 396 private Metadata parseRestContextNode(Element element, ParserContext context) { 397 LOG.trace("Parsing RestContext {}", element); 398 // now parse the rests with JAXB 399 Binder<Node> binder; 400 try { 401 binder = getJaxbContext().createBinder(); 402 } catch (JAXBException e) { 403 throw new ComponentDefinitionException("Failed to create the JAXB binder : " + e, e); 404 } 405 Object value = parseUsingJaxb(element, context, binder); 406 if (!(value instanceof CamelRestContextFactoryBean)) { 407 throw new ComponentDefinitionException("Expected an instance of " + CamelRestContextFactoryBean.class); 408 } 409 410 CamelRestContextFactoryBean rcfb = (CamelRestContextFactoryBean) value; 411 String id = rcfb.getId(); 412 413 MutablePassThroughMetadata factory = context.createMetadata(MutablePassThroughMetadata.class); 414 factory.setId(".camelBlueprint.passThrough." + id); 415 factory.setObject(new PassThroughCallable<Object>(rcfb)); 416 417 MutableBeanMetadata factory2 = context.createMetadata(MutableBeanMetadata.class); 418 factory2.setId(".camelBlueprint.factory." + id); 419 factory2.setFactoryComponent(factory); 420 factory2.setFactoryMethod("call"); 421 422 MutableBeanMetadata ctx = context.createMetadata(MutableBeanMetadata.class); 423 ctx.setId(id); 424 ctx.setRuntimeClass(List.class); 425 ctx.setFactoryComponent(factory2); 426 ctx.setFactoryMethod("getRests"); 427 // must be lazy as we want CamelContext to be activated first 428 ctx.setActivation(ACTIVATION_LAZY); 429 430 // lets inject the namespaces into any namespace aware POJOs 431 injectNamespaces(element, binder); 432 433 LOG.trace("Parsing RestContext {} done, returning {}", element, ctx); 434 return ctx; 435 } 436 437 private Metadata parseEndpointNode(Element element, ParserContext context) { 438 LOG.trace("Parsing Endpoint {}", element); 439 // now parse the rests with JAXB 440 Binder<Node> binder; 441 try { 442 binder = getJaxbContext().createBinder(); 443 } catch (JAXBException e) { 444 throw new ComponentDefinitionException("Failed to create the JAXB binder : " + e, e); 445 } 446 Object value = parseUsingJaxb(element, context, binder); 447 if (!(value instanceof CamelEndpointFactoryBean)) { 448 throw new ComponentDefinitionException("Expected an instance of " + CamelEndpointFactoryBean.class); 449 } 450 451 CamelEndpointFactoryBean rcfb = (CamelEndpointFactoryBean) value; 452 String id = rcfb.getId(); 453 454 MutablePassThroughMetadata factory = context.createMetadata(MutablePassThroughMetadata.class); 455 factory.setId(".camelBlueprint.passThrough." + id); 456 factory.setObject(new PassThroughCallable<Object>(rcfb)); 457 458 MutableBeanMetadata factory2 = context.createMetadata(MutableBeanMetadata.class); 459 factory2.setId(".camelBlueprint.factory." + id); 460 factory2.setFactoryComponent(factory); 461 factory2.setFactoryMethod("call"); 462 factory2.setInitMethod("afterPropertiesSet"); 463 factory2.setDestroyMethod("destroy"); 464 factory2.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); 465 466 MutableBeanMetadata ctx = context.createMetadata(MutableBeanMetadata.class); 467 ctx.setId(id); 468 ctx.setRuntimeClass(Endpoint.class); 469 ctx.setFactoryComponent(factory2); 470 ctx.setFactoryMethod("getObject"); 471 // must be lazy as we want CamelContext to be activated first 472 ctx.setActivation(ACTIVATION_LAZY); 473 474 LOG.trace("Parsing endpoint {} done, returning {}", element, ctx); 475 return ctx; 476 } 477 478 private Metadata parseKeyStoreParametersNode(Element element, ParserContext context) { 479 LOG.trace("Parsing KeyStoreParameters {}", element); 480 // now parse the key store parameters with JAXB 481 Binder<Node> binder; 482 try { 483 binder = getJaxbContext().createBinder(); 484 } catch (JAXBException e) { 485 throw new ComponentDefinitionException("Failed to create the JAXB binder : " + e, e); 486 } 487 Object value = parseUsingJaxb(element, context, binder); 488 if (!(value instanceof KeyStoreParametersFactoryBean)) { 489 throw new ComponentDefinitionException("Expected an instance of " + KeyStoreParametersFactoryBean.class); 490 } 491 492 KeyStoreParametersFactoryBean kspfb = (KeyStoreParametersFactoryBean) value; 493 String id = kspfb.getId(); 494 495 MutablePassThroughMetadata factory = context.createMetadata(MutablePassThroughMetadata.class); 496 factory.setId(".camelBlueprint.passThrough." + id); 497 factory.setObject(new PassThroughCallable<Object>(kspfb)); 498 499 MutableBeanMetadata factory2 = context.createMetadata(MutableBeanMetadata.class); 500 factory2.setId(".camelBlueprint.factory." + id); 501 factory2.setFactoryComponent(factory); 502 factory2.setFactoryMethod("call"); 503 factory2.setInitMethod("afterPropertiesSet"); 504 factory2.setDestroyMethod("destroy"); 505 factory2.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); 506 507 MutableBeanMetadata ctx = context.createMetadata(MutableBeanMetadata.class); 508 ctx.setId(id); 509 ctx.setRuntimeClass(KeyStoreParameters.class); 510 ctx.setFactoryComponent(factory2); 511 ctx.setFactoryMethod("getObject"); 512 // must be lazy as we want CamelContext to be activated first 513 ctx.setActivation(ACTIVATION_LAZY); 514 515 LOG.trace("Parsing KeyStoreParameters done, returning {}", ctx); 516 return ctx; 517 } 518 519 private Metadata parseSecureRandomParametersNode(Element element, ParserContext context) { 520 LOG.trace("Parsing SecureRandomParameters {}", element); 521 // now parse the key store parameters with JAXB 522 Binder<Node> binder; 523 try { 524 binder = getJaxbContext().createBinder(); 525 } catch (JAXBException e) { 526 throw new ComponentDefinitionException("Failed to create the JAXB binder : " + e, e); 527 } 528 Object value = parseUsingJaxb(element, context, binder); 529 if (!(value instanceof SecureRandomParametersFactoryBean)) { 530 throw new ComponentDefinitionException("Expected an instance of " + SecureRandomParametersFactoryBean.class); 531 } 532 533 SecureRandomParametersFactoryBean srfb = (SecureRandomParametersFactoryBean) value; 534 String id = srfb.getId(); 535 536 MutablePassThroughMetadata factory = context.createMetadata(MutablePassThroughMetadata.class); 537 factory.setId(".camelBlueprint.passThrough." + id); 538 factory.setObject(new PassThroughCallable<Object>(srfb)); 539 540 MutableBeanMetadata factory2 = context.createMetadata(MutableBeanMetadata.class); 541 factory2.setId(".camelBlueprint.factory." + id); 542 factory2.setFactoryComponent(factory); 543 factory2.setFactoryMethod("call"); 544 factory2.setInitMethod("afterPropertiesSet"); 545 factory2.setDestroyMethod("destroy"); 546 factory2.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); 547 548 MutableBeanMetadata ctx = context.createMetadata(MutableBeanMetadata.class); 549 ctx.setId(id); 550 ctx.setRuntimeClass(SecureRandomParameters.class); 551 ctx.setFactoryComponent(factory2); 552 ctx.setFactoryMethod("getObject"); 553 // must be lazy as we want CamelContext to be activated first 554 ctx.setActivation(ACTIVATION_LAZY); 555 556 LOG.trace("Parsing SecureRandomParameters done, returning {}", ctx); 557 return ctx; 558 } 559 560 private Metadata parseSSLContextParametersNode(Element element, ParserContext context) { 561 LOG.trace("Parsing SSLContextParameters {}", element); 562 // now parse the key store parameters with JAXB 563 Binder<Node> binder; 564 try { 565 binder = getJaxbContext().createBinder(); 566 } catch (JAXBException e) { 567 throw new ComponentDefinitionException("Failed to create the JAXB binder : " + e, e); 568 } 569 Object value = parseUsingJaxb(element, context, binder); 570 if (!(value instanceof SSLContextParametersFactoryBean)) { 571 throw new ComponentDefinitionException("Expected an instance of " + SSLContextParametersFactoryBean.class); 572 } 573 574 SSLContextParametersFactoryBean scpfb = (SSLContextParametersFactoryBean) value; 575 String id = scpfb.getId(); 576 577 MutablePassThroughMetadata factory = context.createMetadata(MutablePassThroughMetadata.class); 578 factory.setId(".camelBlueprint.passThrough." + id); 579 factory.setObject(new PassThroughCallable<Object>(scpfb)); 580 581 MutableBeanMetadata factory2 = context.createMetadata(MutableBeanMetadata.class); 582 factory2.setId(".camelBlueprint.factory." + id); 583 factory2.setFactoryComponent(factory); 584 factory2.setFactoryMethod("call"); 585 factory2.setInitMethod("afterPropertiesSet"); 586 factory2.setDestroyMethod("destroy"); 587 factory2.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); 588 589 MutableBeanMetadata ctx = context.createMetadata(MutableBeanMetadata.class); 590 ctx.setId(id); 591 ctx.setRuntimeClass(SSLContextParameters.class); 592 ctx.setFactoryComponent(factory2); 593 ctx.setFactoryMethod("getObject"); 594 // must be lazy as we want CamelContext to be activated first 595 ctx.setActivation(ACTIVATION_LAZY); 596 597 LOG.trace("Parsing SSLContextParameters done, returning {}", ctx); 598 return ctx; 599 } 600 601 private void registerBeans(ParserContext context, String contextId, List<?> beans) { 602 if (beans != null) { 603 for (Object bean : beans) { 604 if (bean instanceof AbstractCamelFactoryBean) { 605 registerBean(context, contextId, (AbstractCamelFactoryBean<?>) bean); 606 } 607 } 608 } 609 } 610 611 protected void registerBean(ParserContext context, String contextId, AbstractCamelFactoryBean<?> fact) { 612 String id = fact.getId(); 613 614 fact.setCamelContextId(contextId); 615 616 MutablePassThroughMetadata eff = context.createMetadata(MutablePassThroughMetadata.class); 617 eff.setId(".camelBlueprint.bean.passthrough." + id); 618 eff.setObject(new PassThroughCallable<Object>(fact)); 619 620 MutableBeanMetadata ef = context.createMetadata(MutableBeanMetadata.class); 621 ef.setId(".camelBlueprint.bean.factory." + id); 622 ef.setFactoryComponent(eff); 623 ef.setFactoryMethod("call"); 624 ef.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); 625 ef.setInitMethod("afterPropertiesSet"); 626 ef.setDestroyMethod("destroy"); 627 628 MutableBeanMetadata e = context.createMetadata(MutableBeanMetadata.class); 629 e.setId(id); 630 e.setRuntimeClass(fact.getObjectType()); 631 e.setFactoryComponent(ef); 632 e.setFactoryMethod("getObject"); 633 e.addDependsOn(".camelBlueprint.processor.bean." + contextId); 634 635 context.getComponentDefinitionRegistry().registerComponentDefinition(e); 636 } 637 638 /** 639 * There's single instance of {@link BlueprintCamelStateService} that's used by all Blueprint Camel contexts 640 * to inform about state of Camel contexts. If Karaf is available, this information will propagate to 641 * <em>extended bundle info</em>. 642 * See CAMEL-12980 643 */ 644 private void registerBundleStateService(ParserContext context) { 645 ComponentDefinitionRegistry componentDefinitionRegistry = context.getComponentDefinitionRegistry(); 646 ComponentMetadata cm = componentDefinitionRegistry.getComponentDefinition(".camelBlueprint.bundleStateService"); 647 if (cm == null) { 648 MutableBeanMetadata ssm = context.createMetadata(MutableBeanMetadata.class); 649 ssm.setId(".camelBlueprint.bundleStateService"); 650 ssm.setRuntimeClass(BlueprintCamelStateService.class); 651 ssm.addProperty("bundleContext", createRef(context, "blueprintBundleContext")); 652 ssm.setInitMethod("init"); 653 ssm.setDestroyMethod("destroy"); 654 componentDefinitionRegistry.registerComponentDefinition(ssm); 655 } 656 } 657 658 protected BlueprintContainer getBlueprintContainer(ParserContext context) { 659 PassThroughMetadata ptm = (PassThroughMetadata) context.getComponentDefinitionRegistry().getComponentDefinition("blueprintContainer"); 660 return (BlueprintContainer) ptm.getObject(); 661 } 662 663 @Override 664 public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) { 665 return null; 666 } 667 668 protected Object parseUsingJaxb(Element element, ParserContext parserContext, Binder<Node> binder) { 669 try { 670 return binder.unmarshal(element); 671 } catch (JAXBException e) { 672 throw new ComponentDefinitionException("Failed to parse JAXB element: " + e, e); 673 } 674 } 675 676 public JAXBContext getJaxbContext() throws JAXBException { 677 if (jaxbContext == null) { 678 jaxbContext = new BlueprintModelJAXBContextFactory(getClass().getClassLoader()).newJAXBContext(); 679 } 680 return jaxbContext; 681 } 682 683 private RefMetadata createRef(ParserContext context, String value) { 684 MutableRefMetadata r = context.createMetadata(MutableRefMetadata.class); 685 r.setComponentId(value); 686 return r; 687 } 688 689 private static ComponentMetadata getDataformatResolverReference(ParserContext context, String dataformat) { 690 // we cannot resolve dataformat names using property placeholders at this point in time 691 if (dataformat.startsWith(PropertiesComponent.PREFIX_TOKEN)) { 692 return null; 693 } 694 ComponentDefinitionRegistry componentDefinitionRegistry = context.getComponentDefinitionRegistry(); 695 ComponentMetadata cm = componentDefinitionRegistry.getComponentDefinition(".camelBlueprint.dataformatResolver." + dataformat); 696 if (cm == null) { 697 MutableReferenceMetadata svc = context.createMetadata(MutableReferenceMetadata.class); 698 svc.setId(".camelBlueprint.dataformatResolver." + dataformat); 699 svc.setFilter("(dataformat=" + dataformat + ")"); 700 svc.setAvailability(componentDefinitionRegistry.containsComponentDefinition(dataformat) ? AVAILABILITY_OPTIONAL : AVAILABILITY_MANDATORY); 701 try { 702 // Try to set the runtime interface (only with aries blueprint > 0.1 703 svc.getClass().getMethod("setRuntimeInterface", Class.class).invoke(svc, DataFormatResolver.class); 704 } catch (Throwable t) { 705 // Check if the bundle can see the class 706 try { 707 PassThroughMetadata ptm = (PassThroughMetadata) componentDefinitionRegistry.getComponentDefinition("blueprintBundle"); 708 Bundle b = (Bundle) ptm.getObject(); 709 if (b.loadClass(DataFormatResolver.class.getName()) != DataFormatResolver.class) { 710 throw new UnsupportedOperationException(); 711 } 712 svc.setInterface(DataFormatResolver.class.getName()); 713 } catch (Throwable t2) { 714 throw new UnsupportedOperationException(); 715 } 716 } 717 componentDefinitionRegistry.registerComponentDefinition(svc); 718 cm = svc; 719 } 720 return cm; 721 } 722 723 private static ComponentMetadata getLanguageResolverReference(ParserContext context, String language) { 724 // we cannot resolve language names using property placeholders at this point in time 725 if (language.startsWith(PropertiesComponent.PREFIX_TOKEN)) { 726 return null; 727 } 728 ComponentDefinitionRegistry componentDefinitionRegistry = context.getComponentDefinitionRegistry(); 729 ComponentMetadata cm = componentDefinitionRegistry.getComponentDefinition(".camelBlueprint.languageResolver." + language); 730 if (cm == null) { 731 MutableReferenceMetadata svc = context.createMetadata(MutableReferenceMetadata.class); 732 svc.setId(".camelBlueprint.languageResolver." + language); 733 svc.setFilter("(language=" + language + ")"); 734 svc.setAvailability(componentDefinitionRegistry.containsComponentDefinition(language) ? AVAILABILITY_OPTIONAL : AVAILABILITY_MANDATORY); 735 try { 736 // Try to set the runtime interface (only with aries blueprint > 0.1 737 svc.getClass().getMethod("setRuntimeInterface", Class.class).invoke(svc, LanguageResolver.class); 738 } catch (Throwable t) { 739 // Check if the bundle can see the class 740 try { 741 PassThroughMetadata ptm = (PassThroughMetadata) componentDefinitionRegistry.getComponentDefinition("blueprintBundle"); 742 Bundle b = (Bundle) ptm.getObject(); 743 if (b.loadClass(LanguageResolver.class.getName()) != LanguageResolver.class) { 744 throw new UnsupportedOperationException(); 745 } 746 svc.setInterface(LanguageResolver.class.getName()); 747 } catch (Throwable t2) { 748 throw new UnsupportedOperationException(); 749 } 750 } 751 componentDefinitionRegistry.registerComponentDefinition(svc); 752 cm = svc; 753 } 754 return cm; 755 } 756 757 private static ComponentMetadata getComponentResolverReference(ParserContext context, String component) { 758 // we cannot resolve component names using property placeholders at this point in time 759 if (component.startsWith(PropertiesComponent.PREFIX_TOKEN)) { 760 return null; 761 } 762 ComponentDefinitionRegistry componentDefinitionRegistry = context.getComponentDefinitionRegistry(); 763 ComponentMetadata cm = componentDefinitionRegistry.getComponentDefinition(".camelBlueprint.componentResolver." + component); 764 if (cm == null) { 765 MutableReferenceMetadata svc = context.createMetadata(MutableReferenceMetadata.class); 766 svc.setId(".camelBlueprint.componentResolver." + component); 767 svc.setFilter("(component=" + component + ")"); 768 svc.setAvailability(componentDefinitionRegistry.containsComponentDefinition(component) ? AVAILABILITY_OPTIONAL : AVAILABILITY_MANDATORY); 769 try { 770 // Try to set the runtime interface (only with aries blueprint > 0.1 771 svc.getClass().getMethod("setRuntimeInterface", Class.class).invoke(svc, ComponentResolver.class); 772 } catch (Throwable t) { 773 // Check if the bundle can see the class 774 try { 775 PassThroughMetadata ptm = (PassThroughMetadata) componentDefinitionRegistry.getComponentDefinition("blueprintBundle"); 776 Bundle b = (Bundle) ptm.getObject(); 777 if (b.loadClass(ComponentResolver.class.getName()) != ComponentResolver.class) { 778 throw new UnsupportedOperationException(); 779 } 780 svc.setInterface(ComponentResolver.class.getName()); 781 } catch (Throwable t2) { 782 throw new UnsupportedOperationException(); 783 } 784 } 785 componentDefinitionRegistry.registerComponentDefinition(svc); 786 cm = svc; 787 } 788 return cm; 789 } 790 791 public static class PassThroughCallable<T> implements Callable<T> { 792 793 private T value; 794 795 public PassThroughCallable(T value) { 796 this.value = value; 797 } 798 799 @Override 800 public T call() throws Exception { 801 return value; 802 } 803 } 804 805 public static class CamelInjector extends CamelPostProcessorHelper implements BeanProcessor { 806 807 private final String camelContextName; 808 private BlueprintContainer blueprintContainer; 809 810 public CamelInjector(String camelContextName) { 811 this.camelContextName = camelContextName; 812 } 813 814 public void setBlueprintContainer(BlueprintContainer blueprintContainer) { 815 this.blueprintContainer = blueprintContainer; 816 } 817 818 @Override 819 public CamelContext getCamelContext() { 820 if (blueprintContainer != null) { 821 CamelContext answer = (CamelContext) blueprintContainer.getComponentInstance(camelContextName); 822 return answer; 823 } 824 return null; 825 } 826 827 @Override 828 public Object beforeInit(Object bean, String beanName, BeanCreator beanCreator, BeanMetadata beanMetadata) { 829 LOG.trace("Before init of bean: {} -> {}", beanName, bean); 830 // prefer to inject later in afterInit 831 return bean; 832 } 833 834 /** 835 * A strategy method to allow implementations to perform some custom JBI 836 * based injection of the POJO 837 * 838 * @param bean the bean to be injected 839 */ 840 protected void injectFields(final Object bean, final String beanName) { 841 Class<?> clazz = bean.getClass(); 842 do { 843 Field[] fields = clazz.getDeclaredFields(); 844 for (Field field : fields) { 845 PropertyInject propertyInject = field.getAnnotation(PropertyInject.class); 846 if (propertyInject != null) { 847 injectFieldProperty(field, propertyInject.value(), propertyInject.defaultValue(), bean, beanName); 848 } 849 850 BeanInject beanInject = field.getAnnotation(BeanInject.class); 851 if (beanInject != null) { 852 injectFieldBean(field, beanInject.value(), bean, beanName); 853 } 854 855 EndpointInject endpointInject = field.getAnnotation(EndpointInject.class); 856 if (endpointInject != null) { 857 String uri = endpointInject.value().isEmpty() ? endpointInject.uri() : endpointInject.value(); 858 injectField(field, uri, endpointInject.property(), bean, beanName); 859 } 860 861 Produce produce = field.getAnnotation(Produce.class); 862 if (produce != null) { 863 String uri = produce.value().isEmpty() ? produce.uri() : produce.value(); 864 injectField(field, uri, produce.property(), bean, beanName); 865 } 866 } 867 clazz = clazz.getSuperclass(); 868 } while (clazz != null && clazz != Object.class); 869 } 870 871 protected void injectField(Field field, String endpointUri, String endpointProperty, Object bean, String beanName) { 872 setField(field, bean, getInjectionValue(field.getType(), endpointUri, endpointProperty, field.getName(), bean, beanName)); 873 } 874 875 protected void injectFieldProperty(Field field, String propertyName, String propertyDefaultValue, Object bean, String beanName) { 876 setField(field, bean, getInjectionPropertyValue(field.getType(), propertyName, propertyDefaultValue, field.getName(), bean, beanName)); 877 } 878 879 public void injectFieldBean(Field field, String name, Object bean, String beanName) { 880 setField(field, bean, getInjectionBeanValue(field.getType(), name)); 881 } 882 883 protected static void setField(Field field, Object instance, Object value) { 884 try { 885 boolean oldAccessible = field.isAccessible(); 886 boolean shouldSetAccessible = !Modifier.isPublic(field.getModifiers()) && !oldAccessible; 887 if (shouldSetAccessible) { 888 field.setAccessible(true); 889 } 890 field.set(instance, value); 891 if (shouldSetAccessible) { 892 field.setAccessible(oldAccessible); 893 } 894 } catch (IllegalArgumentException ex) { 895 throw new UnsupportedOperationException("Cannot inject value of class: " + value.getClass() + " into: " + field); 896 } catch (IllegalAccessException ex) { 897 throw new IllegalStateException("Could not access method: " + ex.getMessage()); 898 } 899 } 900 901 protected void injectMethods(final Object bean, final String beanName) { 902 Class<?> clazz = bean.getClass(); 903 do { 904 Method[] methods = clazz.getDeclaredMethods(); 905 for (Method method : methods) { 906 setterInjection(method, bean, beanName); 907 consumerInjection(method, bean, beanName); 908 } 909 clazz = clazz.getSuperclass(); 910 } while (clazz != null && clazz != Object.class); 911 } 912 913 protected void setterInjection(Method method, Object bean, String beanName) { 914 PropertyInject propertyInject = method.getAnnotation(PropertyInject.class); 915 if (propertyInject != null) { 916 setterPropertyInjection(method, propertyInject.value(), propertyInject.defaultValue(), bean, beanName); 917 } 918 919 BeanInject beanInject = method.getAnnotation(BeanInject.class); 920 if (beanInject != null) { 921 setterBeanInjection(method, beanInject.value(), bean, beanName); 922 } 923 924 EndpointInject endpointInject = method.getAnnotation(EndpointInject.class); 925 if (endpointInject != null) { 926 String uri = endpointInject.value().isEmpty() ? endpointInject.uri() : endpointInject.value(); 927 setterInjection(method, bean, beanName, uri, endpointInject.property()); 928 } 929 930 Produce produce = method.getAnnotation(Produce.class); 931 if (produce != null) { 932 String uri = produce.value().isEmpty() ? produce.uri() : produce.value(); 933 setterInjection(method, bean, beanName, uri, produce.property()); 934 } 935 } 936 937 protected void setterPropertyInjection(Method method, String propertyValue, String propertyDefaultValue, Object bean, String beanName) { 938 Class<?>[] parameterTypes = method.getParameterTypes(); 939 if (parameterTypes.length != 1) { 940 LOG.warn("Ignoring badly annotated method for injection due to incorrect number of parameters: {}", method); 941 } else { 942 String propertyName = org.apache.camel.util.ObjectHelper.getPropertyName(method); 943 Object value = getInjectionPropertyValue(parameterTypes[0], propertyValue, propertyDefaultValue, propertyName, bean, beanName); 944 ObjectHelper.invokeMethod(method, bean, value); 945 } 946 } 947 948 protected void setterBeanInjection(Method method, String name, Object bean, String beanName) { 949 Class<?>[] parameterTypes = method.getParameterTypes(); 950 if (parameterTypes.length != 1) { 951 LOG.warn("Ignoring badly annotated method for injection due to incorrect number of parameters: {}", method); 952 } else { 953 Object value = getInjectionBeanValue(parameterTypes[0], name); 954 ObjectHelper.invokeMethod(method, bean, value); 955 } 956 } 957 958 protected void setterInjection(Method method, Object bean, String beanName, String endpointUri, String endpointProperty) { 959 Class<?>[] parameterTypes = method.getParameterTypes(); 960 if (parameterTypes.length != 1) { 961 LOG.warn("Ignoring badly annotated method for injection due to incorrect number of parameters: {}", method); 962 } else { 963 String propertyName = org.apache.camel.util.ObjectHelper.getPropertyName(method); 964 Object value = getInjectionValue(parameterTypes[0], endpointUri, endpointProperty, propertyName, bean, beanName); 965 ObjectHelper.invokeMethod(method, bean, value); 966 } 967 } 968 969 @Override 970 public Object afterInit(Object bean, String beanName, BeanCreator beanCreator, BeanMetadata beanMetadata) { 971 LOG.trace("After init of bean: {} -> {}", beanName, bean); 972 // we cannot inject CamelContextAware beans as the CamelContext may not be ready 973 // TODO: use bean post processor instead 974 injectFields(bean, beanName); 975 injectMethods(bean, beanName); 976 return bean; 977 } 978 979 @Override 980 public void beforeDestroy(Object bean, String beanName) { 981 } 982 983 @Override 984 public void afterDestroy(Object bean, String beanName) { 985 } 986 987 @Override 988 protected boolean isSingleton(Object bean, String beanName) { 989 if (beanName != null) { 990 ComponentMetadata meta = blueprintContainer.getComponentMetadata(beanName); 991 if (meta instanceof BeanMetadata) { 992 String scope = ((BeanMetadata) meta).getScope(); 993 if (scope != null) { 994 return BeanMetadata.SCOPE_SINGLETON.equals(scope); 995 } 996 } 997 } 998 // fallback to super, which will assume singleton 999 // for beans not implementing Camel's IsSingleton interface 1000 return super.isSingleton(bean, beanName); 1001 } 1002 } 1003 1004 public static class CamelDependenciesFinder implements ComponentDefinitionRegistryProcessor { 1005 1006 private final String camelContextName; 1007 private final ParserContext context; 1008 private BlueprintContainer blueprintContainer; 1009 1010 public CamelDependenciesFinder(String camelContextName, ParserContext context) { 1011 this.camelContextName = camelContextName; 1012 this.context = context; 1013 } 1014 1015 public void setBlueprintContainer(BlueprintContainer blueprintContainer) { 1016 this.blueprintContainer = blueprintContainer; 1017 } 1018 1019 @Override 1020 public void process(ComponentDefinitionRegistry componentDefinitionRegistry) { 1021 CamelContextFactoryBean ccfb = (CamelContextFactoryBean) blueprintContainer.getComponentInstance(".camelBlueprint.factory." + camelContextName); 1022 CamelContext camelContext = ccfb.getContext(); 1023 1024 Set<String> components = new HashSet<>(); 1025 Set<String> languages = new HashSet<>(); 1026 Set<String> dataformats = new HashSet<>(); 1027 1028 // regular camel routes 1029 for (RouteDefinition rd : camelContext.getExtension(Model.class).getRouteDefinitions()) { 1030 findInputComponents(rd.getInput(), components, languages, dataformats); 1031 findOutputComponents(rd.getOutputs(), components, languages, dataformats); 1032 } 1033 1034 // rest services can have embedded routes or a singular to 1035 for (RestDefinition rd : camelContext.getExtension(Model.class).getRestDefinitions()) { 1036 for (VerbDefinition vd : rd.getVerbs()) { 1037 Object o = vd.getToOrRoute(); 1038 if (o instanceof RouteDefinition) { 1039 RouteDefinition route = (RouteDefinition) o; 1040 findInputComponents(route.getInput(), components, languages, dataformats); 1041 findOutputComponents(route.getOutputs(), components, languages, dataformats); 1042 } else if (o instanceof ToDefinition) { 1043 findUriComponent(((ToDefinition) o).getUri(), components); 1044 } else if (o instanceof ToDynamicDefinition) { 1045 findUriComponent(((ToDynamicDefinition) o).getUri(), components); 1046 } 1047 } 1048 } 1049 1050 if (ccfb.getRestConfiguration() != null) { 1051 // rest configuration may refer to a component to use 1052 String component = ccfb.getRestConfiguration().getComponent(); 1053 if (component != null) { 1054 components.add(component); 1055 } 1056 component = ccfb.getRestConfiguration().getApiComponent(); 1057 if (component != null) { 1058 components.add(component); 1059 } 1060 1061 // check what data formats are used in binding mode 1062 RestBindingMode mode = ccfb.getRestConfiguration().getBindingMode(); 1063 String json = ccfb.getRestConfiguration().getJsonDataFormat(); 1064 if (json == null && mode != null) { 1065 if (RestBindingMode.json.equals(mode) || RestBindingMode.json_xml.equals(mode)) { 1066 // jackson is the default json data format 1067 json = "json-jackson"; 1068 } 1069 } 1070 if (json != null) { 1071 dataformats.add(json); 1072 } 1073 String xml = ccfb.getRestConfiguration().getXmlDataFormat(); 1074 if (xml == null && mode != null) { 1075 if (RestBindingMode.xml.equals(mode) || RestBindingMode.json_xml.equals(mode)) { 1076 // jaxb is the default xml data format 1077 dataformats.add("jaxb"); 1078 } 1079 } 1080 if (xml != null) { 1081 dataformats.add(xml); 1082 } 1083 } 1084 1085 // We can only add service references to resolvers, but we can't make the factory depends on those 1086 // because the factory has already been instantiated 1087 try { 1088 for (String component : components) { 1089 if (camelContext.getComponent(component, false) == null) { 1090 // component not already in camel-context so resolve an OSGi reference to it 1091 getComponentResolverReference(context, component); 1092 } else { 1093 LOG.debug("Not creating a service reference for component {} because a component already exists in the Camel Context", component); 1094 } 1095 } 1096 for (String language : languages) { 1097 getLanguageResolverReference(context, language); 1098 } 1099 for (String dataformat : dataformats) { 1100 getDataformatResolverReference(context, dataformat); 1101 } 1102 } catch (UnsupportedOperationException e) { 1103 LOG.warn("Unable to add dependencies to Camel components OSGi services. " 1104 + "The Apache Aries blueprint implementation used is too old and the blueprint bundle cannot see the org.apache.camel.spi package."); 1105 components.clear(); 1106 languages.clear(); 1107 dataformats.clear(); 1108 } 1109 1110 } 1111 1112 private void findInputComponents(FromDefinition from, Set<String> components, Set<String> languages, Set<String> dataformats) { 1113 if (from != null) { 1114 findUriComponent(from.getUri(), components); 1115 findSchedulerUriComponent(from.getUri(), components); 1116 } 1117 } 1118 1119 @SuppressWarnings({"rawtypes"}) 1120 private void findOutputComponents(List<ProcessorDefinition<?>> defs, Set<String> components, Set<String> languages, Set<String> dataformats) { 1121 if (defs != null) { 1122 for (ProcessorDefinition<?> def : defs) { 1123 if (def instanceof SendDefinition) { 1124 findUriComponent(((SendDefinition) def).getUri(), components); 1125 } 1126 if (def instanceof MarshalDefinition) { 1127 findDataFormat(((MarshalDefinition) def).getDataFormatType(), dataformats); 1128 } 1129 if (def instanceof UnmarshalDefinition) { 1130 findDataFormat(((UnmarshalDefinition) def).getDataFormatType(), dataformats); 1131 } 1132 if (def instanceof ExpressionNode) { 1133 findLanguage(((ExpressionNode) def).getExpression(), languages); 1134 } 1135 if (def instanceof ResequenceDefinition) { 1136 findLanguage(((ResequenceDefinition) def).getExpression(), languages); 1137 } 1138 if (def instanceof AggregateDefinition) { 1139 findLanguage(((AggregateDefinition) def).getExpression(), languages); 1140 findLanguage(((AggregateDefinition) def).getCorrelationExpression(), languages); 1141 findLanguage(((AggregateDefinition) def).getCompletionPredicate(), languages); 1142 findLanguage(((AggregateDefinition) def).getCompletionTimeoutExpression(), languages); 1143 findLanguage(((AggregateDefinition) def).getCompletionSizeExpression(), languages); 1144 } 1145 if (def instanceof CatchDefinition) { 1146 CatchDefinition doCatch = (CatchDefinition) def; 1147 if (doCatch.getOnWhen() != null) { 1148 findLanguage(doCatch.getOnWhen().getExpression(), languages); 1149 } 1150 } 1151 if (def instanceof OnExceptionDefinition) { 1152 findLanguage(((OnExceptionDefinition) def).getRetryWhile(), languages); 1153 findLanguage(((OnExceptionDefinition) def).getHandled(), languages); 1154 findLanguage(((OnExceptionDefinition) def).getContinued(), languages); 1155 } 1156 if (def instanceof SortDefinition) { 1157 findLanguage(((SortDefinition) def).getExpression(), languages); 1158 } 1159 if (def instanceof WireTapDefinition) { 1160 findLanguage(((WireTapDefinition<?>) def).getNewExchangeExpression(), languages); 1161 } 1162 findOutputComponents(def.getOutputs(), components, languages, dataformats); 1163 } 1164 } 1165 } 1166 1167 private void findLanguage(ExpressionDefinition expression, Set<String> languages) { 1168 if (expression != null) { 1169 String lang = expression.getLanguage(); 1170 if (lang != null && lang.length() > 0) { 1171 languages.add(lang); 1172 } 1173 } 1174 } 1175 1176 private void findLanguage(ExpressionSubElementDefinition expression, Set<String> languages) { 1177 if (expression != null) { 1178 findLanguage(expression.getExpressionType(), languages); 1179 } 1180 } 1181 1182 private void findDataFormat(DataFormatDefinition dfd, Set<String> dataformats) { 1183 if (dfd != null && dfd.getDataFormatName() != null) { 1184 dataformats.add(dfd.getDataFormatName()); 1185 } 1186 } 1187 1188 private void findUriComponent(String uri, Set<String> components) { 1189 // if the uri is a placeholder then skip it 1190 if (uri == null || uri.startsWith(PropertiesComponent.PREFIX_TOKEN)) { 1191 return; 1192 } 1193 1194 // validate uri here up-front so a meaningful error can be logged for blueprint 1195 // it will also speed up tests in case of failure 1196 if (!validateUri(uri)) { 1197 return; 1198 } 1199 1200 String splitURI[] = StringHelper.splitOnCharacter(uri, ":", 2); 1201 if (splitURI[1] != null) { 1202 String scheme = splitURI[0]; 1203 components.add(scheme); 1204 } 1205 } 1206 1207 private void findSchedulerUriComponent(String uri, Set<String> components) { 1208 1209 // the input may use a scheduler which can be quartz or spring 1210 if (uri != null) { 1211 try { 1212 URI u = new URI(uri); 1213 Map<String, Object> parameters = URISupport.parseParameters(u); 1214 Object value = parameters.get("scheduler"); 1215 if (value != null) { 1216 // the scheduler can be quartz or spring based, so add reference to camel component 1217 // from these components os blueprint knows about the requirement 1218 String name = value.toString(); 1219 if ("quartz".equals(name)) { 1220 components.add("quartz"); 1221 } else if ("spring".equals(name)) { 1222 components.add("spring-event"); 1223 } 1224 } 1225 } catch (URISyntaxException e) { 1226 // ignore as uri should be already validated at findUriComponent method 1227 } 1228 } 1229 } 1230 1231 private static boolean validateUri(String uri) { 1232 try { 1233 // the same validation as done in DefaultCamelContext#normalizeEndpointUri(String) 1234 URISupport.normalizeUri(uri); 1235 } catch (URISyntaxException | UnsupportedEncodingException e) { 1236 LOG.error("Endpoint URI '" + uri + "' is not valid due to: " + e.getMessage(), e); 1237 return false; 1238 } 1239 return true; 1240 } 1241 } 1242 1243}