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.component.bean; 018 019import java.lang.annotation.Annotation; 020import java.lang.reflect.AccessibleObject; 021import java.lang.reflect.AnnotatedElement; 022import java.lang.reflect.InvocationTargetException; 023import java.lang.reflect.Method; 024import java.lang.reflect.Modifier; 025import java.util.ArrayList; 026import java.util.Arrays; 027import java.util.HashMap; 028import java.util.Iterator; 029import java.util.List; 030import java.util.Map; 031import java.util.concurrent.Callable; 032import java.util.concurrent.CompletionStage; 033import java.util.concurrent.ExecutorService; 034 035import org.apache.camel.AsyncCallback; 036import org.apache.camel.CamelContext; 037import org.apache.camel.Exchange; 038import org.apache.camel.ExchangePattern; 039import org.apache.camel.Expression; 040import org.apache.camel.ExpressionEvaluationException; 041import org.apache.camel.Message; 042import org.apache.camel.NoTypeConversionAvailableException; 043import org.apache.camel.Pattern; 044import org.apache.camel.Processor; 045import org.apache.camel.RuntimeExchangeException; 046import org.apache.camel.StreamCache; 047import org.apache.camel.impl.DefaultMessage; 048import org.apache.camel.processor.DynamicRouter; 049import org.apache.camel.processor.RecipientList; 050import org.apache.camel.processor.RoutingSlip; 051import org.apache.camel.processor.aggregate.AggregationStrategy; 052import org.apache.camel.support.ExpressionAdapter; 053import org.apache.camel.util.CamelContextHelper; 054import org.apache.camel.util.ExchangeHelper; 055import org.apache.camel.util.ObjectHelper; 056import org.apache.camel.util.ServiceHelper; 057import org.apache.camel.util.StringHelper; 058import org.apache.camel.util.StringQuoteHelper; 059import org.slf4j.Logger; 060import org.slf4j.LoggerFactory; 061 062import static org.apache.camel.util.ObjectHelper.asString; 063 064/** 065 * Information about a method to be used for invocation. 066 * 067 * @version 068 */ 069public class MethodInfo { 070 private static final Logger LOG = LoggerFactory.getLogger(MethodInfo.class); 071 072 private CamelContext camelContext; 073 private Class<?> type; 074 private Method method; 075 private final List<ParameterInfo> parameters; 076 private final List<ParameterInfo> bodyParameters; 077 private final boolean hasCustomAnnotation; 078 private final boolean hasHandlerAnnotation; 079 private Expression parametersExpression; 080 private ExchangePattern pattern = ExchangePattern.InOut; 081 private RecipientList recipientList; 082 private RoutingSlip routingSlip; 083 private DynamicRouter dynamicRouter; 084 085 /** 086 * Adapter to invoke the method which has been annotated with the @DynamicRouter 087 */ 088 private final class DynamicRouterExpression extends ExpressionAdapter { 089 private final Object pojo; 090 091 private DynamicRouterExpression(Object pojo) { 092 this.pojo = pojo; 093 } 094 095 @Override 096 public Object evaluate(Exchange exchange) { 097 // evaluate arguments on each invocation as the parameters can have changed/updated since last invocation 098 final Object[] arguments = parametersExpression.evaluate(exchange, Object[].class); 099 try { 100 return invoke(method, pojo, arguments, exchange); 101 } catch (Exception e) { 102 throw ObjectHelper.wrapRuntimeCamelException(e); 103 } 104 } 105 106 @Override 107 public String toString() { 108 return "DynamicRouter[invoking: " + method + " on bean: " + pojo + "]"; 109 } 110 } 111 112 @SuppressWarnings("deprecation") 113 public MethodInfo(CamelContext camelContext, Class<?> type, Method method, List<ParameterInfo> parameters, List<ParameterInfo> bodyParameters, 114 boolean hasCustomAnnotation, boolean hasHandlerAnnotation) { 115 this.camelContext = camelContext; 116 this.type = type; 117 this.method = method; 118 this.parameters = parameters; 119 this.bodyParameters = bodyParameters; 120 this.hasCustomAnnotation = hasCustomAnnotation; 121 this.hasHandlerAnnotation = hasHandlerAnnotation; 122 this.parametersExpression = createParametersExpression(); 123 124 Map<Class<?>, Annotation> collectedMethodAnnotation = collectMethodAnnotations(type, method); 125 126 Pattern oneway = findOneWayAnnotation(method); 127 if (oneway != null) { 128 pattern = oneway.value(); 129 } 130 131 org.apache.camel.RoutingSlip routingSlipAnnotation = 132 (org.apache.camel.RoutingSlip)collectedMethodAnnotation.get(org.apache.camel.RoutingSlip.class); 133 if (routingSlipAnnotation != null && matchContext(routingSlipAnnotation.context())) { 134 routingSlip = new RoutingSlip(camelContext); 135 routingSlip.setDelimiter(routingSlipAnnotation.delimiter()); 136 routingSlip.setIgnoreInvalidEndpoints(routingSlipAnnotation.ignoreInvalidEndpoints()); 137 // add created routingSlip as a service so we have its lifecycle managed 138 try { 139 camelContext.addService(routingSlip); 140 } catch (Exception e) { 141 throw ObjectHelper.wrapRuntimeCamelException(e); 142 } 143 } 144 145 org.apache.camel.DynamicRouter dynamicRouterAnnotation = 146 (org.apache.camel.DynamicRouter)collectedMethodAnnotation.get(org.apache.camel.DynamicRouter.class); 147 if (dynamicRouterAnnotation != null 148 && matchContext(dynamicRouterAnnotation.context())) { 149 dynamicRouter = new DynamicRouter(camelContext); 150 dynamicRouter.setDelimiter(dynamicRouterAnnotation.delimiter()); 151 dynamicRouter.setIgnoreInvalidEndpoints(dynamicRouterAnnotation.ignoreInvalidEndpoints()); 152 // add created dynamicRouter as a service so we have its lifecycle managed 153 try { 154 camelContext.addService(dynamicRouter); 155 } catch (Exception e) { 156 throw ObjectHelper.wrapRuntimeCamelException(e); 157 } 158 } 159 160 org.apache.camel.RecipientList recipientListAnnotation = 161 (org.apache.camel.RecipientList)collectedMethodAnnotation.get(org.apache.camel.RecipientList.class); 162 if (recipientListAnnotation != null 163 && matchContext(recipientListAnnotation.context())) { 164 recipientList = new RecipientList(camelContext, recipientListAnnotation.delimiter()); 165 recipientList.setStopOnException(recipientListAnnotation.stopOnException()); 166 recipientList.setStopOnAggregateException(recipientListAnnotation.stopOnAggregateException()); 167 recipientList.setIgnoreInvalidEndpoints(recipientListAnnotation.ignoreInvalidEndpoints()); 168 recipientList.setParallelProcessing(recipientListAnnotation.parallelProcessing()); 169 recipientList.setParallelAggregate(recipientListAnnotation.parallelAggregate()); 170 recipientList.setStreaming(recipientListAnnotation.streaming()); 171 recipientList.setTimeout(recipientListAnnotation.timeout()); 172 recipientList.setShareUnitOfWork(recipientListAnnotation.shareUnitOfWork()); 173 174 if (ObjectHelper.isNotEmpty(recipientListAnnotation.executorServiceRef())) { 175 ExecutorService executor = camelContext.getExecutorServiceManager().newDefaultThreadPool(this, recipientListAnnotation.executorServiceRef()); 176 recipientList.setExecutorService(executor); 177 } 178 179 if (recipientListAnnotation.parallelProcessing() && recipientList.getExecutorService() == null) { 180 // we are running in parallel so we need a thread pool 181 ExecutorService executor = camelContext.getExecutorServiceManager().newDefaultThreadPool(this, "@RecipientList"); 182 recipientList.setExecutorService(executor); 183 } 184 185 if (ObjectHelper.isNotEmpty(recipientListAnnotation.strategyRef())) { 186 AggregationStrategy strategy = CamelContextHelper.mandatoryLookup(camelContext, recipientListAnnotation.strategyRef(), AggregationStrategy.class); 187 recipientList.setAggregationStrategy(strategy); 188 } 189 190 if (ObjectHelper.isNotEmpty(recipientListAnnotation.onPrepareRef())) { 191 Processor onPrepare = CamelContextHelper.mandatoryLookup(camelContext, recipientListAnnotation.onPrepareRef(), Processor.class); 192 recipientList.setOnPrepare(onPrepare); 193 } 194 195 // add created recipientList as a service so we have its lifecycle managed 196 try { 197 camelContext.addService(recipientList); 198 } catch (Exception e) { 199 throw ObjectHelper.wrapRuntimeCamelException(e); 200 } 201 } 202 } 203 204 private Map<Class<?>, Annotation> collectMethodAnnotations(Class<?> c, Method method) { 205 Map<Class<?>, Annotation> annotations = new HashMap<Class<?>, Annotation>(); 206 collectMethodAnnotations(c, method, annotations); 207 return annotations; 208 } 209 210 private void collectMethodAnnotations(Class<?> c, Method method, Map<Class<?>, Annotation> annotations) { 211 for (Class<?> i : c.getInterfaces()) { 212 collectMethodAnnotations(i, method, annotations); 213 } 214 if (!c.isInterface() && c.getSuperclass() != null) { 215 collectMethodAnnotations(c.getSuperclass(), method, annotations); 216 } 217 // make sure the sub class can override the definition 218 try { 219 Annotation[] ma = c.getDeclaredMethod(method.getName(), method.getParameterTypes()).getAnnotations(); 220 for (Annotation a : ma) { 221 annotations.put(a.annotationType(), a); 222 } 223 } catch (SecurityException e) { 224 // do nothing here 225 } catch (NoSuchMethodException e) { 226 // do nothing here 227 } 228 } 229 230 /** 231 * Does the given context match this camel context 232 */ 233 private boolean matchContext(String context) { 234 if (ObjectHelper.isNotEmpty(context)) { 235 if (!camelContext.getName().equals(context)) { 236 return false; 237 } 238 } 239 return true; 240 } 241 242 public String toString() { 243 return method.toString(); 244 } 245 246 public MethodInvocation createMethodInvocation(final Object pojo, boolean hasParameters, final Exchange exchange) { 247 final Object[] arguments; 248 if (hasParameters) { 249 arguments = parametersExpression.evaluate(exchange, Object[].class); 250 } else { 251 arguments = null; 252 } 253 254 return new MethodInvocation() { 255 public Method getMethod() { 256 return method; 257 } 258 259 public Object[] getArguments() { 260 return arguments; 261 } 262 263 public boolean proceed(AsyncCallback callback) { 264 Object body = exchange.getIn().getBody(); 265 if (body != null && body instanceof StreamCache) { 266 // ensure the stream cache is reset before calling the method 267 ((StreamCache) body).reset(); 268 } 269 try { 270 return doProceed(callback); 271 } catch (InvocationTargetException e) { 272 exchange.setException(e.getTargetException()); 273 callback.done(true); 274 return true; 275 } catch (Throwable e) { 276 exchange.setException(e); 277 callback.done(true); 278 return true; 279 } 280 } 281 282 private boolean doProceed(AsyncCallback callback) throws Exception { 283 // dynamic router should be invoked beforehand 284 if (dynamicRouter != null) { 285 if (!dynamicRouter.isStarted()) { 286 ServiceHelper.startService(dynamicRouter); 287 } 288 // use a expression which invokes the method to be used by dynamic router 289 Expression expression = new DynamicRouterExpression(pojo); 290 return dynamicRouter.doRoutingSlip(exchange, expression, callback); 291 } 292 293 // invoke pojo 294 if (LOG.isTraceEnabled()) { 295 LOG.trace(">>>> invoking: {} on bean: {} with arguments: {} for exchange: {}", new Object[]{method, pojo, asString(arguments), exchange}); 296 } 297 Object result = invoke(method, pojo, arguments, exchange); 298 299 // the method may be a closure or chained method returning a callable which should be called 300 if (result instanceof Callable) { 301 LOG.trace("Method returned Callback which will be called: {}", result); 302 Object callableResult = ((Callable) result).call(); 303 if (callableResult != null) { 304 result = callableResult; 305 } else { 306 // if callable returned null we should not change the body 307 result = Void.TYPE; 308 } 309 } 310 311 if (recipientList != null) { 312 // ensure its started 313 if (!recipientList.isStarted()) { 314 ServiceHelper.startService(recipientList); 315 } 316 return recipientList.sendToRecipientList(exchange, result, callback); 317 } 318 if (routingSlip != null) { 319 if (!routingSlip.isStarted()) { 320 ServiceHelper.startService(routingSlip); 321 } 322 return routingSlip.doRoutingSlip(exchange, result, callback); 323 } 324 325 //If it's Java 8 async result 326 if (CompletionStage.class.isAssignableFrom(getMethod().getReturnType())) { 327 CompletionStage<?> completionStage = (CompletionStage<?>) result; 328 329 completionStage 330 .whenComplete((resultObject, e) -> { 331 if (e != null) { 332 exchange.setException(e); 333 } else if (resultObject != null) { 334 fillResult(exchange, resultObject); 335 } 336 callback.done(false); 337 }); 338 return false; 339 } 340 341 // if the method returns something then set the value returned on the Exchange 342 if (!getMethod().getReturnType().equals(Void.TYPE) && result != Void.TYPE) { 343 fillResult(exchange, result); 344 } 345 346 // we did not use any of the eips, but just invoked the bean 347 // so notify the callback we are done synchronously 348 callback.done(true); 349 return true; 350 } 351 352 public Object getThis() { 353 return pojo; 354 } 355 356 public AccessibleObject getStaticPart() { 357 return method; 358 } 359 }; 360 } 361 362 private void fillResult(Exchange exchange, Object result) { 363 LOG.trace("Setting bean invocation result : {}", result); 364 365 // the bean component forces OUT if the MEP is OUT capable 366 boolean out = ExchangeHelper.isOutCapable(exchange) || exchange.hasOut(); 367 Message old; 368 if (out) { 369 old = exchange.getOut(); 370 // propagate headers 371 exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders()); 372 // propagate attachments 373 if (exchange.getIn().hasAttachments()) { 374 exchange.getOut().getAttachments().putAll(exchange.getIn().getAttachments()); 375 } 376 } else { 377 old = exchange.getIn(); 378 } 379 380 // create a new message container so we do not drag specialized message objects along 381 // but that is only needed if the old message is a specialized message 382 boolean copyNeeded = !(old.getClass().equals(DefaultMessage.class)); 383 384 if (copyNeeded) { 385 Message msg = new DefaultMessage(exchange.getContext()); 386 msg.copyFromWithNewBody(old, result); 387 388 // replace message on exchange 389 ExchangeHelper.replaceMessage(exchange, msg, false); 390 } else { 391 // no copy needed so set replace value directly 392 old.setBody(result); 393 } 394 } 395 396 public Class<?> getType() { 397 return type; 398 } 399 400 public Method getMethod() { 401 return method; 402 } 403 404 /** 405 * Returns the {@link org.apache.camel.ExchangePattern} that should be used when invoking this method. This value 406 * defaults to {@link org.apache.camel.ExchangePattern#InOut} unless some {@link org.apache.camel.Pattern} annotation is used 407 * to override the message exchange pattern. 408 * 409 * @return the exchange pattern to use for invoking this method. 410 */ 411 public ExchangePattern getPattern() { 412 return pattern; 413 } 414 415 public Expression getParametersExpression() { 416 return parametersExpression; 417 } 418 419 public List<ParameterInfo> getBodyParameters() { 420 return bodyParameters; 421 } 422 423 public Class<?> getBodyParameterType() { 424 if (bodyParameters.isEmpty()) { 425 return null; 426 } 427 ParameterInfo parameterInfo = bodyParameters.get(0); 428 return parameterInfo.getType(); 429 } 430 431 public boolean bodyParameterMatches(Class<?> bodyType) { 432 Class<?> actualType = getBodyParameterType(); 433 return actualType != null && ObjectHelper.isAssignableFrom(bodyType, actualType); 434 } 435 436 public List<ParameterInfo> getParameters() { 437 return parameters; 438 } 439 440 public boolean hasBodyParameter() { 441 return !bodyParameters.isEmpty(); 442 } 443 444 public boolean hasCustomAnnotation() { 445 return hasCustomAnnotation; 446 } 447 448 public boolean hasHandlerAnnotation() { 449 return hasHandlerAnnotation; 450 } 451 452 public boolean hasParameters() { 453 return !parameters.isEmpty(); 454 } 455 456 public boolean isReturnTypeVoid() { 457 return method.getReturnType().getName().equals("void"); 458 } 459 460 public boolean isStaticMethod() { 461 return Modifier.isStatic(method.getModifiers()); 462 } 463 464 /** 465 * Returns true if this method is covariant with the specified method 466 * (this method may above or below the specified method in the class hierarchy) 467 */ 468 public boolean isCovariantWith(MethodInfo method) { 469 return 470 method.getMethod().getName().equals(this.getMethod().getName()) 471 && (method.getMethod().getReturnType().isAssignableFrom(this.getMethod().getReturnType()) 472 || this.getMethod().getReturnType().isAssignableFrom(method.getMethod().getReturnType())) 473 && Arrays.deepEquals(method.getMethod().getParameterTypes(), this.getMethod().getParameterTypes()); 474 } 475 476 protected Object invoke(Method mth, Object pojo, Object[] arguments, Exchange exchange) throws InvocationTargetException { 477 try { 478 return mth.invoke(pojo, arguments); 479 } catch (IllegalAccessException e) { 480 throw new RuntimeExchangeException("IllegalAccessException occurred invoking method: " + mth + " using arguments: " + Arrays.asList(arguments), exchange, e); 481 } catch (IllegalArgumentException e) { 482 throw new RuntimeExchangeException("IllegalArgumentException occurred invoking method: " + mth + " using arguments: " + Arrays.asList(arguments), exchange, e); 483 } 484 } 485 486 protected Expression[] createParameterExpressions() { 487 final int size = parameters.size(); 488 LOG.trace("Creating parameters expression for {} parameters", size); 489 490 final Expression[] expressions = new Expression[size]; 491 for (int i = 0; i < size; i++) { 492 Expression parameterExpression = parameters.get(i).getExpression(); 493 expressions[i] = parameterExpression; 494 LOG.trace("Parameter #{} has expression: {}", i, parameterExpression); 495 } 496 497 return expressions; 498 } 499 500 protected Expression createParametersExpression() { 501 return new ParameterExpression(createParameterExpressions()); 502 } 503 504 /** 505 * Finds the oneway annotation in priority order; look for method level annotations first, then the class level annotations, 506 * then super class annotations then interface annotations 507 * 508 * @param method the method on which to search 509 * @return the first matching annotation or none if it is not available 510 */ 511 protected Pattern findOneWayAnnotation(Method method) { 512 Pattern answer = getPatternAnnotation(method); 513 if (answer == null) { 514 Class<?> type = method.getDeclaringClass(); 515 516 // create the search order of types to scan 517 List<Class<?>> typesToSearch = new ArrayList<Class<?>>(); 518 addTypeAndSuperTypes(type, typesToSearch); 519 Class<?>[] interfaces = type.getInterfaces(); 520 for (Class<?> anInterface : interfaces) { 521 addTypeAndSuperTypes(anInterface, typesToSearch); 522 } 523 524 // now let's scan for a type which the current declared class overloads 525 answer = findOneWayAnnotationOnMethod(typesToSearch, method); 526 if (answer == null) { 527 answer = findOneWayAnnotation(typesToSearch); 528 } 529 } 530 return answer; 531 } 532 533 /** 534 * Returns the pattern annotation on the given annotated element; either as a direct annotation or 535 * on an annotation which is also annotated 536 * 537 * @param annotatedElement the element to look for the annotation 538 * @return the first matching annotation or null if none could be found 539 */ 540 protected Pattern getPatternAnnotation(AnnotatedElement annotatedElement) { 541 return getPatternAnnotation(annotatedElement, 2); 542 } 543 544 /** 545 * Returns the pattern annotation on the given annotated element; either as a direct annotation or 546 * on an annotation which is also annotated 547 * 548 * @param annotatedElement the element to look for the annotation 549 * @param depth the current depth 550 * @return the first matching annotation or null if none could be found 551 */ 552 protected Pattern getPatternAnnotation(AnnotatedElement annotatedElement, int depth) { 553 Pattern answer = annotatedElement.getAnnotation(Pattern.class); 554 int nextDepth = depth - 1; 555 556 if (nextDepth > 0) { 557 // look at all the annotations to see if any of those are annotated 558 Annotation[] annotations = annotatedElement.getAnnotations(); 559 for (Annotation annotation : annotations) { 560 Class<? extends Annotation> annotationType = annotation.annotationType(); 561 if (annotation instanceof Pattern || annotationType.equals(annotatedElement)) { 562 continue; 563 } else { 564 Pattern another = getPatternAnnotation(annotationType, nextDepth); 565 if (pattern != null) { 566 if (answer == null) { 567 answer = another; 568 } else { 569 LOG.warn("Duplicate pattern annotation: " + another + " found on annotation: " + annotation + " which will be ignored"); 570 } 571 } 572 } 573 } 574 } 575 return answer; 576 } 577 578 /** 579 * Adds the current class and all of its base classes (apart from {@link Object} to the given list 580 */ 581 protected void addTypeAndSuperTypes(Class<?> type, List<Class<?>> result) { 582 for (Class<?> t = type; t != null && t != Object.class; t = t.getSuperclass()) { 583 result.add(t); 584 } 585 } 586 587 /** 588 * Finds the first annotation on the base methods defined in the list of classes 589 */ 590 protected Pattern findOneWayAnnotationOnMethod(List<Class<?>> classes, Method method) { 591 for (Class<?> type : classes) { 592 try { 593 Method definedMethod = type.getMethod(method.getName(), method.getParameterTypes()); 594 Pattern answer = getPatternAnnotation(definedMethod); 595 if (answer != null) { 596 return answer; 597 } 598 } catch (NoSuchMethodException e) { 599 // ignore 600 } 601 } 602 return null; 603 } 604 605 606 /** 607 * Finds the first annotation on the given list of classes 608 */ 609 protected Pattern findOneWayAnnotation(List<Class<?>> classes) { 610 for (Class<?> type : classes) { 611 Pattern answer = getPatternAnnotation(type); 612 if (answer != null) { 613 return answer; 614 } 615 } 616 return null; 617 } 618 619 protected boolean hasExceptionParameter() { 620 for (ParameterInfo parameter : parameters) { 621 if (Exception.class.isAssignableFrom(parameter.getType())) { 622 return true; 623 } 624 } 625 return false; 626 } 627 628 /** 629 * Expression to evaluate the bean parameter parameters and provide the correct values when the method is invoked. 630 */ 631 private final class ParameterExpression implements Expression { 632 private final Expression[] expressions; 633 634 ParameterExpression(Expression[] expressions) { 635 this.expressions = expressions; 636 } 637 638 @SuppressWarnings("unchecked") 639 public <T> T evaluate(Exchange exchange, Class<T> type) { 640 Object body = exchange.getIn().getBody(); 641 boolean multiParameterArray = exchange.getIn().getHeader(Exchange.BEAN_MULTI_PARAMETER_ARRAY, false, boolean.class); 642 if (multiParameterArray) { 643 // Just change the message body to an Object array 644 if (!(body instanceof Object[])) { 645 body = exchange.getIn().getBody(Object[].class); 646 } 647 } 648 649 // if there was an explicit method name to invoke, then we should support using 650 // any provided parameter values in the method name 651 String methodName = exchange.getIn().getHeader(Exchange.BEAN_METHOD_NAME, String.class); 652 // the parameter values is between the parenthesis 653 String methodParameters = StringHelper.betweenOuterPair(methodName, '(', ')'); 654 // use an iterator to walk the parameter values 655 Iterator<?> it = null; 656 if (methodParameters != null) { 657 // split the parameters safely separated by comma, but beware that we can have 658 // quoted parameters which contains comma as well, so do a safe quote split 659 String[] parameters = StringQuoteHelper.splitSafeQuote(methodParameters, ',', true); 660 it = ObjectHelper.createIterator(parameters, ",", true); 661 } 662 663 // remove headers as they should not be propagated 664 // we need to do this before the expressions gets evaluated as it may contain 665 // a @Bean expression which would by mistake read these headers. So the headers 666 // must be removed at this point of time 667 if (multiParameterArray) { 668 exchange.getIn().removeHeader(Exchange.BEAN_MULTI_PARAMETER_ARRAY); 669 } 670 if (methodName != null) { 671 exchange.getIn().removeHeader(Exchange.BEAN_METHOD_NAME); 672 } 673 674 Object[] answer = evaluateParameterExpressions(exchange, body, multiParameterArray, it); 675 return (T) answer; 676 } 677 678 /** 679 * Evaluates all the parameter expressions 680 */ 681 private Object[] evaluateParameterExpressions(Exchange exchange, Object body, boolean multiParameterArray, Iterator<?> it) { 682 Object[] answer = new Object[expressions.length]; 683 for (int i = 0; i < expressions.length; i++) { 684 685 if (body != null && body instanceof StreamCache) { 686 // need to reset stream cache for each expression as you may access the message body in multiple parameters 687 ((StreamCache) body).reset(); 688 } 689 690 // grab the parameter value for the given index 691 Object parameterValue = it != null && it.hasNext() ? it.next() : null; 692 // and the expected parameter type 693 Class<?> parameterType = parameters.get(i).getType(); 694 // the value for the parameter to use 695 Object value = null; 696 697 if (multiParameterArray && body instanceof Object[]) { 698 // get the value from the array 699 Object[] array = (Object[]) body; 700 if (array.length >= i) { 701 value = array[i]; 702 } 703 } else { 704 // prefer to use parameter value if given, as they override any bean parameter binding 705 // we should skip * as its a type placeholder to indicate any type 706 if (parameterValue != null && !parameterValue.equals("*")) { 707 // evaluate the parameter value binding 708 value = evaluateParameterValue(exchange, i, parameterValue, parameterType); 709 } 710 // use bean parameter binding, if still no value 711 Expression expression = expressions[i]; 712 if (value == null && expression != null) { 713 value = evaluateParameterBinding(exchange, expression, i, parameterType); 714 } 715 } 716 // remember the value to use 717 if (value != Void.TYPE) { 718 answer[i] = value; 719 } 720 } 721 722 return answer; 723 } 724 725 /** 726 * Evaluate using parameter values where the values can be provided in the method name syntax. 727 * <p/> 728 * This methods returns accordingly: 729 * <ul> 730 * <li><tt>null</tt> - if not a parameter value</li> 731 * <li><tt>Void.TYPE</tt> - if an explicit null, forcing Camel to pass in <tt>null</tt> for that given parameter</li> 732 * <li>a non <tt>null</tt> value - if the parameter was a parameter value, and to be used</li> 733 * </ul> 734 * 735 * @since 2.9 736 */ 737 private Object evaluateParameterValue(Exchange exchange, int index, Object parameterValue, Class<?> parameterType) { 738 Object answer = null; 739 740 // convert the parameter value to a String 741 String exp = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, parameterValue); 742 if (exp != null) { 743 // check if its a valid parameter value 744 boolean valid = BeanHelper.isValidParameterValue(exp); 745 746 if (!valid) { 747 // it may be a parameter type instead, and if so, then we should return null, 748 // as this method is only for evaluating parameter values 749 Boolean isClass = BeanHelper.isAssignableToExpectedType(exchange.getContext().getClassResolver(), exp, parameterType); 750 // the method will return a non null value if exp is a class 751 if (isClass != null) { 752 return null; 753 } 754 } 755 756 // use simple language to evaluate the expression, as it may use the simple language to refer to message body, headers etc. 757 Expression expression = null; 758 try { 759 expression = exchange.getContext().resolveLanguage("simple").createExpression(exp); 760 parameterValue = expression.evaluate(exchange, Object.class); 761 // use "null" to indicate the expression returned a null value which is a valid response we need to honor 762 if (parameterValue == null) { 763 parameterValue = "null"; 764 } 765 } catch (Exception e) { 766 throw new ExpressionEvaluationException(expression, "Cannot create/evaluate simple expression: " + exp 767 + " to be bound to parameter at index: " + index + " on method: " + getMethod(), exchange, e); 768 } 769 770 // special for explicit null parameter values (as end users can explicit indicate they want null as parameter) 771 // see method javadoc for details 772 if ("null".equals(parameterValue)) { 773 return Void.TYPE; 774 } 775 776 // the parameter value may match the expected type, then we use it as-is 777 if (parameterType.isAssignableFrom(parameterValue.getClass())) { 778 valid = true; 779 } else { 780 // the parameter value was not already valid, but since the simple language have evaluated the expression 781 // which may change the parameterValue, so we have to check it again to see if its now valid 782 exp = exchange.getContext().getTypeConverter().tryConvertTo(String.class, parameterValue); 783 // String values from the simple language is always valid 784 if (!valid) { 785 // re validate if the parameter was not valid the first time (String values should be accepted) 786 valid = parameterValue instanceof String || BeanHelper.isValidParameterValue(exp); 787 } 788 } 789 790 if (valid) { 791 // we need to unquote String parameters, as the enclosing quotes is there to denote a parameter value 792 if (parameterValue instanceof String) { 793 parameterValue = StringHelper.removeLeadingAndEndingQuotes((String) parameterValue); 794 } 795 if (parameterValue != null) { 796 try { 797 // its a valid parameter value, so convert it to the expected type of the parameter 798 answer = exchange.getContext().getTypeConverter().mandatoryConvertTo(parameterType, exchange, parameterValue); 799 if (LOG.isTraceEnabled()) { 800 LOG.trace("Parameter #{} evaluated as: {} type: ", new Object[]{index, answer, ObjectHelper.type(answer)}); 801 } 802 } catch (Exception e) { 803 if (LOG.isDebugEnabled()) { 804 LOG.debug("Cannot convert from type: {} to type: {} for parameter #{}", new Object[]{ObjectHelper.type(parameterValue), parameterType, index}); 805 } 806 throw new ParameterBindingException(e, method, index, parameterType, parameterValue); 807 } 808 } 809 } 810 } 811 812 return answer; 813 } 814 815 /** 816 * Evaluate using classic parameter binding using the pre compute expression 817 */ 818 private Object evaluateParameterBinding(Exchange exchange, Expression expression, int index, Class<?> parameterType) { 819 Object answer = null; 820 821 // use object first to avoid type conversion so we know if there is a value or not 822 Object result = expression.evaluate(exchange, Object.class); 823 if (result != null) { 824 try { 825 if (parameterType.isInstance(result)) { 826 // optimize if the value is already the same type 827 answer = result; 828 } else { 829 // we got a value now try to convert it to the expected type 830 answer = exchange.getContext().getTypeConverter().mandatoryConvertTo(parameterType, result); 831 } 832 if (LOG.isTraceEnabled()) { 833 LOG.trace("Parameter #{} evaluated as: {} type: ", new Object[]{index, answer, ObjectHelper.type(answer)}); 834 } 835 } catch (NoTypeConversionAvailableException e) { 836 if (LOG.isDebugEnabled()) { 837 LOG.debug("Cannot convert from type: {} to type: {} for parameter #{}", new Object[]{ObjectHelper.type(result), parameterType, index}); 838 } 839 throw new ParameterBindingException(e, method, index, parameterType, result); 840 } 841 } else { 842 LOG.trace("Parameter #{} evaluated as null", index); 843 } 844 845 return answer; 846 } 847 848 @Override 849 public String toString() { 850 return "ParametersExpression: " + Arrays.asList(expressions); 851 } 852 853 } 854}