← Wiki

Message Translator in Mule: the partner's CSV order becomes the application's order

  • 9 min read
On this page

Code

A partner sends orders as CSV, one row per item, with its own product codes and prices in cents. The order application works with a JSON order, with a list of items, its own SKUs and prices in reais. Someone has to convert one format into the other without either side changing, and in Mule 4 that someone is the Transform, with a DataWeave script.

The problem

In the series’ order scenario (order → payment → inventory → invoice), the partner’s order arrives like this:

partnerOrderRef,buyerCode,shipToCountry,productCode,qty,unitPriceCents
P-77,B-100,BR,BOOK-01,2,3000
P-77,B-100,BR,MUG-02,1,1250

The application expects { orderId, customerId, country, currency, items }. Renaming the columns is not enough. Two rows become one order with two items; "2" becomes the number 2; 3000 cents become 30; BOOK-01 becomes SKU-BOOK. The partner will not change its file for the application, and the application should not know the format of every partner.

The pattern in the book

The book starts from a common situation: the integrated applications are legacy systems, packaged software, in-house applications or partners’ applications, and each is built around its own data model. Each has a slightly different idea of what a customer is, and expects to receive messages in a format that mimics its internal one. On top of that, the integration often has to talk to third parties in formats standardized by consortia, while internal systems use their own. The pattern’s question is how systems that use different data formats can communicate through messages. The answer is a special filter, the Message Translator, placed between other filters or applications to translate one data format into another. The book compares the pattern to the Adapter of the GoF catalog: the adapter converts one component’s interface into another so that it can be used in a different context (Message Translator).

One format in, another out

The diagram, redrawn from the official sketch (CC BY 4.0), answers: where does the translator sit, and what does each side need to know about the other?

The Partner, which speaks CSV, sends to the Message Translator, which delivers to the Order application, which speaks JSON.

Neither side knows the other’s format. Only the translator knows both.

In Mule

In Mule 4, the Message Translator is the Transform (or Transform Message). The documentation describes it as the component that converts input data into a new output structure or format, with a visual mapper or a hand-written DataWeave script (Transform Message Component). DataWeave reads the CSV because the request arrives with Content-Type: application/csv, the MIME type of the CSV format in the documentation. That format is represented as an array of objects, one per row, and with header=true, the default, each row’s fields are accessed by column name (CSV Format).

The translation flow

The diagram answers: what happens to the CSV before and during the translation?

The POST /eip/orders/translate endpoint receives application/csv and passes to the decision “Valid rows, a single order, known codes?”. If not, it answers 400: APP:BAD_REQUEST. If yes, the Transform Translate Partner CSV To Order delivers the Application’s order in JSON.

The same component also does two other patterns

The Transform also implements the Canonical Data Model, when each system translates to a common model instead of translating to every other system, and the Content Filter, when the output only drops fields from the message. In the book these are three patterns, each for its own problem; it was Mule, not the book, that put the three in one component. The page of each one shows the problem it solves and what changes in DataWeave.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule maps the Message Translator to the Message Transformer, with a link to the Transform Message Component page: the same component as on this page.

The example

The POST /eip/orders/translate endpoint receives the partner’s CSV and returns the application’s order. The translation is a Transform:

<ee:transform doc:name="Translate Partner CSV To Order">
	<ee:message>
		<ee:set-payload><![CDATA[%dw 2.0
output application/json
import skuFor from dwl::translator::PartnerProducts
var first = payload[0]
---
{
	orderId: "ORD-" ++ first.partnerOrderRef,
	customerId: "CUS-" ++ first.buyerCode,
	country: upper(first.shipToCountry),
	// The partner contract is BRL-only: the CSV has no currency column and its prices are BRL cents.
	currency: "BRL",
	items: payload map ((row) -> {
		sku: skuFor(row.productCode),
		quantity: row.qty as Number,
		unitPrice: (row.unitPriceCents as Number) / 100
	})
}]]></ee:set-payload>
	</ee:message>
</ee:transform>

In the repository: src/main/mule/eip/message-translator/message-translator.xml

The structure. Each CSV row is an item; there is only one order. The order’s data (reference, buyer, country) comes from the first row, and payload map turns each row into an item of the list.

The types. In CSV, every simple value is text (CSV Format). The quantity becomes a number with as Number, and the price in cents becomes reais by dividing by 100.

The codes. The partner’s product code is not the application’s SKU. The mapping table lives in a DataWeave module of its own, used by both the validation and the translation:

%dw 2.0
// Message translator: the partner's product codes and this application's SKUs.
var skuByProductCode = {
	"BOOK-01": "SKU-BOOK",
	"MUG-02": "SKU-MUG",
	"EBOOK-03": "SKU-EBOOK",
	"POSTER-04": "SKU-POSTER"
}

