@Override public Optional<ProcessorDefinition> handle(Choice step, ProcessorDefinition route, SyndesisRouteBuilder routeBuilder) { final CamelContext context = routeBuilder.getContext(); final ChoiceDefinition choice = route.choice(); List<Filter> filters = ObjectHelper.supplyIfEmpty(step.getFilters(), Collections::<Filter>emptyList); for (Filter filter : filters) { Predicate predicate = JsonSimpleHelpers.getMandatorySimplePredicate(context, filter, filter.getExpression()); ChoiceDefinition when = choice.when(predicate); routeBuilder.addSteps(when, filter.getSteps()); } Otherwise otherwiseStep = step.getOtherwise(); if (otherwiseStep != null) { List<Step> otherwiseSteps = ObjectHelper.supplyIfEmpty(otherwiseStep.getSteps(), Collections::<Step>emptyList); if (!otherwiseSteps.isEmpty()) { routeBuilder.addSteps(choice.otherwise(), otherwiseSteps); } } return Optional.empty(); }
@Override public ProcessorDefinition handle(Choice step, ProcessorDefinition route, SyndesisRouteBuilder routeBuilder) { final CamelContext context = routeBuilder.getContext(); final ChoiceDefinition choice = route.choice(); List<Filter> filters = ObjectHelper.supplyIfEmpty(step.getFilters(), Collections::emptyList); for (Filter filter : filters) { Predicate predicate = JsonSimpleHelpers.getMandatorySimplePredicate(context, filter, filter.getExpression()); ChoiceDefinition when = choice.when(predicate); route = routeBuilder.addSteps(when, filter.getSteps()); } Otherwise otherwiseStep = step.getOtherwise(); if (otherwiseStep != null) { List<Step> otherwiseSteps = ObjectHelper.supplyIfEmpty(otherwiseStep.getSteps(), Collections::emptyList); if (!otherwiseSteps.isEmpty()) { route = routeBuilder.addSteps(choice.otherwise(), otherwiseSteps); } } return route; }
@Override public void configure() throws Exception { // you can define the endpoints and predicates here // it is more common to inline the endpoints and predicates in the route // as shown in the CreateOrderRoute Endpoint newOrder = endpoint("activemq:queue:newOrder"); Predicate isWidget = xpath("/order/product = 'widget'"); Endpoint widget = endpoint("activemq:queue:widget"); Endpoint gadget = endpoint("activemq:queue:gadget"); from(newOrder) .choice() .when(isWidget) .to("log:widget") // add a log so we can see this happening in the shell .to(widget) .otherwise() .to("log:gadget") // add a log so we can see this happening in the shell .to(gadget); }
public void testSimpleExpressionOrPredicate() throws Exception { Predicate predicate = SimpleLanguage.predicate("${header.bar} == 123"); assertTrue(predicate.matches(exchange)); predicate = SimpleLanguage.predicate("${header.bar} == 124"); assertFalse(predicate.matches(exchange)); Expression expression = SimpleLanguage.expression("${body}"); assertEquals("<hello id='m123'>world!</hello>", expression.evaluate(exchange, String.class)); expression = SimpleLanguage.simple("${body}"); assertEquals("<hello id='m123'>world!</hello>", expression.evaluate(exchange, String.class)); expression = SimpleLanguage.simple("${body}", String.class); assertEquals("<hello id='m123'>world!</hello>", expression.evaluate(exchange, String.class)); expression = SimpleLanguage.simple("${header.bar} == 123", boolean.class); assertEquals(Boolean.TRUE, expression.evaluate(exchange, Object.class)); expression = SimpleLanguage.simple("${header.bar} == 124", boolean.class); assertEquals(Boolean.FALSE, expression.evaluate(exchange, Object.class)); expression = SimpleLanguage.simple("${header.bar} == 123", Boolean.class); assertEquals(Boolean.TRUE, expression.evaluate(exchange, Object.class)); expression = SimpleLanguage.simple("${header.bar} == 124", Boolean.class); assertEquals(Boolean.FALSE, expression.evaluate(exchange, Object.class)); }
public static Predicate contains(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 true; } else if (leftValue == null || rightValue == null) { // only one of them is null so they are not equal return false; } return ObjectHelper.contains(leftValue, rightValue); } protected String getOperationText() { return "contains"; } }; }
public void testOrSignatures() throws Exception { Predicate p1 = header("name").isEqualTo(constant("does-not-apply")); Predicate p2 = header("size").isGreaterThanOrEqualTo(constant(10)); Predicate p3 = header("location").contains(constant("does-not-apply")); // check method signature with two parameters assertMatches(PredicateBuilder.or(p1, p2)); assertMatches(PredicateBuilder.or(p2, p3)); // check method signature with varargs assertMatches(PredicateBuilder.in(p1, p2, p3)); assertMatches(PredicateBuilder.or(p1, p2, p3)); // maybe a list of predicates? assertMatches(PredicateBuilder.in(Arrays.asList(p1, p2, p3))); assertMatches(PredicateBuilder.or(Arrays.asList(p1, p2, p3))); }
public static Predicate startsWith(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 true; } else if (leftValue == null || rightValue == null) { // only one of them is null so they are not equal return false; } String leftStr = exchange.getContext().getTypeConverter().convertTo(String.class, leftValue); String rightStr = exchange.getContext().getTypeConverter().convertTo(String.class, rightValue); if (leftStr != null && rightStr != null) { return leftStr.startsWith(rightStr); } else { return false; } } protected String getOperationText() { return "startsWith"; } }; }
public static Predicate isEqualToIgnoreCase(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 true; } else if (leftValue == null || rightValue == null) { // only one of them is null so they are not equal return false; } return ObjectHelper.typeCoerceEquals(exchange.getContext().getTypeConverter(), leftValue, rightValue, true); } protected String getOperationText() { return "=~"; } }; }
@Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { Predicate goodWord = body().contains("World"); from("direct:start") .to("mock:before") .filter(goodWord) .to("mock:good") .end() .split(body().tokenize(" "), new MyAggregationStrategy()) .to("mock:split") .end() .to("mock:result"); } }; }
@Test @Ignore("Testing behind nat produces timeouts") public void testDNSWithNameHeaderAndType() throws Exception { resultEndpoint.expectedMessageCount(1); resultEndpoint.expectedMessagesMatches(new Predicate() { public boolean matches(Exchange exchange) { Record[] record = (Record[]) exchange.getIn().getBody(); return record[0].getName().toString().equals("www.example.com."); } }); Map<String, Object> headers = new HashMap<String, Object>(); headers.put("dns.name", "www.example.com"); headers.put("dns.type", "A"); template.sendBodyAndHeaders("hello", headers); resultEndpoint.assertIsSatisfied(); }
@Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { Predicate goodWord = body().contains("World"); from("direct:start") .filter(goodWord) .to("mock:filtered") .aggregate(header("id"), new MyAggregationStrategy()).completionTimeout(1000) .to("mock:result") .end() .end(); } }; }
@Override public Optional<ProcessorDefinition> handle(Filter step, ProcessorDefinition route, SyndesisRouteBuilder routeBuilder) { CamelContext context = routeBuilder.getContext(); Predicate predicate = JsonSimpleHelpers.getMandatorySimplePredicate(context, step, step.getExpression()); FilterDefinition filter = route.filter(predicate); routeBuilder.addSteps(filter, step.getSteps()); return Optional.empty(); }
@Override public ProcessorDefinition handle(Filter step, ProcessorDefinition route, SyndesisRouteBuilder routeBuilder) { CamelContext context = routeBuilder.getContext(); Predicate predicate = JsonSimpleHelpers.getMandatorySimplePredicate(context, step, step.getExpression()); FilterDefinition filter = route.filter(predicate); return routeBuilder.addSteps(filter, step.getSteps()); }
@Test @Ignore("Testing behind nat produces timeouts") public void testDNSWithNameHeader() throws Exception { resultEndpoint.expectedMessageCount(1); resultEndpoint.expectedMessagesMatches(new Predicate() { public boolean matches(Exchange exchange) { Record[] record = (Record[]) exchange.getIn().getBody(); return record[0].getName().toString().equals("www.example.com."); } }); Map<String, Object> headers = new HashMap<String, Object>(); headers.put("dns.name", "www.example.com"); template.sendBodyAndHeaders("hello", headers); resultEndpoint.assertIsSatisfied(); }
public void testSimpleEqFunctionFunction() throws Exception { exchange.getIn().setBody(122); exchange.getIn().setHeader("val", 122); SimplePredicateParser parser = new SimplePredicateParser("${body} == ${header.val}", true); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); }
public void testSimpleUnaryInc() throws Exception { exchange.getIn().setBody(122); SimplePredicateParser parser = new SimplePredicateParser("${body}++ == 123", true); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); }
public void testSimpleEq() throws Exception { exchange.getIn().setBody("foo"); SimplePredicateParser parser = new SimplePredicateParser("${body} == 'foo'", true); Predicate pre = parser.parsePredicate(); assertTrue(pre.matches(exchange)); }
/** * Adds an expectation that messages received should have the given exchange pattern */ public void expectedExchangePattern(final ExchangePattern exchangePattern) { expectedMessagesMatches(new Predicate() { public boolean matches(Exchange exchange) { return exchange.getPattern().equals(exchangePattern); } }); }
@Override public CatchProcessor createProcessor(RouteContext routeContext) throws Exception { // create and load exceptions if not done if (exceptionClasses == null) { exceptionClasses = createExceptionClasses(routeContext.getCamelContext()); } // must have at least one exception if (exceptionClasses.isEmpty()) { throw new IllegalArgumentException("At least one Exception must be configured to catch"); } // parent must be a try if (!(getParent() instanceof TryDefinition)) { throw new IllegalArgumentException("This doCatch should have a doTry as its parent on " + this); } // do catch does not mandate a child processor Processor childProcessor = this.createChildProcessor(routeContext, false); Predicate when = null; if (onWhen != null) { when = onWhen.getExpression().createPredicate(routeContext); } Predicate handle = handledPolicy; if (handled != null) { handle = handled.createPredicate(routeContext); } return new CatchProcessor(exceptionClasses, childProcessor, when, handle); }
/** * Performs any assertions on the given exchange */ protected void applyAssertionOn(MockEndpoint endpoint, int index, Exchange exchange) { for (Predicate predicate : predicates) { currentIndex = index; PredicateAssertHelper.assertMatches(predicate, "Assertion error at index " + index + " on mock " + endpoint.getEndpointUri() + " with predicate: ", exchange); } }
@Test @Ignore("Testing behind nat produces timeouts") public void testWikipediaForMonkey() throws Exception { resultEndpoint.expectedMessageCount(1); resultEndpoint.expectedMessagesMatches(new Predicate() { public boolean matches(Exchange exchange) { String str = (String) exchange.getIn().getBody(); return RESPONSE_MONKEY.equals(str); } }); Map<String, Object> headers = new HashMap<String, Object>(); headers.put("term", "monkey"); template.sendBodyAndHeaders(null, headers); resultEndpoint.assertIsSatisfied(); }
protected void testStatsConsumer(String mockEnpoint, String expectedPath, final Class<?> expectedType) throws Exception { MockEndpoint mock = getMockEndpoint(mockEnpoint); mock.expectedMinimumMessageCount(1); mock.expectedHeaderReceived(EtcdConstants.ETCD_NAMESPACE, EtcdNamespace.stats.name()); mock.expectedHeaderReceived(EtcdConstants.ETCD_PATH, expectedPath); mock.expectedMessagesMatches(new Predicate() { @Override public boolean matches(Exchange exchange) { return exchange.getIn().getBody().getClass() == expectedType; } }); assertMockEndpointsSatisfied(); }
@Override public Predicate createPredicate(String predicate) { Language language = new ScriptLanguageResolver().resolveLanguage("jruby", getCamelContext()); if (language != null) { return language.createPredicate(predicate); } else { return null; } }
public void testSimpleEqNumeric() throws Exception { exchange.getIn().setBody(123); SimplePredicateParser parser = new SimplePredicateParser("${body} == 123", true); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); }
public void testAggregateIgnoreInvalidCorrelationKey() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("A+C+END"); Processor done = new SendProcessor(context.getEndpoint("mock:result")); Expression corr = header("id"); AggregationStrategy as = new BodyInAggregatingStrategy(); Predicate complete = body().contains("END"); AggregateProcessor ap = new AggregateProcessor(context, done, corr, as, executorService, true); ap.setCompletionPredicate(complete); ap.setIgnoreInvalidCorrelationKeys(true); ap.start(); Exchange e1 = new DefaultExchange(context); e1.getIn().setBody("A"); e1.getIn().setHeader("id", 123); Exchange e2 = new DefaultExchange(context); e2.getIn().setBody("B"); Exchange e3 = new DefaultExchange(context); e3.getIn().setBody("C"); e3.getIn().setHeader("id", 123); Exchange e4 = new DefaultExchange(context); e4.getIn().setBody("END"); e4.getIn().setHeader("id", 123); ap.process(e1); ap.process(e2); ap.process(e3); ap.process(e4); assertMockEndpointsSatisfied(); ap.stop(); }
@Override public Predicate createPredicate(String predicate) { Language language = new ScriptLanguageResolver().resolveLanguage("php", getCamelContext()); if (language != null) { return language.createPredicate(predicate); } else { return null; } }
@Override protected void configurePredicate(CamelContext camelContext, Predicate predicate) { if (lenient != null) { setProperty(predicate, "lenient", lenient); } super.configurePredicate(camelContext, predicate); }
public void testCompoundAndPredicatesVarargs() throws Exception { Predicate p1 = header("name").isEqualTo(constant("James")); Predicate p2 = header("size").isGreaterThanOrEqualTo(constant(10)); Predicate p3 = header("location").contains(constant("London")); Predicate and = PredicateBuilder.and(p1, p2, p3); assertMatches(and); }
public static Expression fromCamelContext(final String contextName) { return new PredicateToExpressionAdapter(new Predicate() { @Override public boolean matches(Exchange exchange) { return exchange.getContext().getName().equals(contextName); } }); }
public void testSimpleUnaryDec() throws Exception { exchange.getIn().setBody(122); SimplePredicateParser parser = new SimplePredicateParser("${body}-- == 121", true); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); }
@Override public Predicate createPredicate(CamelContext camelContext) { if (documentType == null && documentTypeName != null) { try { documentType = camelContext.getClassResolver().resolveMandatoryClass(documentTypeName); } catch (ClassNotFoundException e) { throw ObjectHelper.wrapRuntimeCamelException(e); } } resolveXPathFactory(camelContext); return super.createPredicate(camelContext); }
@Override protected void configurePredicate(CamelContext camelContext, Predicate predicate) { boolean isSaxon = getSaxon() != null && getSaxon(); boolean isLogNamespaces = getLogNamespaces() != null && getLogNamespaces(); if (documentType != null) { setProperty(predicate, "documentType", documentType); } if (resultType != null) { setProperty(predicate, "resultType", resultType); } if (isSaxon) { ObjectHelper.cast(XPathBuilder.class, predicate).enableSaxon(); } if (xpathFactory != null) { setProperty(predicate, "xPathFactory", xpathFactory); } if (objectModel != null) { setProperty(predicate, "objectModelUri", objectModel); } if (isLogNamespaces) { ObjectHelper.cast(XPathBuilder.class, predicate).setLogNamespaces(true); } if (ObjectHelper.isNotEmpty(getHeaderName())) { ObjectHelper.cast(XPathBuilder.class, predicate).setHeaderName(getHeaderName()); } // moved the super configuration to the bottom so that the namespace init picks up the newly set XPath Factory super.configurePredicate(camelContext, predicate); }
/** * Concat the given predicates into a single predicate, which matches * if at least one predicates matches. * * @param predicates predicates * @return a single predicate containing all the predicates */ public static Predicate or(List<Predicate> predicates) { Predicate answer = null; for (Predicate predicate : predicates) { if (answer == null) { answer = predicate; } else { answer = or(answer, predicate); } } return answer; }
public void testAggregateProcessorCompletionPredicateEager() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("A+B+END"); mock.expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, "predicate"); Processor done = new SendProcessor(context.getEndpoint("mock:result")); Expression corr = header("id"); AggregationStrategy as = new BodyInAggregatingStrategy(); Predicate complete = body().isEqualTo("END"); AggregateProcessor ap = new AggregateProcessor(context, done, corr, as, executorService, true); ap.setCompletionPredicate(complete); ap.setEagerCheckCompletion(true); ap.start(); Exchange e1 = new DefaultExchange(context); e1.getIn().setBody("A"); e1.getIn().setHeader("id", 123); Exchange e2 = new DefaultExchange(context); e2.getIn().setBody("B"); e2.getIn().setHeader("id", 123); Exchange e3 = new DefaultExchange(context); e3.getIn().setBody("END"); e3.getIn().setHeader("id", 123); Exchange e4 = new DefaultExchange(context); e4.getIn().setBody("D"); e4.getIn().setHeader("id", 123); ap.process(e1); ap.process(e2); ap.process(e3); ap.process(e4); assertMockEndpointsSatisfied(); ap.stop(); }
public Predicate in(Object... values) { List<Predicate> predicates = new ArrayList<Predicate>(); for (Object value : values) { Expression right = asExpression(value); right = ExpressionBuilder.convertToExpression(right, expression); Predicate predicate = onNewPredicate(PredicateBuilder.isEqualTo(expression, right)); predicates.add(predicate); } return in(predicates.toArray(new Predicate[predicates.size()])); }
@Override public Predicate createPredicate(String predicate) { Language language = new ScriptLanguageResolver().resolveLanguage("python", getCamelContext()); if (language != null) { return language.createPredicate(predicate); } else { return null; } }
@Override public Processor createProcessor(RouteContext routeContext) throws Exception { Processor output = this.createChildProcessor(routeContext, true); boolean isCopy = getCopy() != null && getCopy(); boolean isWhile = getDoWhile() != null && getDoWhile(); Predicate predicate = null; Expression expression = null; if (isWhile) { predicate = getExpression().createPredicate(routeContext); } else { expression = getExpression().createExpression(routeContext); } return new LoopProcessor(output, expression, predicate, isCopy); }
@Test public void testGet() throws Exception { final Map<String, Object> headers = new HashMap<>(); final Cache<Object, Object> cache = getCacheFromEndpoint("jcache://test-cache"); final String key = randomString(); final String val = randomString(); cache.put(key, val); headers.clear(); headers.put(JCacheConstants.ACTION, "GET"); headers.put(JCacheConstants.KEY, key); sendBody("direct:get", null, headers); MockEndpoint mock = getMockEndpoint("mock:get"); mock.expectedMinimumMessageCount(1); mock.expectedHeaderReceived(JCacheConstants.KEY, key); mock.expectedMessagesMatches(new Predicate() { @Override public boolean matches(Exchange exchange) { assertNotNull("body", exchange.getIn().getBody()); return exchange.getIn().getBody().equals(val); } }); mock.assertIsSatisfied(); }
/** * A strategy method to allow derived classes to deal with the newly created * predicate in different ways */ protected Predicate onNewPredicate(Predicate predicate) { if (not) { return PredicateBuilder.not(predicate); } else { return predicate; } }
public void testSimpleLogicalAnd() throws Exception { exchange.getIn().setBody("Hello"); exchange.getIn().setHeader("high", true); exchange.getIn().setHeader("foo", 123); SimplePredicateParser parser = new SimplePredicateParser("${header.high} == true and ${header.foo} == 123", true); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); }