Transport
Ajax Transport Reference
Ajax (Asynchronous Java and XML) is a group of interrelated web development techniques used for creating interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page.
The Mule Ajax connector allows Mule events to be sent and received asynchronously to and from the web browser. The connector includes a JavaScript client that listens for events, sends events, and performs RPC calls. It can be deployed in Mule standalone or embedded in a servlet container such as Apache Tomcat or Tcat Server.
Ajax Connector Guide: Ajax Connector
Transport Info
Feature | Value | Description |
---|---|---|
Ajax |
The name/protocol of the transport |
|
Doc |
JavaDoc and Schema doc |
|
Inbound |
|
Whether the transport can receive inbound events and can be used for an inbound endpoint. |
Outbound |
|
Whether the transport can produce outbound events and be used with an outbound endpoint. |
Request |
|
Whether this endpoint can be queried directly with a request call (via MuleClient or the EventContext). |
Transactions |
|
Whether transactions are supported by the transport. Transports that support transactions can be configured in either local or distributed two-phase commit (XA) transaction. |
Streaming |
|
Whether this transport can process messages that come in on an input stream. This allows for very efficient processing of large data. |
Retries |
|
Whether this transport supports retry policies. Note that all transports can be configured with Retry policies, but only the ones marked here are officially supported by MuleSoft. |
MEPs |
one-way |
Message Exchange Patterns supported by this transport. |
Default MEP |
one-way |
The default MEP for endpoints that use this transport that do not explicitly configure a MEP |
Maven Artifact |
|
The group name and artifact name for this transport in Maven |
The Ajax transport has server and client parts. The server part is similar to every other Mule transport. The client part is a JavaScript client that lets users publish and subscribe to Mule messages in a browser (see Using the JavaScript Client). The server connector can either run as an embedded Ajax (cometD) server or bind to a servlet container.
Namespace and Syntax
XML Namespace:
xmlns:ajax="http://www.mulesoft.org/schema/mule/ajax"
XML Schema location:
http://www.mulesoft.org/schema/mule/ajax http://www.mulesoft.org/schema/mule/ajax/current/mule-ajax.xsd
Connector Syntax:
<ajax:connector name="ajaxServer" serverUrl="http://0.0.0.0:8090/mule/ajaxServer" resourceBase="${app.home}/docroot"/>
Features
-
Easily performs asynchronous calls to Mule
-
Broadcasts events to browsers listening to Ajax channels
-
Performs sudo - RPC calls from the browser
-
Uses standalone or bound to a servlet container
Usage
To the Ajax transport in your configuration, add the ajax
namespaces:
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:ajax="http://www.mulesoft.org/schema/mule/ajax"
xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/ajax http://www.mulesoft.org/schema/mule/ajax/current/mule-ajax.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">
...
Configuring the Server
The usual way of setting up the Ajax server is to use the one embedded in Mule. This can be created by adding an ajax:connector element to your config:
<ajax:connector serverUrl="http://0.0.0.0:8080/ajax"/>
This starts an Ajax server and is ready to start publishing and subscribing. Next you can create a flow that listens to Ajax messages on a channel:
<flow name="AjaxEcho">
<ajax:inbound-endpoint channel="/services/echo"/>
<echo-component/>
</flow>
Or to publish on an Ajax channel, use an outbound endpoint:
Embedding in a Servlet Container
If you are running Mule inside a servlet container such as Apache Tomcat, bind Ajax endpoints to the servlet container by adding the org.mule.transport.ajax.container.MuleAjaxServlet
to your web.xml
in your webapp and use the ajax:servlet-xxx-endpoint
elements.
Configure your web.xml
using:
<servlet>
<servlet-name>ajax</servlet-name>
<servlet-class>org.mule.transport.ajax.container.MuleAjaxServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ajax</servlet-name>
<url-pattern>/ajax/*</url-pattern>
</servlet-mapping>
Then replace any ajax:inbound-endpoint
and ajax:outbound-endpoint
with ajax:servlet-inbound-endpoint
and ajax:servlet-outbound-endpoint
respectively.
To use the football scores example again:
<flow name="AjaxBridge">
<jms:inbound-endpoint topic="football.scores"/>
<ajax:servlet-outbound-endpoint channel="/football/scores"/>
</flow>
Then configure your connector and endpoints as described below.
Using the JavaScript Client
Mule provides a powerful JavaScript client with full Ajax support that can be used to interact with Mule flows directly in the browser. It also provides support for interacting directly with objects running inside the container using Cometd, a message bus for Ajax web applications that allows multi-channel messaging between the server and client.
Configuring the Server
To use the JavaScript client, you just need to have a flow that has an Ajax inbound endpoint through which requests can be sent. This example shows a simple echo flow published on the /services/echo
Ajax channel:
<flow name="AjaxEcho">
<ajax:inbound-endpoint channel="/services/echo"/>
<echo-component/>
</flow>
Enabling the Client
To enable the client in an HTML page, add a single script element to the page:
<head>
...
<script type="text/javascript" src="mule-resource/js/mule.js"></script>
Adding this script element makes a 'mule' client object available for your page.
Making an RPC request
This example defines a button in the body that, when clicked, sends a request to the Echo flow:
<input id="sendButton" class="button" type="submit" name="Go" value="Send" onclick="callEcho();"/>
The button calls the callEcho
function, which handles the logic of the request:
function callEcho()
{
var data = new Object();
data.phrase = document.getElementById('phrase').value;
mule.rpc("/services/echo", data, callEchoResponse);
}
This function uses the rpc
method to request data from the flow. The rpc
method sets up a private response channel that Mule uses to publish when response data is available. The first argument is the channel on which you’re making the request (this matches the channel that our Echo Flow is listening on), the second argument is the payload object, and the third argument is the callback function that processes the response, in this case a function called call Echo Response:
function callEchoResponse(message)
{
document.getElementById("response").innerHTML = "<b>Response: </b>" + message.data + "\n";
}
If you use rpc
just for a one-way request where you don’t pass a callback function as parameter because you don’t expect a response, use the disableReplyTo
flag in the Ajax connector:
<ajax:connector name="ajaxServer" ... disableReplyTo="true" />
Handling Errors
To check if an error occurred, set the error
parameter in the callback function to verify that the error is null before processing. If it is not null, an error occurred and the error should be logged or displayed to the user.
function callEchoResponse(message, error)
{
if(error)
handleError(error)
else
document.getElementById("response").innerHTML = "<b>Response: </b>" + message.data + "\n";
}
function handleError(error) {
alert(error);
}
Listening to Server Events
The Mule JavaScript client allows developers to subscribe to events from Mule flows. These events just need to be published on an Ajax endpoint. Here is a flow that receives events on JMS and publishes them to an Ajax channel.
<flow name="AjaxBridge">
<jms:inbound-endpoint topic="football.scores"/>
<ajax:outbound-endpoint channel="/football/scores"/>
</flow>
Now you can register for interest in these football scores by adding a subscriber via the Mule JavaScript client.
<script type="text/javascript">
mule.subscribe("/football/scores", scoresCallback);
</script>
The first argument of the subscribe
method is the Ajax path that the flow publishes to. The second argument is the name of the callback function that processes the message. In this example, it’s the scoresCallback
function, which is defined next:
function scoresCallback(message)
{
console.debug("data:" + message.data);
if (!message.data)
{
console.debug("bad message format " + message);
return;
}
// logic goes here
...
}
JSON Support Mule has JSON support including object/JSON bindings, which makes it really easy to marshal data to JSON markup before dispatching to the browser, where JSON is a native format. |
Sending a Message
Let’s say you want to send a message out without getting a response. In this case, you call the publish
function on the Mule client:
<script type="text/javascript">
mule.publish("/services/foo", data);
</script>
Example Configurations
Mule comes bundled with several examples that employ the Ajax Connector. We recommend you take a look at the "Notifications Example" and the "GPS Walker Example" (which is also explained in further detail in Walk this Way: Building AJAX apps with Mule). In the following typical use cases we focus on the key elements involved when using and configuring the connector.
Publish Example Server code
First, set up an Ajax inbound endpoint in the Mule configuration to receive requests:
Configuring an Ajax Inbound Endpoint | ||||||||
---|---|---|---|---|---|---|---|---|
|
Publish Example Client Code
The browser sends some information to Mule (using the JavaScript Mule client) when a button is pushed.
Publishing data | ||||||
---|---|---|---|---|---|---|
|
Subscribe Example Server code
This is a useful and friendly way to send information to several clients at once. All they have to do is subscribe themselves to a channel where the server sends whatever needs to be broadcasted.
Mule Runtime provides an AJAX connector, an AJAX outbound endpoint and the required JavaScript client library to take care of this.
We add an AJAX connector that hosts the pages (HTML, CSS, etc.) using the JavaScript client and that lets them interact with Mule’s AJAX endpoints. It’s the same connector we used in the two previous examples.
We also need to publish some content via an AJAX outbound endpoint in a channel.
Configuring an AJAX Outbound Endpoint Channel | ||||||||
---|---|---|---|---|---|---|---|---|
|
Subscribe Example Client Code
Listening to an AJAX Outbound Channel | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|
|
RPC Example Server Code
This configuration is very similar to the one in the previous example. As a matter of fact, the only significant changes are the channel name and an out-of-the-box echo component to bounce the request back to the caller.
Configuring an AJAX Inbound Endpoint that sends a response | ||||||||
---|---|---|---|---|---|---|---|---|
|
RPC Example Client Code
The browser sends information to Mule (using the JavaScript Mule client) when a button is pushed, just as it did before. This time however, a callback method displays the response.
Making an RPC Call - Expecting a response |
---|
|
Note the following changes:
-
Loading the mule.js script ❶ makes the Mule client automatically available via the ‘mule’ variable.
-
The rpcCallMuleEcho() ❷ method gathers some data from the page and submits it to the ‘/services/echo’ channel we configured before.
-
The mule.rpc() ❸ method makes the actual call to Mule. This time, it receives three parameters:
-
The channel name.
-
The data to send.
-
The callback method to be invoked when the response is returned.
-
-
The rpcEchoResponse() callback method ❹ takes a single parameter, which is the response message, and displays its data on the page.
Connector
Allows Mule to expose Mule Services over HTTP using a Jetty HTTP server and Cometd. A single Jetty server is created for each connector instance. One connector can serve many endpoints. Users should rarely need to have more than one Ajax servlet connector.
There are no default values in the following table.
Name | Description |
---|---|
serverUrl |
When using Ajax embedded (not within a servlet container), configure a URL to create an Ajax server hosted in Mule. The URL should be in the form of |
resourceBase |
Specifies a local path where files are served from. The local path gets mapped directly to the path on the 'serverUrl'. |
disableReplyTo |
By default, an asynchronous reply to the inbound endpoint is sent back. This can cause unwanted side effects in some cases, use this attribute to disable. |
logLevel |
0=none, 1=info, 2=debug |
timeout |
The server side poll timeout in milliseconds (default 250000). This is how long the server holds a reconnect request before responding. |
interval |
The client side poll timeout in milliseconds (default 0). How long a client waits between reconnects |
maxInterval |
The max client side poll timeout in milliseconds (default 30000). A client is removed if a connection is not received in this time. |
jsonCommented |
If |
multiFrameInterval |
The client side poll timeout if multiple connections are detected from the same browser (default 1500). |
refsThreshold |
The number of message refs at which a single message response is cached instead of being generated for every client delivered to. Optimizes a single message being sent to multiple clients. |
Name | Cardinality |
---|---|
client |
0..1 |
key-store |
0..1 |
server |
0..1 |
protocol-handler |
0..1 |
Inbound Endpoint
Allows a Mule service to receive Ajax events over HTTP using a Jetty server. This is different from the equivalent servlet-inbound-endpoint
because it uses an embedded servlet container rather that relying on a pre-existing servlet container instance. This endpoint type should not be used if running Mule embedded in a servlet container.
Name | Type | Required | Description |
---|---|---|---|
channel |
string |
yes |
The Ajax channel to bind the service endpoint to. This channel path is independent context path that your application is deployed to in the servlet container. |
No child elements.
Outbound Endpoint
Allows a Mule service to send Ajax events over HTTP using Bayeux. JavaScript clients can register interest in these events using the Mule JavaScript client.
Name | Description |
---|---|
channel |
The Ajax channel to bind the service endpoint to. This channel path is independent context path that your application is deployed to in the servlet container. |
cacheMessages |
If set to true, the dispatcher caches messages if there are no clients subscribed to this channel. |
messageCacheSize |
If cache messages is set to true, this value determines the size of the memory cache. The cache automatically expires older items to make room for newer items. |
No child elements.
Maven
The Ajax Transport can be included with the following dependency:
<dependency>
<groupId>org.mule.transports</groupId>
<artifactId>mule-transport-ajax</artifactId>
</dependency>
Best Practices
-
Use Ajax outbound endpoints mainly for broadcasting information to several clients simultaneously. For example, broadcasting live news updates to several browsers in real time without reloading the page.
-
It’s recommended to subscribe/unsubscribe callback methods associated with outbound channels on
<body>
onload/onunload. See example above. Pay special attention to unsubscribing callback methods. -
When sending information back and forth between clients and servers using Ajax you should consider using JSON. Mule provides a JSON module to handle transformations gracefully.