// The SKU of a partner product code, or null when the code is unknown.
fun skuFor(productCode: String | Null): String | Null = if (productCode == null) null else skuByProductCode[productCode]

In the repository: src/main/resources/dwl/translator/PartnerProducts.dwl

A code without a SKU does not become an item with a null SKU: the validation, before the Transform, answers 400 and says which code was not recognized. The same goes for rows of two different orders in the same request, which would be merged into one order, and for a quantity that is not a whole number. A translator that guesses or drops a value hands the target a message that looks valid and has the wrong content.

The suite checks the output field by field, and the type of the quantity:

<munit-tools:assert-that doc:name="Rows became items" expression="#[payload.items]" is="#[MunitTools::equalTo([{sku: 'SKU-BOOK', quantity: 2, unitPrice: 30}, {sku: 'SKU-MUG', quantity: 1, unitPrice: 12.5}])]" />
<munit-tools:assert-that doc:name="Quantity is a number, not the CSV string" expression="#[payload.items[0].quantity is Number]" is="#[MunitTools::equalTo(true)]" />

In the repository: src/test/munit/eip/message-translator-test-suite.xml

Caveats

Everything from the CSV is text. The format’s documentation says all simple CSV values are represented as strings (CSV Format). Without a conversion, the quantity comes out in the JSON as "2", and the next system compares text with a number. The mt-partner-csv-rows-become-one-order test checks that the quantity is a Number.

An empty column is not null. In a 2017 Stack Overflow question, still on DataWeave 1 in Mule 3, empty CSV fields showed up as "" in the JSON, and skipNullOn did not remove them (Stack Overflow: Ignore empty string when mapping CSV to JSON using Dataweave). In a MuleSoft forum thread from the same period, the answer explains why: skipNullOn skips null values, and an empty string is not null (MuleSoft forum: how to skip elements which is empty string when converting csv to json). Both cases are from Mule 3; the current documentation does not cover the empty column, but since the Mule 4 CSV reader still delivers every simple value as text (CSV Format), the trap is likely to remain (an inference from the documentation, not tested in the example). The example’s validation uses isEmpty on each required column and a regular expression on the quantity and the price, and rejects the row before the Transform tries to read a number that does not exist (the mt-non-numeric-quantity-is-rejected test).

A number in text depends on the format. A MuleSoft knowledge base article describes the error Cannot coerce String (0,372970) to Number in Mule 4: a number formatted as text came out with a decimal comma, because no locale was given and the machine used a comma as the separator, and converting it back to a number failed (KB 001123351). The coercion documentation lists format and locale as the properties that govern conversion between String and Number (Type Coercion with DataWeave). In the example, the partner contract sends the price in whole cents, with no decimal separator to interpret.

The header is part of the contract. With header=true, the default, columns are read by name; with header=false, by position, like payload[107][2] (CSV Format). If the partner sends the file without a header, row.qty no longer exists, and it is the validation that has to reject the order, not the Transform that has to make up a value.

When not to use it

When both sides already speak the same format, a Transform in the middle just copies the message. When many applications exchange data with each other and the number of translators starts to grow pairwise, the pattern is the Canonical Data Model. When the message only needs to lose fields, without changing format, it is the Content Filter. And when what is missing is not in the message but in another system, the pattern is the Content Enricher.

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 example runs with nothing external.

What each test in the suite proves, observed on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
mt-partner-csv-rows-become-one-order Two rows of order P-77 become one order with two items, numeric quantities, prices in reais and the application’s SKUs and identifiers
mt-unknown-product-code-rejects-the-whole-order A product code without a SKU rejects the whole order with 400 and names the code (LAMP-99)
mt-rows-of-two-orders-are-rejected Rows of two orders in the same request are rejected with 400, instead of being merged into one order
mt-non-numeric-quantity-is-rejected A quantity that is not a whole number (two) is rejected with 400 before the Transform
mt-over-http-error-answers-400-and-success-200 Over HTTP, the listener returns the status the error handling set: the unknown product code gets 400 in JSON, and the valid CSV gets 200

To call the endpoint, run the application in Anypoint Studio (port 8081) and open requests.http in VS Code (REST Client) or IntelliJ:

### EIP message translator — a partner order as CSV becomes this app's order
POST {{base}}/eip/orders/translate
Content-Type: application/csv

partnerOrderRef,buyerCode,shipToCountry,productCode,qty,unitPriceCents
P-77,B-100,BR,BOOK-01,2,3000
P-77,B-100,BR,MUG-02,1,1250

In the repository: requests.http

The other patterns, with the Mule component that implements each one, are in the catalog of integration patterns in Mule; the reverse path, from component to patterns, is in the index by component.

Code for this page