protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: e1 from("direct:a").routingSlip(header("myHeader")).to("mock:end"); // END SNIPPET: e1 // START SNIPPET: e2 from("direct:b").routingSlip(ExpressionBuilder.headerExpression("aRoutingSlipHeader")); // END SNIPPET: e2 // START SNIPPET: e3 from("direct:c").routingSlip(header("aRoutingSlipHeader"), "#"); // END SNIPPET: e3 // START SNIPPET: e4 from("direct:d").routingSlip(body()); // END SNIPPET: e4 } }; }
private void parseValueExpression(Token valueSrcToken) { if (SSPTParserConstants.SIMPLE_EXP_TOKEN == valueSrcToken.kind) { final Expression exp = ExpressionBuilder.simpleExpression(valueSrcToken.toString()); this.valueExtractor = new ValueExtractor() { @Override public Object eval(Exchange exchange, Object container) { return exp.evaluate(exchange, Object.class); } }; } else if (SSPTParserConstants.PARAMETER_POS_TOKEN == valueSrcToken.kind) { //remove leading :# final String mapKey = valueSrcToken.toString().substring(2); this.valueExtractor = new ValueExtractor() { @Override public Object eval(Exchange exchange, Object container) { return ((Map) container).get(mapKey); } }; } }
@Override public void store(@Body InputStream input, Exchange exchange) { FileOutputStream fos = null; try { String fileName = ExpressionBuilder.simpleExpression(fileNameExpression).evaluate(exchange,String.class); File outputFile = new File(baseDir,fileName); fos = new FileOutputStream(outputFile); IOUtils.copyLarge(input,fos); exchange.getIn().setHeader(MessageStore.MESSAGE_STORE_REF,outputFile.getAbsolutePath()); } catch (IOException e) { //throw this so it propergates back to the sender because if we can't persist message we shouldn't accept them throw new RuntimeException("currently unable to persist messages in message store " + e,e); } finally { IOUtils.closeQuietly(fos); } }
/** * 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 Processor createProcessor(RouteContext routeContext) throws Exception { ObjectHelper.notNull(headerName, "headerName"); Expression expr = getExpression().createExpression(routeContext); Expression nameExpr = ExpressionBuilder.parseSimpleOrFallbackToConstantExpression(getHeaderName(), routeContext.getCamelContext()); return new SetHeaderProcessor(nameExpr, expr); }
@Override public Processor createProcessor(RouteContext routeContext) throws Exception { ObjectHelper.notNull(getPropertyName(), "propertyName", this); Expression expr = getExpression().createExpression(routeContext); Expression nameExpr = ExpressionBuilder.parseSimpleOrFallbackToConstantExpression(getPropertyName(), routeContext.getCamelContext()); return new SetPropertyProcessor(nameExpr, expr); }
public boolean doRoutingSlip(Exchange exchange, Object routingSlip, AsyncCallback callback) { if (routingSlip instanceof Expression) { return doRoutingSlipWithExpression(exchange, (Expression) routingSlip, callback); } else { return doRoutingSlipWithExpression(exchange, ExpressionBuilder.constantExpression(routingSlip), callback); } }
private Expression createSimpleExpressionDirectly(String expression) { if (ObjectHelper.isEqualToAny(expression, "body", "in.body")) { return ExpressionBuilder.bodyExpression(); } else if (ObjectHelper.equal(expression, "out.body")) { return ExpressionBuilder.outBodyExpression(); } else if (ObjectHelper.equal(expression, "id")) { return ExpressionBuilder.messageIdExpression(); } else if (ObjectHelper.equal(expression, "exchangeId")) { return ExpressionBuilder.exchangeIdExpression(); } else if (ObjectHelper.equal(expression, "exchange")) { return ExpressionBuilder.exchangeExpression(); } else if (ObjectHelper.equal(expression, "exception")) { return ExpressionBuilder.exchangeExceptionExpression(); } else if (ObjectHelper.equal(expression, "exception.message")) { return ExpressionBuilder.exchangeExceptionMessageExpression(); } else if (ObjectHelper.equal(expression, "exception.stacktrace")) { return ExpressionBuilder.exchangeExceptionStackTraceExpression(); } else if (ObjectHelper.equal(expression, "threadName")) { return ExpressionBuilder.threadNameExpression(); } else if (ObjectHelper.equal(expression, "camelId")) { return ExpressionBuilder.camelContextNameExpression(); } else if (ObjectHelper.equal(expression, "routeId")) { return ExpressionBuilder.routeIdExpression(); } else if (ObjectHelper.equal(expression, "null")) { return ExpressionBuilder.nullExpression(); } return null; }
private Expression createSimpleFileExpression(String remainder, boolean strict) { if (ObjectHelper.equal(remainder, "name")) { return ExpressionBuilder.fileNameExpression(); } else if (ObjectHelper.equal(remainder, "name.noext")) { return ExpressionBuilder.fileNameNoExtensionExpression(); } else if (ObjectHelper.equal(remainder, "name.noext.single")) { return ExpressionBuilder.fileNameNoExtensionSingleExpression(); } else if (ObjectHelper.equal(remainder, "name.ext") || ObjectHelper.equal(remainder, "ext")) { return ExpressionBuilder.fileExtensionExpression(); } else if (ObjectHelper.equal(remainder, "name.ext.single")) { return ExpressionBuilder.fileExtensionSingleExpression(); } else if (ObjectHelper.equal(remainder, "onlyname")) { return ExpressionBuilder.fileOnlyNameExpression(); } else if (ObjectHelper.equal(remainder, "onlyname.noext")) { return ExpressionBuilder.fileOnlyNameNoExtensionExpression(); } else if (ObjectHelper.equal(remainder, "onlyname.noext.single")) { return ExpressionBuilder.fileOnlyNameNoExtensionSingleExpression(); } else if (ObjectHelper.equal(remainder, "parent")) { return ExpressionBuilder.fileParentExpression(); } else if (ObjectHelper.equal(remainder, "path")) { return ExpressionBuilder.filePathExpression(); } else if (ObjectHelper.equal(remainder, "absolute")) { return ExpressionBuilder.fileAbsoluteExpression(); } else if (ObjectHelper.equal(remainder, "absolute.path")) { return ExpressionBuilder.fileAbsolutePathExpression(); } else if (ObjectHelper.equal(remainder, "length") || ObjectHelper.equal(remainder, "size")) { return ExpressionBuilder.fileSizeExpression(); } else if (ObjectHelper.equal(remainder, "modified")) { return ExpressionBuilder.fileLastModifiedExpression(); } if (strict) { throw new SimpleParserException("Unknown file language syntax: " + remainder, token.getIndex()); } return null; }
@Override public Expression createExpression(String expression) { Expression answer = null; if (block != null) { answer = block.createExpression(expression); } if (answer == null) { // there quoted literal is empty answer = ExpressionBuilder.constantExpression(""); } return answer; }
@Override public Expression createExpression(String expression) { if (children.isEmpty()) { return null; } else if (children.size() == 1) { return children.get(0).createExpression(expression); } else { List<Expression> answer = new ArrayList<Expression>(); for (SimpleNode child : children) { answer.add(child.createExpression(expression)); } return ExpressionBuilder.concatExpression(answer); } }
private Expression createRangeExpression(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 range = rightExp.evaluate(exchange, String.class); Matcher matcher = RANGE_PATTERN.matcher(range); if (matcher.matches()) { // wrap as constant expression for the from and to values Expression from = ExpressionBuilder.constantExpression(matcher.group(1)); Expression to = ExpressionBuilder.constantExpression(matcher.group(3)); // build a compound predicate for the range predicate = PredicateBuilder.isGreaterThanOrEqualTo(leftExp, from); predicate = PredicateBuilder.and(predicate, PredicateBuilder.isLessThanOrEqualTo(leftExp, to)); } else { throw new SimpleIllegalSyntaxException(expression, right.getToken().getIndex(), operator + " operator is not valid. Valid syntax:'from..to' (where from and to are numbers)."); } if (operator == BinaryOperatorType.NOT_RANGE) { 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; } }; }
public Expression createExpression(String expression, Class<?> resultType) { if (resultType == Boolean.class || resultType == boolean.class) { // if its a boolean as result then its a predicate Predicate predicate = createPredicate(expression); return PredicateToExpressionAdapter.toExpression(predicate); } else { Expression exp = createExpression(expression); if (resultType != null) { exp = ExpressionBuilder.convertToExpression(exp, resultType); } return exp; } }
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); } }
/** * Creates a tokenize expression. */ public Expression createExpression() { ObjectHelper.notNull(path, "path"); Expression answer = ExpressionBuilder.tokenizeXMLAwareExpression(path, mode); return answer; }
public void loadDefaultRegistry() { addParameterMapping(Exchange.class, ExpressionBuilder.exchangeExpression()); addParameterMapping(Message.class, ExpressionBuilder.inMessageExpression()); addParameterMapping(Exception.class, ExpressionBuilder.exchangeExceptionExpression()); addParameterMapping(TypeConverter.class, ExpressionBuilder.typeConverterExpression()); addParameterMapping(Registry.class, ExpressionBuilder.registryExpression()); addParameterMapping(CamelContext.class, ExpressionBuilder.camelContextExpression()); }
public void testExpressionEvaluationException() { Expression exp = ExpressionBuilder.constantExpression("foo"); Exchange exchange = new DefaultExchange(context); ExpressionEvaluationException e = new ExpressionEvaluationException(exp, exchange, new IllegalArgumentException("Damn")); assertSame(exchange, e.getExchange()); assertSame(exp, e.getExpression()); assertNotNull(e.getCause()); }
@Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { onException(IllegalArgumentException.class).handled(true).to("mock:handled"); from("direct:start") .aggregate(header("id")) .completionTimeout(500) .aggregationStrategy(new AggregationStrategy() { public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { Object body = newExchange.getIn().getBody(); if ("Damn".equals(body)) { throw new IllegalArgumentException(); } return newExchange; } }) .to("mock:result"); from("direct:predicate") .aggregate(new Expression() { public <T> T evaluate(Exchange exchange, Class<T> type) { if (exchange.getIn().getBody().equals("Damn")) { throw new IllegalArgumentException(); } return ExpressionBuilder.headerExpression("id").evaluate(exchange, type); } }, new UseLatestAggregationStrategy()) .completionTimeout(500) .to("mock:result"); } }; }
@Override public void assertMessageExpected(DataSetEndpoint dataSetEndpoint, Exchange expected, Exchange actual, long index) throws Exception { // lets compare the XPath result Predicate predicate = PredicateBuilder.isEqualTo(expression, ExpressionBuilder.constantExpression(index)); log.debug("evaluating predicate: " + predicate); PredicateAssertHelper.assertMatches(predicate, "Actual: " + actual, actual); }
public void testExpectedBodyExpression() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived(987); // start with 0 (zero) to have it converted to the number and match 987 // and since its an expression it would be evaluated first as well template.sendBody("direct:a", ExpressionBuilder.constantExpression("0987")); assertMockEndpointsSatisfied(); }
@Test public void testSortedEntries() throws Exception { MockEndpoint mock = getMockEndpoint("mock:sorted"); mock.expectsAscending(ExpressionBuilder.beanExpression("myBean", "getPubDate")); mock.expectedMessageCount(10); mock.setResultWaitTime(15000L); mock.assertIsSatisfied(); }
@Test public void testUnSortedEntries() throws Exception { MockEndpoint mock = getMockEndpoint("mock:unsorted"); mock.expectsAscending(ExpressionBuilder.beanExpression("myBean", "getPubDate")); mock.expectedMessageCount(10); mock.setResultWaitTime(2000L); mock.assertIsNotSatisfied(2000L); }
@Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .choice() .when().jsonpath("$.store.book[?(@.price < 10)]") .to("mock:cheap") .when().jsonpath("$.store.book[?(@.price < 30)]") .to("mock:average") .otherwise() .to("mock:expensive"); from("direct:bicycle") .choice() .when().method(new BeanPredicate()) .to("mock:cheap") .otherwise() .to("mock:expensive"); from("direct:bicycle2") .choice() .when(PredicateBuilder.isLessThan(ExpressionBuilder.languageExpression("jsonpath", "$.store.bicycle.price"), ExpressionBuilder.constantExpression(20))) .to("mock:cheap") .otherwise() .to("mock:expensive"); } }; }
protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { port1 = getPort(); port2 = getNextPort(); errorHandler(noErrorHandler()); from("direct:gzip") .marshal().gzip() .setProperty(Exchange.SKIP_GZIP_ENCODING, ExpressionBuilder.constantExpression(Boolean.TRUE)) .to("http://localhost:" + port1 + "/gzip").unmarshal().gzip(); from("jetty:http://localhost:" + port1 + "/gzip").process(new Processor() { public void process(Exchange exchange) throws Exception { // check the request method HttpServletRequest request = exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST, HttpServletRequest.class); if ("POST".equals(request.getMethod())) { String requestBody = exchange.getIn().getBody(String.class); assertEquals("Get a wrong request string", "<Hello>World</Hello>", requestBody); } exchange.getOut().setHeader(Exchange.CONTENT_ENCODING, "gzip"); // check the Accept Encoding header String header = exchange.getIn().getHeader("Accept-Encoding", String.class); if (header != null && header.indexOf("gzip") > -1) { exchange.getOut().setBody("<b>Hello World for gzip</b>"); } else { exchange.getOut().setBody("<b>Hello World</b>"); } } }); from("jetty:http://localhost:" + port2 + "/route?bridgeEndpoint=true") .to("http://localhost:" + port1 + "/gzip?bridgeEndpoint=true"); } }; }
@Test public void canCreateConsumer() { String uri = "lb-file://" + rootDirectory + "?initialDelay=1s&delay=10s&priorityFileFilterFactory=#defaultPriorityFileFilterFactory&runLoggingLevel=INFO"; LogProcessor processor = new LogProcessor(ExpressionBuilder.simpleExpression("${body}"), new CamelLogger()); LoadBalancedFileEndpoint loadBalancedFileEndpoint = new LoadBalancedFileEndpoint(uri, new LoadBalancedFileComponent(context)); LoadBalancedFileConsumer consumer = new LoadBalancedFileConsumer(loadBalancedFileEndpoint, processor, new FileOperations()); Assert.assertNotNull(consumer); }
@Override protected RoutesBuilder[] createRouteBuilders() throws Exception { return new RoutesBuilder[] { new RetryingBatchFailedMessageRoute("direct:failure_batches", /*retryDelay:*/ ExpressionBuilder.constantExpression(10), /*maxRetryCount:*/ 5, /*processTimeout:*/ Duration.ofSeconds(5), "mock:direct:dlq"), new RetryingBatchFailedMessageRoute("direct:failure_batches_long_delay", /*retryDelay:*/ ExpressionBuilder.constantExpression(2000), /*maxRetryCount:*/ 5, /*processTimeout:*/ Duration.ofSeconds(5), "mock:direct:dlq"), }; }
public SetHeaderDefinition(String headerName, String value) { super(ExpressionBuilder.constantExpression(value)); setHeaderName(headerName); }
public SetPropertyDefinition(String propertyName, String value) { super(ExpressionBuilder.constantExpression(value)); setPropertyName(propertyName); }
public void constantDelay(Integer millis) { Expression delay = ExpressionBuilder.constantExpression(millis); delayer.setDelay(delay); }
public static Expression constant(Object value) { return ExpressionBuilder.constantExpression(value); }
public static Expression exchangeProperty(String propertyName) { return ExpressionBuilder.exchangePropertyExpression(propertyName); }
@Override public Expression createExpression(String expression) { return ExpressionBuilder.constantExpression(getText()); }
public static Expression header(String headerName) { return ExpressionBuilder.headerExpression(headerName); }
/** * Creates a tokenize expression. */ public Expression createExpression() { ObjectHelper.notNull(token, "token"); // validate some invalid combinations if (endToken != null && inheritNamespaceTagName != null) { throw new IllegalArgumentException("Cannot have both xml and pair tokenizer enabled."); } if (isXml() && (endToken != null || includeTokens)) { throw new IllegalArgumentException("Cannot have both xml and pair tokenizer enabled."); } Expression answer = null; if (isXml()) { answer = ExpressionBuilder.tokenizeXMLExpression(token, inheritNamespaceTagName); } else if (endToken != null) { answer = ExpressionBuilder.tokenizePairExpression(token, endToken, includeTokens); } if (answer == null) { // use the regular tokenizer Expression exp = headerName == null ? ExpressionBuilder.bodyExpression() : ExpressionBuilder.headerExpression(headerName); if (regex) { answer = ExpressionBuilder.regexTokenizeExpression(exp, token); } else { answer = ExpressionBuilder.tokenizeExpression(exp, token); } if (group == 0 && skipFirst) { // wrap in skip first (if group then it has its own skip first logic) answer = ExpressionBuilder.skipFirstExpression(answer); } } // if group then wrap answer in group expression if (group > 0) { if (isXml()) { answer = ExpressionBuilder.groupXmlIteratorExpression(answer, group); } else { answer = ExpressionBuilder.groupIteratorExpression(answer, token, group, skipFirst); } } return answer; }
protected MethodInfo createMethodInfo(Class<?> clazz, Method method) { Class<?>[] parameterTypes = method.getParameterTypes(); List<Annotation>[] parametersAnnotations = collectParameterAnnotations(clazz, method); List<ParameterInfo> parameters = new ArrayList<ParameterInfo>(); List<ParameterInfo> bodyParameters = new ArrayList<ParameterInfo>(); boolean hasCustomAnnotation = false; boolean hasHandlerAnnotation = ObjectHelper.hasAnnotation(method.getAnnotations(), Handler.class); int size = parameterTypes.length; if (LOG.isTraceEnabled()) { LOG.trace("Creating MethodInfo for class: {} method: {} having {} parameters", new Object[]{clazz, method, size}); } for (int i = 0; i < size; i++) { Class<?> parameterType = parameterTypes[i]; Annotation[] parameterAnnotations = parametersAnnotations[i].toArray(new Annotation[parametersAnnotations[i].size()]); Expression expression = createParameterUnmarshalExpression(clazz, method, parameterType, parameterAnnotations); hasCustomAnnotation |= expression != null; ParameterInfo parameterInfo = new ParameterInfo(i, parameterType, parameterAnnotations, expression); LOG.trace("Parameter #{}: {}", i, parameterInfo); parameters.add(parameterInfo); if (expression == null) { boolean bodyAnnotation = ObjectHelper.hasAnnotation(parameterAnnotations, Body.class); LOG.trace("Parameter #{} has @Body annotation", i); hasCustomAnnotation |= bodyAnnotation; if (bodyParameters.isEmpty()) { // okay we have not yet set the body parameter and we have found // the candidate now to use as body parameter if (Exchange.class.isAssignableFrom(parameterType)) { // use exchange expression = ExpressionBuilder.exchangeExpression(); } else { // assume it's the body and it must be mandatory convertible to the parameter type // but we allow null bodies in case the message really contains a null body expression = ExpressionBuilder.mandatoryBodyExpression(parameterType, true); } LOG.trace("Parameter #{} is the body parameter using expression {}", i, expression); parameterInfo.setExpression(expression); bodyParameters.add(parameterInfo); } else { // will ignore the expression for parameter evaluation } } LOG.trace("Parameter #{} has parameter info: ", i, parameterInfo); } // now let's add the method to the repository return new MethodInfo(camelContext, clazz, method, parameters, bodyParameters, hasCustomAnnotation, hasHandlerAnnotation); }
private MethodInfo chooseBestPossibleMethodInfo(Exchange exchange, Collection<MethodInfo> operationList, Object body, List<MethodInfo> possibles, List<MethodInfo> possiblesWithException, List<MethodInfo> possibleWithCustomAnnotation) throws AmbiguousMethodCallException { Exception exception = ExpressionBuilder.exchangeExceptionExpression().evaluate(exchange, Exception.class); if (exception != null && possiblesWithException.size() == 1) { LOG.trace("Exchange has exception set so we prefer method that also has exception as parameter"); // prefer the method that accepts exception in case we have an exception also return possiblesWithException.get(0); } else if (possibles.size() == 1) { return possibles.get(0); } else if (possibles.isEmpty()) { LOG.trace("No possible methods so now trying to convert body to parameter types"); // let's try converting Object newBody = null; MethodInfo matched = null; int matchCounter = 0; for (MethodInfo methodInfo : operationList) { if (methodInfo.getBodyParameterType() != null) { if (methodInfo.getBodyParameterType().isInstance(body)) { return methodInfo; } // we should only try to convert, as we are looking for best match Object value = exchange.getContext().getTypeConverter().tryConvertTo(methodInfo.getBodyParameterType(), exchange, body); if (value != null) { if (LOG.isTraceEnabled()) { LOG.trace("Converted body from: {} to: {}", body.getClass().getCanonicalName(), methodInfo.getBodyParameterType().getCanonicalName()); } matchCounter++; newBody = value; matched = methodInfo; } } } if (matchCounter > 1) { throw new AmbiguousMethodCallException(exchange, Arrays.asList(matched, matched)); } if (matched != null) { LOG.trace("Setting converted body: {}", body); Message in = exchange.getIn(); in.setBody(newBody); return matched; } } else { // if we only have a single method with custom annotations, let's use that one if (possibleWithCustomAnnotation.size() == 1) { MethodInfo answer = possibleWithCustomAnnotation.get(0); LOG.trace("There are only one method with annotations so we choose it: {}", answer); return answer; } // try to choose among multiple methods with annotations MethodInfo chosen = chooseMethodWithCustomAnnotations(exchange, possibles); if (chosen != null) { return chosen; } // just make sure the methods aren't all actually the same chosen = getSingleCovariantMethod(possibles); if (chosen != null) { return chosen; } throw new AmbiguousMethodCallException(exchange, possibles); } // cannot find a good method to use return null; }
@Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry jndi = super.createRegistry(); jndi.bind("myExpression", ExpressionBuilder.bodyExpression()); return jndi; }