public Expression createExpression(CamelContext camelContext) { if (getExpressionValue() == null) { if (getExpressionType() != null) { setExpressionValue(getExpressionType().createExpression(camelContext)); } else if (getExpression() != null) { ObjectHelper.notNull("language", getLanguage()); Language language = camelContext.resolveLanguage(getLanguage()); if (language == null) { throw new NoSuchLanguageException(getLanguage()); } String exp = getExpression(); // should be true by default boolean isTrim = getTrim() == null || getTrim(); // trim if configured to trim if (exp != null && isTrim) { exp = exp.trim(); } // resolve the expression as it may be an external script from the classpath/file etc exp = ResourceHelper.resolveOptionalExternalScript(camelContext, exp); setExpressionValue(language.createExpression(exp)); configureExpression(camelContext, getExpressionValue()); } } return getExpressionValue(); }
public static Expression simpleExpression(final String expression) { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { if (SimpleLanguage.hasSimpleFunction(expression)) { // resolve language using context to have a clear separation of packages // must call evaluate to return the nested language evaluate when evaluating // stacked expressions Language language = exchange.getContext().resolveLanguage("simple"); return language.createExpression(expression).evaluate(exchange, Object.class); } else { return expression; } } @Override public String toString() { return "simple(" + expression + ")"; } }; }
public static Expression beanExpression(final String expression) { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { // bean is able to evaluate method name if it contains nested functions // so we should not eager evaluate expression as a string // resolve language using context to have a clear separation of packages // must call evaluate to return the nested language evaluate when evaluating // stacked expressions Language language = exchange.getContext().resolveLanguage("bean"); return language.createExpression(expression).evaluate(exchange, Object.class); } @Override public String toString() { return "bean(" + expression + ")"; } }; }
private XPathFunction createSimpleFunction() { return new XPathFunction() { @SuppressWarnings("rawtypes") public Object evaluate(List list) throws XPathFunctionException { if (!list.isEmpty()) { Object value = list.get(0); if (value != null) { String text = exchange.get().getContext().getTypeConverter().convertTo(String.class, value); Language simple = exchange.get().getContext().resolveLanguage("simple"); Expression exp = simple.createExpression(text); Object answer = exp.evaluate(exchange.get(), Object.class); return answer; } } return null; } }; }
/** * Evaluates the expression */ protected Object evaluateExpression(String expressionText, String expectedValue) { Language language = assertResolveLanguage(getLanguageName()); Expression expression = language.createExpression(expressionText); assertNotNull("No Expression could be created for text: " + expressionText + " language: " + language, expression); 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); return value; }
/** * 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("No Expression could be created for text: " + expressionText + " language: " + language, expression); 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("Expression: " + expression + " on Exchange: " + exchange, expectedValue.equals(value) || orThisExpectedValue.equals(value)); }
public Language resolveLanguage(String name, CamelContext context) { // lookup in registry first Object bean = null; try { bean = context.getRegistry().lookupByName(name); if (bean != null) { LOG.debug("Found language: {} in registry: {}", name, bean); } } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Ignored error looking up bean: " + name + ". Error: " + e); } } if (bean instanceof Language) { return (Language)bean; } Language lang = getLanguage(name, context); if (lang != null) { return lang; } LanguageResolver resolver = getLanguageResolver("default", context); if (resolver != null) { return resolver.resolveLanguage(name, context); } throw new NoSuchLanguageException(name); }
protected Language getLanguage(String name, CamelContext context) { LOG.trace("Finding Language: {}", name); try { ServiceReference<?>[] refs = bundleContext.getServiceReferences(LanguageResolver.class.getName(), "(language=" + name + ")"); if (refs != null) { for (ServiceReference<?> ref : refs) { Object service = bundleContext.getService(ref); if (LanguageResolver.class.isAssignableFrom(service.getClass())) { LanguageResolver resolver = (LanguageResolver) service; return resolver.resolveLanguage(name, context); } } } return null; } catch (InvalidSyntaxException e) { throw ObjectHelper.wrapRuntimeCamelException(e); } }
/** * 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); }
@Test public void testExpressionArray() throws Exception { Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(new File("src/test/resources/books.json")); Language lan = context.resolveLanguage("jsonpath"); Expression exp = lan.createExpression("$.store.book[*].author"); List<?> authors = exp.evaluate(exchange, List.class); log.debug("Authors {}", authors); assertNotNull(authors); assertEquals(2, authors.size()); assertEquals("Nigel Rees", authors.get(0)); assertEquals("Evelyn Waugh", authors.get(1)); exp = lan.createExpression("$.store.bicycle.price"); String price = exp.evaluate(exchange, String.class); assertEquals("Got a wrong result", "19.95", price); }
@Test public void testExpressionField() throws Exception { Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(new File("src/test/resources/type.json")); Language lan = context.resolveLanguage("jsonpath"); Expression exp = lan.createExpression("$.kind"); String kind = exp.evaluate(exchange, String.class); assertNotNull(kind); assertEquals("full", kind); exp = lan.createExpression("$.type"); String type = exp.evaluate(exchange, String.class); assertNotNull(type); assertEquals("customer", type); }
@Test public void testExpressionListAuthor() throws Exception { Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(new File("src/test/resources/authors.rdf")); exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/turtle"); exchange.getIn().setHeader("LDPATH_CONTEXT", "http://localhost/foo"); Language lan = context.resolveLanguage("ldpath"); Expression exp = lan.createExpression("author = dc:author :: xsd:string ;"); Map<String, Collection<String>> results = exp.evaluate(exchange, Map.class); assertNotNull(results); assertEquals(1, results.size()); ArrayList<String> authors = new ArrayList<>(results.get("author")); assertNotNull(authors); assertEquals(1, authors.size()); assertEquals("Aaron Coburn", authors.get(0)); }
@Test public void testExpressionListTitle() throws Exception { Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(new File("src/test/resources/indexable.rdf")); exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/turtle"); exchange.getIn().setHeader("LDPATH_CONTEXT", "http://localhost/foo"); Language lan = context.resolveLanguage("ldpath"); Expression exp = lan.createExpression("title = dc:title :: xsd:string ;"); Map<String,Collection<String>> results = exp.evaluate(exchange, Map.class); assertNotNull(results); assertEquals(1, results.size()); ArrayList<String> titles = new ArrayList<>(results.get("title")); assertNotNull(titles); assertEquals(1, titles.size()); assertEquals("Indexable Object", titles.get(0)); }
@Test public void testExpressionListMultiple() throws Exception { Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(new File("src/test/resources/indexable.rdf")); exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/turtle"); exchange.getIn().setHeader("LDPATH_CONTEXT", "http://localhost/foo"); Language lan = context.resolveLanguage("ldpath"); Expression exp = lan.createExpression("title = dc:title :: xsd:string ;\n author = dc:author :: xsd:string ;"); Map<String,Collection<String>> results = exp.evaluate(exchange, Map.class); assertNotNull(results); assertEquals(2, results.size()); ArrayList<String> titles = new ArrayList<>(results.get("title")); assertNotNull(titles); assertEquals(1, titles.size()); assertEquals("Indexable Object", titles.get(0)); }
@Test public void testExpressionList4() throws Exception { Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(new File("src/test/resources/indexable.rdf")); exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/turtle"); exchange.getIn().setHeader("LDPATH_CONTEXT", "http://localhost/foo"); Language lan = context.resolveLanguage("ldpath"); Expression exp = lan.createExpression("title = dc:title :: xsd:string ;"); Map<String,Collection<String>> results = exp.evaluate(exchange, Map.class); assertNotNull(results); assertEquals(1, results.size()); ArrayList<String> titles = new ArrayList<>(results.get("title")); assertNotNull(titles); assertEquals(1, titles.size()); assertEquals("Indexable Object", titles.get(0)); }
@Test public void testGroupedExpression() throws Exception { Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(new File("src/test/resources/indexable.rdf")); exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/turtle"); exchange.getIn().setHeader("LDPATH_CONTEXT", "http://localhost/foo"); Language lan = context.resolveLanguage("ldpath"); Expression exp = lan.createExpression("all = dc:title | dc:author :: xsd:string ;"); Map<String,Collection<String>> results = exp.evaluate(exchange, Map.class); assertNotNull(results); assertEquals(1, results.size()); ArrayList<String> all = new ArrayList<>(results.get("all")); assertNotNull(all); assertEquals(2, all.size()); }
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; }
protected Predicate getMandatoryPredicate(Step step, String expression, String language) { Objects.requireNonNull(expression, "No expression specified for step " + step); Language jsonpath = getLanguage(language); Predicate answer = jsonpath.createPredicate(expression); Objects.requireNonNull(answer, "No predicate created from: " + expression); return answer; }
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; }
protected Language getLanguage(String language) { // use jsonpath as default String languageName = language != null && !language.isEmpty() ? language : "jsonpath"; Language answer = getContext().resolveLanguage(languageName); Objects.requireNonNull(answer, "The language `" + languageName + "` cound not be resolved!"); return answer; }
public Predicate createPredicate(CamelContext camelContext) { if (predicate == null) { if (getExpressionType() != null) { predicate = getExpressionType().createPredicate(camelContext); } else if (getExpressionValue() != null) { predicate = new ExpressionToPredicateAdapter(getExpressionValue()); } else if (getExpression() != null) { ObjectHelper.notNull("language", getLanguage()); Language language = camelContext.resolveLanguage(getLanguage()); if (language == null) { throw new NoSuchLanguageException(getLanguage()); } String exp = getExpression(); // should be true by default boolean isTrim = getTrim() == null || getTrim(); // trim if configured to trim if (exp != null && isTrim) { exp = exp.trim(); } // resolve the expression as it may be an external script from the classpath/file etc exp = ResourceHelper.resolveOptionalExternalScript(camelContext, exp); predicate = language.createPredicate(exp); configurePredicate(camelContext, predicate); } } return predicate; }
public String validateConditionalBreakpoint(String language, String predicate) { Language lan = null; try { lan = camelContext.resolveLanguage(language); lan.createPredicate(predicate); return null; } catch (Exception e) { if (lan == null) { return e.getMessage(); } else { return "Invalid syntax " + predicate + " due: " + e.getMessage(); } } }
public Language resolveLanguage(String language) { Language answer; synchronized (languages) { answer = languages.get(language); // check if the language is singleton, if so return the shared instance if (answer instanceof IsSingleton) { boolean singleton = ((IsSingleton) answer).isSingleton(); if (singleton) { return answer; } } // language not known or not singleton, then use resolver answer = getLanguageResolver().resolveLanguage(language, this); // inject CamelContext if aware if (answer != null) { if (answer instanceof CamelContextAware) { ((CamelContextAware) answer).setCamelContext(this); } if (answer instanceof Service) { try { startService((Service) answer); } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); } } languages.put(language, answer); } } return answer; }
public Predicate getRetryWhilePolicy(CamelContext context) { Predicate answer = getRetryWhile(); if (getRetryWhileRef() != null) { // its a bean expression Language bean = context.resolveLanguage("bean"); answer = bean.createPredicate(getRetryWhileRef()); } return answer; }
/** * Returns a new sort by file language expression * * @param context the camel context * @param expression the file language expression * @param reverse true to reverse order * @param ignoreCase ignore case if comparing strings * @param nested nested comparator for sub group sorting, can be null * @return the comparator */ public static Comparator<Exchange> sortByFileLanguage( final CamelContext context, final String expression, final boolean reverse, final boolean ignoreCase, final Comparator<Exchange> nested) { // the expression should be enclosed by ${ } String text = expression; if (!expression.startsWith("${")) { text = "${" + text; } if (!expression.endsWith("}")) { text = text + "}"; } Language language = context.resolveLanguage("file"); final Expression exp = language.createExpression(text); return new Comparator<Exchange>() { public int compare(Exchange o1, Exchange o2) { Object result1 = exp.evaluate(o1, Object.class); Object result2 = exp.evaluate(o2, Object.class); int answer = ObjectHelper.compare(result1, result2, ignoreCase); // if equal then sub sort by nested comparator if (answer == 0 && nested != null) { answer = nested.compare(o1, o2); } return reverse ? -1 * answer : answer; } public String toString() { return expression + (nested != null ? ";" + nested.toString() : ""); } }; }
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); }
public LanguageEndpoint(String endpointUri, Component component, Language language, Expression expression, String resourceUri) { super(endpointUri, component, resourceUri); this.language = language; this.expression = expression; // enable cache by default setContentCache(true); }
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { String name = ObjectHelper.before(remaining, ":"); String script = ObjectHelper.after(remaining, ":"); // no script then remaining is the language name if (name == null && script == null) { name = remaining; } if (ObjectHelper.isEmpty(name)) { throw new IllegalArgumentException("Illegal syntax. Name of language not given in uri: " + uri); } Language language = getCamelContext().resolveLanguage(name); String resourceUri = null; String resource = script; if (resource != null) { if (resource.startsWith(RESOURCE)) { resource = resource.substring(RESOURCE.length()); } if (ResourceHelper.hasScheme(resource)) { // the script is a uri for a resource resourceUri = resource; // then the script should be null script = null; } else { // the script is provided as text in the uri, so decode to utf-8 script = URLDecoder.decode(script, "UTF-8"); // then the resource should be null resourceUri = null; } } LanguageEndpoint endpoint = new LanguageEndpoint(uri, this, language, null, resourceUri); endpoint.setScript(script); setProperties(endpoint, parameters); return endpoint; }
protected void processByLanguage(Exchange exchange, Language language) throws Exception { LanguageTask task = new LanguageTask(exchange, language); if (getEndpoint().isAsync()) { getEndpoint().getComponent().getExecutorService().submit(task); } else { task.run(); } }
public void testLookupByType() throws Exception { JndiRegistry jndi = new JndiRegistry(JndiTest.createInitialContext()); jndi.bind("foo", new SimpleLanguage()); jndi.bind("bar", "Hello bar"); assertEquals("Hello bar", jndi.lookup("bar")); assertEquals("Hello bar", jndi.lookupByName("bar")); assertEquals("Hello bar", jndi.lookupByNameAndType("bar", String.class)); assertNull(jndi.lookup("unknown")); assertNull(jndi.lookupByName("unknown")); try { assertNull(jndi.lookupByNameAndType("bar", Language.class)); fail("Should throw exception"); } catch (NoSuchBeanException e) { // expected } assertNotNull(jndi.lookupByNameAndType("foo", Language.class)); assertNotNull(jndi.lookupByNameAndType("foo", SimpleLanguage.class)); assertSame(jndi.lookupByNameAndType("foo", Language.class), jndi.lookupByNameAndType("foo", SimpleLanguage.class)); Map<String, ?> set = jndi.lookupByType(Language.class); assertNotNull(set); assertEquals(1, set.size()); String key = set.keySet().iterator().next(); assertEquals("foo", key); assertSame(jndi.lookupByName("foo"), set.values().iterator().next()); }
public void testLanguageCamelContextAware() throws Exception { Language lan = context.resolveLanguage("my"); assertNotNull(lan); MyLanguage me = assertIsInstanceOf(MyLanguage.class, lan); assertNotNull(me.getCamelContext()); }
@Override protected Language assertResolveLanguage(String languageName) { XPathLanguage answer = new XPathLanguage(); answer.setResultType(XPathConstants.STRING); assertEquals(XPathConstants.STRING, answer.getResultType()); return answer; }
public void testNonSingletonLanguage() throws Exception { Language tol = context.resolveLanguage("tokenize"); assertNotNull(tol); assertEquals(1, context.getLanguageNames().size()); // resolve again, should find another instance Language tol2 = context.resolveLanguage("tokenize"); assertNotNull(tol2); assertNotSame(tol, tol2); assertEquals(1, context.getLanguageNames().size()); context.stop(); assertTrue(context.getLanguageNames().isEmpty()); }
protected void assertExpressionResultInstanceOf(String expressionText, Class<?> expectedType) { Language language = assertResolveLanguage(getLanguageName()); Expression expression = language.createExpression(expressionText); assertNotNull("Cannot assert type when no type is provided", expectedType); assertNotNull("No Expression could be created for text: " + expressionText + " language: " + language, expression); Object answer = expression.evaluate(exchange, Object.class); assertIsInstanceOf(expectedType, answer); }
/** * Asserts that the given language name and expression evaluates to the * given value on a specific exchange */ protected void assertExpression(Exchange exchange, String languageName, String expressionText, Object expectedValue) { Language language = assertResolveLanguage(languageName); Expression expression = language.createExpression(expressionText); assertNotNull("No Expression could be created for text: " + expressionText + " language: " + language, expression); assertExpression(expression, exchange, expectedValue); }
/** * Asserts that the given language name and predicate expression evaluates * to the expected value on the message exchange */ protected void assertPredicate(String languageName, String expressionText, Exchange exchange, boolean expected) { Language language = assertResolveLanguage(languageName); Predicate predicate = language.createPredicate(expressionText); assertNotNull("No Predicate could be created for text: " + expressionText + " language: " + language, predicate); assertPredicate(predicate, exchange, expected); }
@Test public void testExpression() throws Exception { Language language = assertResolveLanguage(getLanguageName()); Expression expression = language.createExpression("SELECT * FROM org.apache.camel.builder.sql.Person where city = 'London'"); List<?> value = expression.evaluate(exchange, List.class); assertEquals("List size", 2, value.size()); for (Object person : value) { log.info("Found: " + person); } }
@Test public void testExpressionWithHeaderVariable() throws Exception { Language language = assertResolveLanguage(getLanguageName()); Expression expression = language.createExpression("SELECT * FROM org.apache.camel.builder.sql.Person where name = :fooHeader"); List<?> value = expression.evaluate(exchange, List.class); assertEquals("List size", 1, value.size()); for (Object person : value) { log.info("Found: " + person); assertEquals("name", "James", ((Person) person).getName()); } }
protected void testLanguage(String mainFeature, String language) throws Exception { LOG.info("Looking up CamelContext(myCamel) in OSGi Service Registry"); installCamelFeature(mainFeature); CamelContext camelContext = getOsgiService(bundleContext, CamelContext.class, "(camel.context.name=myCamel)", 20000); assertNotNull("Cannot find CamelContext with name myCamel", camelContext); LOG.info("Getting Camel language: {}", language); Language lan = camelContext.resolveLanguage(language); assertNotNull("Cannot get language with name: " + language, lan); LOG.info("Found Camel language: {} instance: {} with className: {}", language, lan, lan.getClass()); }