이 콘텐츠는 선택한 언어로 제공되지 않습니다.

13.2. How to Invoke an Expression Language


Prerequisites

Before you can use a particular expression language, you must ensure that the required JAR files are available on the classpath. If the language you want to use is not included in the Apache Camel core, you must add the relevant JARs to your classpath.
If you are using the Maven build system, you can modify the build-time classpath simply by adding the relevant dependency to your POM file. For example, if you want to use the Ruby language, add the following dependency to your POM file:
<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-script</artifactId>
  <!-- Use the same version as your Camel core version -->
  <version>${camel.version}</version>
</dependency>
Copy to Clipboard Toggle word wrap
If you are going to deploy your application in a Red Hat JBoss Fuse OSGi container, you also need to ensure that the relevant language features are installed (features are named after the corresponding Maven artifact). For example, to use the Groovy language in the OSGi container, you must first install the camel-groovy feature by entering the following OSGi console command:
karaf@root> features:install camel-groovy
Copy to Clipboard Toggle word wrap
Note
If you are using an expression or predicate in the routes, refer the value as an external resource by using resource:classpath:path or resource:file:path. For example, resource:classpath:com/foo/myscript.groovy.

Camel on EAP deployment

The camel-script component and the camel-groovy component are both supported by the Camel on EAP (Wildfly Camel) framework, which offers a simplified deployment model on the Red Hat JBoss Enterprise Application Platform (JBoss EAP) container. For details of this model, see chapter "Apache Camel on Red Hat JBoss EAP" in "Deploying into a Web Server".

Approaches to invoking

As shown in Table 13.1, “Expression and Predicate Languages”, there are several different syntaxes for invoking an expression language, depending on the context in which it is used. You can invoke an expression language:

As a static method

Most of the languages define a static method that can be used in any context where an org.apache.camel.Expression type or an org.apache.camel.Predicate type is expected. The static method takes a string expression (or predicate) as its argument and returns an Expression object (which is usually also a Predicate object).
For example, to implement a content-based router that processes messages in XML format, you could route messages based on the value of the /order/address/countryCode element, as follows:
from("SourceURL")
  .choice
    .when(xpath("/order/address/countryCode = 'us'"))
      .to("file://countries/us/")
    .when(xpath("/order/address/countryCode = 'uk'"))
      .to("file://countries/uk/")
    .otherwise()
      .to("file://countries/other/")
  .to("TargetURL");
Copy to Clipboard Toggle word wrap

As a fluent DSL method

The Java fluent DSL supports another style of invoking expression languages. Instead of providing the expression as an argument to an Enterprise Integration Pattern (EIP), you can provide the expression as a sub-clause of the DSL command. For example, instead of invoking an XPath expression as filter(xpath("Expression")), you can invoke the expression as, filter().xpath("Expression").
For example, the preceding content-based router can be re-implemented in this style of invocation, as follows:
from("SourceURL")
  .choice
    .when().xpath("/order/address/countryCode = 'us'")
      .to("file://countries/us/")
    .when().xpath("/order/address/countryCode = 'uk'")
      .to("file://countries/uk/")
    .otherwise()
      .to("file://countries/other/")
  .to("TargetURL");
Copy to Clipboard Toggle word wrap

As an XML element

You can also invoke an expression language in XML, by putting the expression string inside the relevant XML element.
For example, the XML element for invoking XPath in XML is xpath (which belongs to the standard Apache Camel namespace). You can use XPath expressions in a XML DSL content-based router, as follows:
<from uri="file://input/orders"/>
<choice>
  <when>
 <xpath>/order/address/countryCode = 'us'</xpath>
    <to uri="file://countries/us/"/>
  </when>
  <when>
 <xpath>/order/address/countryCode = 'uk'</xpath>
    <to uri="file://countries/uk/"/>
  </when>
  <otherwise>
    <to uri="file://countries/other/"/>
  </otherwise>
</choice>
Copy to Clipboard Toggle word wrap
Alternatively, you can specify a language expression using the language element, where you specify the name of the language in the language attribute. For example, you can define an XPath expression using the language element as follows:
<language language="xpath">/order/address/countryCode = 'us'</language>
Copy to Clipboard Toggle word wrap

As an annotation

Language annotations are used in the context of bean integration (see Section 2.4, “Bean Integration”). The annotations provide a convenient way of extracting information from a message or header and then injecting the extracted data into a bean's method parmeters.
For example, consider the bean, myBeanProc, which is invoked as a predicate of the filter() EIP. If the bean's checkCredentials method returns true, the message is allowed to proceed; but if the method returns false, the message is blocked by the filter. The filter pattern is implemented as follows:
// Java
MyBeanProcessor myBeanProc = new MyBeanProcessor();

from("SourceURL")
  .filter().method(myBeanProc, "checkCredentials")
  .to("TargetURL");
Copy to Clipboard Toggle word wrap
The implementation of the MyBeanProcessor class exploits the @XPath annotation to extract the username and password from the underlying XML message, as follows:
// Java
import org.apache.camel.language.XPath;

public class MyBeanProcessor {
    boolean void checkCredentials(
        @XPath("/credentials/username/text()") String user,
        @XPath("/credentials/password/text()") String pass
    ) {
        // Check the user/pass credentials...
        ...
    }
}
Copy to Clipboard Toggle word wrap
The @XPath annotation is placed just before the parameter into which it gets injected. Notice how the XPath expression explicitly selects the text node, by appending /text() to the path, which ensures that just the content of the element is selected, not the enclosing tags.

As a Camel endpoint URI

Using the Camel Language component, you can invoke a supported language in an endpoint URI. There are two alternative syntaxes.
To invoke a language script stored in a file (or other resource type defined by Scheme), use the following URI syntax:
language://LanguageName:resource:Scheme:Location[?Options]
Copy to Clipboard Toggle word wrap
Where the scheme can be file:, classpath:, or http:.
For example, the following route executes the mysimplescript.txt from the classpath:
from("direct:start")
  .to("language:simple:classpath:org/apache/camel/component/language/mysimplescript.txt")
  .to("mock:result");
Copy to Clipboard Toggle word wrap
To invoke an embedded language script, use the following URI syntax:
language://LanguageName[:Script][?Options]
Copy to Clipboard Toggle word wrap
For example, to run the Simple language script stored in the script string:
String script = URLEncoder.encode("Hello ${body}", "UTF-8");
from("direct:start")
  .to("language:simple:" + script)
  .to("mock:result");
Copy to Clipboard Toggle word wrap
For more details about the Language component, see Language in the Apache Camel Component Reference Guide.
맨 위로 이동
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2025 Red Hat