Channel Adapter in Mule: the legacy ERP's CSV becomes an order message
- 10 min read
On this page
Code
Some of the orders still live in an old ERP that knows nothing about messaging or JSON: it answers each order as a semicolon-separated CSV line, with the amount in cents and the status in a one-letter code. Connecting an application like that to the integration, so that it produces and receives the same messages as the others, is the Channel Adapter problem. In Mule, it is a connector (here, the HTTP Request) followed by the transformation that converts the system’s format into the order message.
The problem
The rest of the integration works with an order message: orderId, amount in reais, currency and status with names such as PAID or PAYMENT_DECLINED. The legacy ERP answers GET /eip/legacy/orders/ORD-LEGACY-1001 with this (assembled from the assertions of ca-legacy-csv-becomes-the-order-message):
ORDER_ID;TOTAL_CENTS;CURRENCY;STATUS_CODE
ORD-LEGACY-1001;4250;BRL;P
Without an adapter, every flow that needs an order from the ERP would have to know how to call the ERP, read semicolon-separated CSV, divide cents by 100, know that P means paid and that a nonexistent order comes back as plain text with a 404. The old system’s quirks would spread through the whole integration.
The pattern in the book
The book starts from companies that use messaging to integrate different applications and asks how to connect an application to the messaging system so it can send and receive messages. The solution is to use a Channel Adapter that can access the application’s API or data and publish messages on a channel based on that data, and that likewise can receive messages and invoke functions inside the application (Channel Adapter).
The adapter acts as a client of the messaging system and invokes the application’s functions through an interface the application itself offers. That way, any application can connect to the messaging system and be integrated with the others, as long as it has a suitable Channel Adapter. The book adds that the adapter can connect to different layers of the application’s architecture, depending on the architecture and the data the messaging system needs to access.
The diagram redraws the book’s sketch (CC BY 4.0) in the orders scenario:
In Mule
The documentation says a connector can act as an entry point that starts the flow (connectors that have sources), as a message processor that runs operations in the middle of the flow, or as an exit point that receives the flow’s final payload (Anypoint Connectors Overview). Not every connector does all three; the same page tells you to check each connector’s reference guide to see whether it can act as a source. In this page’s reading, backed by the book’s description, a connector used to talk to a system that does not know the integration (the ERP over HTTP, a database through the Database connector, a file server through SFTP) is the Channel Adapter: it speaks the system’s protocol and hands the flow a Mule message.
In the example, the connector is used as an operation: the HTTP Request fetches the order from the ERP in the middle of the flow. An adapter that started the flow, such as a file listener on a folder the ERP fills, would be the same pattern with the connector as a source, an Event-Driven Consumer on the legacy system’s side.
The connector solves only half. It delivers the CSV’s bytes; DataWeave, right after, converts them into the order message. That second half is the Message Translator, and in Mule the two pieces go together in the same flow. The book separates them, and the Message Translator page shows the translation on its own.
In the MuleSoft documentation
The documentation’s Enterprise Integration Patterns Using Mule page does not list the Channel Adapter. The closest row is the Message Endpoint’s, which it maps to the Mule SDK’s sources and operations, the pieces a connector is written with.
The example
The flow calls the ERP with the HTTP Request, handles unavailability inside a try, translates the legacy ERP’s 404 into the application’s 404 and converts the CSV:
<try doc:name="Try Read Legacy ERP">
<http:request doc:name="GET Order From Legacy ERP" config-ref="eip-self-http-request-config" method="GET" path="/eip/legacy/orders/{orderId}">
<http:uri-params><![CDATA[#[output application/java --- { orderId: vars.vOrderId }]]]></http:uri-params>
<http:response-validator>
<http:success-status-code-validator values="200,404" />
</http:response-validator>
</http:request>
<error-handler>
<on-error-continue doc:name="On Error Continue (legacy ERP unavailable)" type="HTTP:INTERNAL_SERVER_ERROR, HTTP:BAD_GATEWAY, HTTP:SERVICE_UNAVAILABLE, HTTP:GATEWAY_TIMEOUT, HTTP:CONNECTIVITY, HTTP:TIMEOUT" logException="false">
<logger doc:name="WARN: Log legacy ERP unavailable" level="WARN" message="#['Legacy ERP unavailable for order ' ++ vars.vOrderId ++ ': ' ++ error.errorType.namespace ++ ':' ++ error.errorType.identifier ++ ', correlationId=' ++ correlationId]" />
<set-variable doc:name="SET vLegacyDown" variableName="vLegacyDown" value="#[true]" />
</on-error-continue>
</error-handler>
</try>
<choice doc:name="Check Legacy Reachable">
<when expression="#[vars.vLegacyDown default false]">
<raise-error doc:name="Raise SERVICE_UNAVAILABLE Error - Legacy ERP down" type="APP:SERVICE_UNAVAILABLE" description="Legacy ERP unavailable" />
</when>
</choice>
<choice doc:name="Check Legacy Response">
<when expression="#[attributes.statusCode == 404]">
<raise-error doc:name="Raise NOT_FOUND Error - Unknown order" type="APP:NOT_FOUND" description="Order not found in the legacy ERP" />
</when>
</choice>
<ee:transform doc:name="Legacy CSV To Order Message">
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
var row = read(payload.^raw, "application/csv", { separator: ";" })[0]
var statuses = { P: "PAID", D: "PAYMENT_DECLINED", R: "REFUNDED" }
---
{
orderId: row.ORDER_ID,
amount: (row.TOTAL_CENTS as Number) / 100,
currency: row.CURRENCY,
status: statuses[row.STATUS_CODE] default "UNKNOWN",
(legacyStatusCode: row.STATUS_CODE) if (statuses[row.STATUS_CODE] == null),
source: "legacy-erp"
}]]></ee:set-payload>
</ee:message>
</ee:transform>
In the repository: src/main/mule/eip/channel-adapter/channel-adapter.xml
By default, the HTTP Request throws an error when the status is 400 or higher, so a 404 or a 500 from the server triggers error handling (Configure HTTP Request Operation). The example’s validator accepts 200,404 because the ERP’s 404 is a response, not a failure: the order does not exist, and the adapter answers 404 in JSON instead of the legacy ERP’s ORDER NOT FOUND text. The 500, 502, 503 and 504 responses, connection failures and timeouts become 503: the adapter does not know whether the order exists, and the caller can try again later.
In the transformation, DataWeave reads the CSV with the ; separator, passed as a reader property; the CSV format’s default separator is the comma (CSV Format). read(payload.^raw, ...) reads the response’s raw bytes and does not depend on the content type the ERP declares (an inference from the use of payload.^raw in the example; the simulated ERP declares application/csv, so the example does not prove the case of a legacy system that declares another type). A status code the adapter does not know does not break the read: it becomes UNKNOWN, and the original code stays in legacyStatusCode, so the receiver of the message knows there is something to look at.
The legacy ERP is simulated in the same application, in legacy-erp.xml, with four orders; ORD-LEGACY-1004 has the code X, which the adapter does not know.
Caveats
- The separator belongs to the reader, not to the data. Without
separator: ";", DataWeave would use the default comma (CSV Format) and, by inference from that default, would read the whole line as a single column. When the connector is the one reading the content, the separator can go in the connector’s own output type: KB article 001117176 shows afile:readwithoutputMimeType='application/csv; separator="	"'to read a TAB-separated file, and warns that Studio may convert the&into a character reference and cause unexpected behavior (Read a TAB delimited text file in Mule 4). In a 2020 Stack Overflow case, with DataWeave 1 (Mule 3), the asker thought a semicolon inside a field emptied the fields that followed; the answer showed the problem was something else: the file was|-separated, and the separator was not declared on the Transform’s input (Mule transform message failing at semi-colon). - A field that contains the separator needs quotes or an escape. The CSV format has the
quoteandescapeproperties for fields that contain the separator (CSV Format). It is worth agreeing with the legacy system’s owner on how it escapes fields before choosing the separator. - The legacy ERP’s failures have to stop at the adapter. Without the validator and the
try, the ERP’s 404 would arrive asHTTP:NOT_FOUNDand the 500 asHTTP:INTERNAL_SERVER_ERROR(HTTP Connector Reference), and the adapter’s callers would see the old system’s errors under the old system’s name. The testsca-legacy-500-becomes-503,ca-legacy-503-becomes-503andca-legacy-unreachable-becomes-503pin down the translation, with the error simulated by a mock; the 502, 504 and timeout are in the handler’s list but have no test. A 400, 401, 403 or 429 from the ERP is not translated: the validator accepts only 200 and 404, and those arrive as anHTTP:*error, with no test in the example. - The adapter is not the place for business rules. The book describes the adapter as what connects the application to the channel. Hence the example’s choice (this page’s reading, not the book’s): deciding what to do with a
REFUNDEDorder is up to the receiver of the message, and the adapter only converts format, units and codes.
When not to use it
When the system already speaks the integration’s message (JSON with the same fields), a connector is enough and the transformation is empty; there is nothing to adapt. When the difference is only in format between two messages already inside the integration, with no external system involved, what you want is the Message Translator alone. And when several legacy systems send the same kind of data in different formats, one adapter per system converts each to a common model; the series covers that in the Canonical Data Model.
Running the example and the tests
git clone https://github.com/brunosouzas/mulesoft-patterns-examples.git
cd mulesoft-patterns-examples
mvn clean test
The project requires Java 17, Maven 3.9+ and the Mule 4.9 runtime. MUnit runs on the Enterprise runtime, so Maven needs access to MuleSoft’s Enterprise repository (credentials in ~/.m2/settings.xml).
The channel-adapter-test-suite.xml suite pins down the behavior, observed on Mule 4.9.17 with MUnit 3.7.1:
| Test | What it proves |
|---|---|
ca-legacy-csv-becomes-the-order-message |
The ERP answers application/csv with ORD-LEGACY-1001;4250;BRL;P; the adapter answers JSON with amount 42.5 and status PAID |
ca-status-codes-are-translated |
D becomes PAYMENT_DECLINED (19.99), R becomes REFUNDED (USD kept); X becomes UNKNOWN with legacyStatusCode X |
ca-legacy-404-becomes-the-app-404 |
The ERP’s plain-text 404 becomes the application’s 404, in JSON |
ca-legacy-500-becomes-503 |
A 500 from the ERP (simulated with a mock) becomes a 503 in JSON, not a generic 500 |
ca-legacy-503-becomes-503 |
A 503 from the ERP (simulated with a mock) becomes a 503 in JSON |
ca-legacy-unreachable-becomes-503 |
An ERP that is down (connection error simulated with a mock) becomes a 503 in JSON |
The first test calls the ERP and the adapter and compares the two responses:
<munit-tools:assert-that doc:name="Legacy speaks CSV" expression="#[vars.vLegacy.contentType]" is="#[MunitTools::startsWith('application/csv')]" />
<munit-tools:assert-that doc:name="Legacy CSV with ; separator" expression="#[vars.vLegacy.text]" is="#[MunitTools::containsString('ORDER_ID;TOTAL_CENTS;CURRENCY;STATUS_CODE')]" />
<munit-tools:assert-that doc:name="Legacy row" expression="#[vars.vLegacy.text]" is="#[MunitTools::containsString('ORD-LEGACY-1001;4250;BRL;P')]" />
<munit-tools:assert-that doc:name="Adapter 200" expression="#[vars.vAdapted.status]" is="#[MunitTools::equalTo(200)]" />
<munit-tools:assert-that doc:name="Adapter JSON" expression="#[vars.vAdapted.contentType]" is="#[MunitTools::startsWith('application/json')]" />
<munit-tools:assert-that doc:name="Order message" expression="#[vars.vAdapted.body]" is="#[MunitTools::equalTo({ orderId: 'ORD-LEGACY-1001', amount: 42.5, currency: 'BRL', status: 'PAID', source: 'legacy-erp' })]" />
In the repository: src/test/munit/eip/channel-adapter-test-suite.xml
To call the endpoints, run the application in Anypoint Studio (port 8081) and use the Channel Adapter entries in requests.http:
### EIP channel adapter — the legacy ERP's CSV, and the same order through the adapter
GET {{base}}/eip/legacy/orders/ORD-LEGACY-1001
###
GET {{base}}/eip/adapters/legacy-orders/ORD-LEGACY-1001
In the repository: requests.http
Swap the ID for ORD-LEGACY-1004 to see the unknown code, or for one that does not exist to see the legacy ERP’s 404 become the application’s. The other patterns are in the catalog of integration patterns in Mule and, by component name, in the index by component.