@Override @SuppressWarnings("unchecked") public Processor createProcessor(RouteContext routeContext) throws Exception { // lookup in registry if (ObjectHelper.isNotEmpty(comparatorRef)) { comparator = routeContext.getCamelContext().getRegistry().lookupByNameAndType(comparatorRef, Comparator.class); } // if no comparator then default on to string representation if (comparator == null) { comparator = new Comparator<T>() { public int compare(T o1, T o2) { return ObjectHelper.compare(o1, o2); } }; } // if no expression provided then default to body expression Expression exp; if (getExpression() == null) { exp = bodyExpression(); } else { exp = getExpression().createExpression(routeContext); } return new SortProcessor<T>(exp, getComparator()); }
public static Predicate isInstanceOf(final Expression expression, final Class<?> type) { notNull(expression, "expression"); notNull(type, "type"); return new Predicate() { public boolean matches(Exchange exchange) { Object value = expression.evaluate(exchange, Object.class); return type.isInstance(value); } @Override public String toString() { return expression + " instanceof " + type.getCanonicalName(); } }; }
/** * Asserts that the expression evaluates to one of the two given values */ protected void assertExpression(String expressionText, String expectedValue, String orThisExpectedValue) { Language language = assertResolveLanguage(getLanguageName()); Expression expression = language.createExpression(expressionText); assertNotNull(expression, "No Expression could be created for text: " + expressionText + " language: " + language); Object value; if (expectedValue != null) { value = expression.evaluate(exchange, expectedValue.getClass()); } else { value = expression.evaluate(exchange, Object.class); } log.debug("Evaluated expression: " + expression + " on exchange: " + exchange + " result: " + value); assertTrue(expectedValue.equals(value) || orThisExpectedValue.equals(value), "Expression: " + expression + " on Exchange: " + exchange); }
public static Predicate isNotEqualTo(final Expression left, final Expression right) { return new BinaryPredicateSupport(left, right) { protected boolean matches(Exchange exchange, Object leftValue, Object rightValue) { if (leftValue == null && rightValue == null) { // they are equal return false; } else if (leftValue == null || rightValue == null) { // only one of them is null so they are not equal return true; } return ObjectHelper.typeCoerceNotEquals(exchange.getContext().getTypeConverter(), leftValue, rightValue); } protected String getOperationText() { return "!="; } }; }
/** * Creates a processor which sets the body of the FAULT message to the value of the expression */ public static Processor setFaultBody(final Expression expression) { return new Processor() { public void process(Exchange exchange) { Object newBody = expression.evaluate(exchange, Object.class); if (exchange.hasOut()) { exchange.getOut().setFault(true); exchange.getOut().setBody(newBody); } else { exchange.getIn().setFault(true); exchange.getIn().setBody(newBody); } } @Override public String toString() { return "setFaultBody(" + expression + ")"; } }; }
protected Expression createProducerExpression() { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { Object answer; // must have a body try { if (getEntityType() == null) { answer = exchange.getIn().getMandatoryBody(); } else { answer = exchange.getIn().getMandatoryBody(getEntityType()); } } catch (InvalidPayloadException e) { throw new InvalidPayloadRuntimeException(exchange, getEntityType(), e.getCause()); } // is never null return answer; } }; }
/** * Returns a random number between min and max */ public static Expression randomExpression(final String min, final String max) { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { int num1 = simpleExpression(min).evaluate(exchange, Integer.class); int num2 = simpleExpression(max).evaluate(exchange, Integer.class); Random random = new Random(); int randomNum = random.nextInt(num2 - num1) + num1; return randomNum; } @Override public String toString() { return "random"; } }; }
/** * Returns an expression for the header value with the given name * <p/> * Will fallback and look in properties if not found in headers. * * @param headerName the name of the header the expression will return * @return an expression object which will return the header value */ public static Expression headerExpression(final String headerName) { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { String name = simpleExpression(headerName).evaluate(exchange, String.class); Object header = exchange.getIn().getHeader(name); if (header == null) { // fall back on a property header = exchange.getProperty(name); } return header; } @Override public String toString() { return "header(" + headerName + ")"; } }; }
/** * Returns the expression for the out messages body */ public static Expression outBodyExpression() { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { if (exchange.hasOut()) { return exchange.getOut().getBody(); } else { return null; } } @Override public String toString() { return "outBody"; } }; }
public AggregateProcessor(CamelContext camelContext, Processor processor, Expression correlationExpression, AggregationStrategy aggregationStrategy, ExecutorService executorService, boolean shutdownExecutorService) { ObjectHelper.notNull(camelContext, "camelContext"); ObjectHelper.notNull(processor, "processor"); ObjectHelper.notNull(correlationExpression, "correlationExpression"); ObjectHelper.notNull(aggregationStrategy, "aggregationStrategy"); ObjectHelper.notNull(executorService, "executorService"); this.camelContext = camelContext; this.processor = processor; this.correlationExpression = correlationExpression; this.aggregationStrategy = aggregationStrategy; this.executorService = executorService; this.shutdownExecutorService = shutdownExecutorService; this.exceptionHandler = new LoggingExceptionHandler(camelContext, getClass()); }
@Override public Expression createExpression(CamelContext camelContext, Annotation annotation, LanguageAnnotation languageAnnotation, Class<?> expressionReturnType) { String expression = getExpressionFromAnnotation(annotation); JsonPathExpression answer = new JsonPathExpression(expression); if (expressionReturnType != null) { answer.setResultType(expressionReturnType); } if (annotation instanceof JsonPath) { JsonPath jsonPathAnnotation = (JsonPath) annotation; answer.setSuppressExceptions(jsonPathAnnotation.suppressExceptions()); Option[] options = jsonPathAnnotation.options(); answer.setOptions(options); } answer.init(); return answer; }
/** * Adds an expectation that the given body value are received by this endpoint */ public AssertionClause expectedBodyReceived() { expectedMessageCount(1); final AssertionClause clause = new AssertionClause(this) { public void run() { Exchange exchange = getReceivedExchange(0); assertTrue("No exchange received for counter: " + 0, exchange != null); Object actualBody = exchange.getIn().getBody(); Expression exp = createExpression(getCamelContext()); Object expectedBody = exp.evaluate(exchange, Object.class); assertEquals("Body of message: " + 0, expectedBody, actualBody); } }; expects(clause); return clause; }
/** * Returns the expression for the exchanges inbound message body converted * to the given type */ public static Expression bodyExpression(final String name) { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { String text = simpleExpression(name).evaluate(exchange, String.class); Class<?> type; try { type = exchange.getContext().getClassResolver().resolveMandatoryClass(text); } catch (ClassNotFoundException e) { throw ObjectHelper.wrapCamelExecutionException(exchange, e); } return exchange.getIn().getBody(type); } @Override public String toString() { return "bodyAs[" + name + "]"; } }; }
@Override public Optional<ProcessorDefinition> handle(Split step, ProcessorDefinition route, SyndesisRouteBuilder routeBuilder) { CamelContext context = routeBuilder.getContext(); Expression expression = JsonSimpleHelpers.getMandatoryExpression(context, step, step.getExpression()); ProcessorDefinition split = route.split(expression).marshal().json(JsonLibrary.Jackson); routeBuilder.addSteps(split, step.getSteps()); return Optional.empty(); }
public static Expression getMandatoryExpression(CamelContext context, Step step, String expression) { Objects.requireNonNull(expression, "No expression specified for step " + step); Language jsonpath = getLanguage(context); Expression answer = jsonpath.createExpression(expression); Objects.requireNonNull(answer, "No expression created from: " + expression); return answer; }
/** * Creates a consumer endpoint that splits up the List of Maps into exchanges of single * Maps, and within each exchange it converts each Map to JSON. */ @Override public Consumer createConsumer(final Processor processor) throws Exception { final ToJSONProcessor toJsonProcessor = new ToJSONProcessor(); Processor pipeline = Pipeline.newInstance(getCamelContext(), toJsonProcessor, processor); final Expression expression = ExpressionBuilder.bodyExpression(List.class); final Splitter splitter = new Splitter(getCamelContext(), expression, pipeline, null); return endpoint.createConsumer(splitter); }
@Override public ProcessorDefinition handle(Split step, ProcessorDefinition route, SyndesisRouteBuilder routeBuilder) { CamelContext context = routeBuilder.getContext(); Expression expression = JsonSimpleHelpers.getMandatoryExpression(context, step, step.getExpression()); ProcessorDefinition split = route.split(expression).marshal().json(JsonLibrary.Jackson); return routeBuilder.addSteps(split, step.getSteps()); }
protected Expression getMandatoryExpression(Step step, String expression, String language) { Objects.requireNonNull(expression, "No expression specified for step " + step); Language jsonpath = getLanguage(language); Expression answer = jsonpath.createExpression(expression); Objects.requireNonNull(answer, "No expression created from: " + expression); return answer; }
public void testLessThanOrEqual() throws Exception { // less than Expression a = ExpressionBuilder.constantExpression("100"); Expression b = ExpressionBuilder.constantExpression(Integer.valueOf("200")); assertMatches(PredicateBuilder.isLessThanOrEqualTo(a, b)); assertDoesNotMatch(PredicateBuilder.isLessThanOrEqualTo(b, a)); // reverse the types and try again a = ExpressionBuilder.constantExpression(Integer.valueOf("200")); b = ExpressionBuilder.constantExpression("100"); assertDoesNotMatch(PredicateBuilder.isLessThanOrEqualTo(a, b)); assertMatches(PredicateBuilder.isLessThanOrEqualTo(b, a)); // equal a = ExpressionBuilder.constantExpression("100"); b = ExpressionBuilder.constantExpression(Integer.valueOf("100")); assertMatches(PredicateBuilder.isLessThanOrEqualTo(a, b)); assertMatches(PredicateBuilder.isLessThanOrEqualTo(b, a)); // reverse the types and try again a = ExpressionBuilder.constantExpression(Integer.valueOf("100")); b = ExpressionBuilder.constantExpression("100"); assertMatches(PredicateBuilder.isGreaterThanOrEqualTo(a, b)); assertMatches(PredicateBuilder.isGreaterThanOrEqualTo(b, a)); }
@Override protected void preCreateProcessor() { Expression exp = expression; if (expression != null && expression.getExpressionValue() != null) { exp = expression.getExpressionValue(); } if (exp instanceof ExpressionClause) { ExpressionClause<?> clause = (ExpressionClause<?>) exp; if (clause.getExpressionType() != null) { // if using the Java DSL then the expression may have been set using the // ExpressionClause which is a fancy builder to define expressions and predicates // using fluent builders in the DSL. However we need afterwards a callback to // reset the expression to the expression type the ExpressionClause did build for us expression = clause.getExpressionType(); } } if (expression != null && expression.getExpression() == null) { // use toString from predicate or expression so we have some information to show in the route model if (expression.getPredicate() != null) { expression.setExpression(expression.getPredicate().toString()); } else if (expression.getExpressionValue() != null) { expression.setExpression(expression.getExpressionValue().toString()); } } }
/** * Uses sticky load balancer * * @param correlationExpression the expression for correlation * @return the builder */ public LoadBalanceDefinition sticky(Expression correlationExpression) { StickyLoadBalancerDefinition def = new StickyLoadBalancerDefinition(); def.setCorrelationExpression(correlationExpression); setLoadBalancerType(def); return this; }
private Expression createFileLanguageExpression(String expression) { Language language; // only use file language if the name is complex (eg. using $) if (expression.contains("$")) { language = getCamelContext().resolveLanguage("file"); } else { language = getCamelContext().resolveLanguage("constant"); } return language.createExpression(expression); }
/** * Returns the expression for the current thread name */ public static Expression threadNameExpression() { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { return Thread.currentThread().getName(); } @Override public String toString() { return "threadName"; } }; }
public void testTokenizeXMLPairNoData() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", null); exchange.getIn().setBody(""); List<?> names = exp.evaluate(exchange, List.class); assertEquals(0, names.size()); }
@Override public Processor createProcessor(RouteContext routeContext) throws Exception { Processor childProcessor = this.createChildProcessor(routeContext, true); aggregationStrategy = createAggregationStrategy(routeContext); boolean isParallelProcessing = getParallelProcessing() != null && getParallelProcessing(); boolean isStreaming = getStreaming() != null && getStreaming(); boolean isShareUnitOfWork = getShareUnitOfWork() != null && getShareUnitOfWork(); boolean isParallelAggregate = getParallelAggregate() != null && getParallelAggregate(); boolean shutdownThreadPool = ProcessorDefinitionHelper.willCreateNewThreadPool(routeContext, this, isParallelProcessing); ExecutorService threadPool = ProcessorDefinitionHelper.getConfiguredExecutorService(routeContext, "Split", this, isParallelProcessing); long timeout = getTimeout() != null ? getTimeout() : 0; if (timeout > 0 && !isParallelProcessing) { throw new IllegalArgumentException("Timeout is used but ParallelProcessing has not been enabled."); } if (onPrepareRef != null) { onPrepare = CamelContextHelper.mandatoryLookup(routeContext.getCamelContext(), onPrepareRef, Processor.class); } Expression exp = getExpression().createExpression(routeContext); Splitter answer = new Splitter(routeContext.getCamelContext(), exp, childProcessor, aggregationStrategy, isParallelProcessing, threadPool, shutdownThreadPool, isStreaming, isStopOnException(), timeout, onPrepare, isShareUnitOfWork, isParallelAggregate); return answer; }
public void testTokenize() throws Exception { Expression expression = tokenizeExpression(headerExpression("location"), ","); List<String> expected = new ArrayList<String>(Arrays.asList(new String[] {"Islington", "London", "UK"})); assertExpression(expression, exchange, expected); Predicate predicate = contains(tokenizeExpression(headerExpression("location"), ","), constantExpression("London")); assertPredicate(predicate, exchange, true); predicate = contains(tokenizeExpression(headerExpression("location"), ","), constantExpression("Manchester")); assertPredicate(predicate, exchange, false); }
public void testSimpleUnaryDec() throws Exception { exchange.getIn().setBody("122"); SimpleExpressionParser parser = new SimpleExpressionParser("${body}--", true); Expression exp = parser.parseExpression(); assertEquals("121", exp.evaluate(exchange, String.class)); }
public void testBeanTypeAndMethodExpression() throws Exception { Expression exp = BeanLanguage.bean(MyUser.class, "hello"); Exchange exchange = createExchangeWithBody("Claus"); Object result = exp.evaluate(exchange, Object.class); assertEquals("Hello Claus", result); }
public void testRegexTokenize() throws Exception { Expression expression = regexTokenizeExpression(headerExpression("location"), ","); List<String> expected = new ArrayList<String>(Arrays.asList(new String[] {"Islington", "London", "UK"})); assertExpression(expression, exchange, expected); Predicate predicate = contains(regexTokenizeExpression(headerExpression("location"), ","), constantExpression("London")); assertPredicate(predicate, exchange, true); predicate = contains(regexTokenizeExpression(headerExpression("location"), ","), constantExpression("Manchester")); assertPredicate(predicate, exchange, false); }
private Expression createIsExpression(final String expression, final Expression leftExp, final Expression rightExp) { return new Expression() { @Override public <T> T evaluate(Exchange exchange, Class<T> type) { Predicate predicate; String name = rightExp.evaluate(exchange, String.class); if (name == null || "null".equals(name)) { throw new SimpleIllegalSyntaxException(expression, right.getToken().getIndex(), operator + " operator cannot accept null. A class type must be provided."); } Class<?> rightType = exchange.getContext().getClassResolver().resolveClass(name); if (rightType == null) { throw new SimpleIllegalSyntaxException(expression, right.getToken().getIndex(), operator + " operator cannot find class with name: " + name); } predicate = PredicateBuilder.isInstanceOf(leftExp, rightType); if (operator == BinaryOperatorType.NOT_IS) { predicate = PredicateBuilder.not(predicate); } boolean answer = predicate.matches(exchange); return exchange.getContext().getTypeConverter().convertTo(type, answer); } @Override public String toString() { return left + " " + token.getText() + " " + right; } }; }
/** * Returns an expression for the {@link org.apache.camel.CamelContext} name * * @return an expression object which will return the camel context name */ public static Expression camelContextNameExpression() { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { return exchange.getContext().getName(); } @Override public String toString() { return "camelContextName"; } }; }
/** * Sets the property on the exchange */ public static Processor setProperty(final String name, final Expression expression) { return new Processor() { public void process(Exchange exchange) { Object value = expression.evaluate(exchange, Object.class); exchange.setProperty(name, value); } @Override public String toString() { return "setProperty(" + name + ", " + expression + ")"; } }; }
/** * Returns an expression for the property value of the camel context with the given name * * @param propertyName the name of the property the expression will return * @return an expression object which will return the property value */ public static Expression camelContextPropertyExpression(final String propertyName) { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { String text = simpleExpression(propertyName).evaluate(exchange, String.class); return exchange.getContext().getProperty(text); } @Override public String toString() { return "camelContextProperty(" + propertyName + ")"; } }; }
protected Expression doParseExpression() { // parse the expression using the following grammar nextToken(); while (!token.getType().isEol()) { // an expression supports just template (eg text), functions, or unary operator templateText(); functionText(); unaryOperator(); nextToken(); } // now after parsing we need a bit of work to do, to make it easier to turn the tokens // into and ast, and then from the ast, to Camel expression(s). // hence why there is a number of tasks going on below to accomplish this // turn the tokens into the ast model parseAndCreateAstModel(); // compact and stack blocks (eg function start/end) prepareBlocks(); // compact and stack unary operators prepareUnaryExpressions(); // create and return as a Camel expression List<Expression> expressions = createExpressions(); if (expressions.isEmpty()) { // return an empty string as response as there was nothing to parse return ExpressionBuilder.constantExpression(""); } else if (expressions.size() == 1) { return expressions.get(0); } else { // concat expressions as evaluating an expression is like a template language return ExpressionBuilder.concatExpression(expressions, expression); } }
/** * Returns the expression for the IN message */ public static Expression inMessageExpression() { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { return exchange.getIn(); } @Override public String toString() { return "inMessage"; } }; }
public void testNestedNestedFunctions() throws Exception { exchange.getIn().setBody("123"); exchange.getIn().setHeader("foo", "Integer"); exchange.getIn().setHeader("bar", "foo"); SimpleExpressionParser parser = new SimpleExpressionParser("${bodyAs(${header.${header.bar}})}", true); Expression exp = parser.parseExpression(); Object obj = exp.evaluate(exchange, Object.class); assertNotNull(obj); Integer num = assertIsInstanceOf(Integer.class, obj); assertEquals(123, num.intValue()); }
public static Predicate parsePredicate(String expression, boolean allowEscape) { Expression answer = doParseExpression(expression, allowEscape); if (answer != null) { return ExpressionToPredicateAdapter.toPredicate(answer); } else { return null; } }
/** * Returns the expression for the exchange invoking methods defined * in a simple OGNL notation * * @param ognl methods to invoke on the exchange in a simple OGNL syntax */ public static Expression exchangeOgnlExpression(final String ognl) { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { // ognl is able to evaluate method name if it contains nested functions // so we should not eager evaluate ognl as a string return new MethodCallExpression(exchange, ognl).evaluate(exchange); } @Override public String toString() { return "exchangeOgnl(" + ognl + ")"; } }; }
/** * Returns an expression for the inbound message attachments * * @return an expression object which will return the inbound message attachments */ public static Expression attachmentValuesExpression() { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { return exchange.getIn().getAttachments().values(); } @Override public String toString() { return "attachments"; } }; }