Examples Introduction¶ The Ballerina Module feature in WSO2 Integrator: MI allows developers to integrate custom data transformation logic into integration flows using the Ballerina programming language. By leveraging this capability, you can encapsulate complex business logic, data mappings, and type-specific operations as reusable modules and invoke them directly within your integration sequences. This document demonstrates how to use Ballerina code inside MI projects using the WSO2 Integrator: MI's Ballerina Module, with practical examples that showcase JSON-to-JSON mapping, XML total calculation, and dynamic type-based transformations. Example 1: Patient Mapping¶ This example demonstrates the transformation of a JSON payload representing patient data into a new format. The Ballerina module mapPatient processes the input data, extracts relevant details such as name, gender, and address, and maps them into a structured response. Example 2: Price Calculation¶ This example illustrates the use of a Ballerina module to calculate the total price of items in an XML payload. The module calculates the total price by summing up the prices of individual items and returns the result as a JSON response. Example 3: Dynamic Type-Based Transformation¶ This example handles various data types like string, integer, boolean, float, and decimal. Based on the input type, the corresponding Ballerina module performs operations such as doubling a string, inverting a boolean, or calculating a reciprocal of a float. The result is returned in a standardized format. If you do not want to configure this yourself, you can simply get the project and run it. Setup the Integration Project¶ Install the WSO2 Integrator: MI VS Code Extension To begin, install the WSO2 Integrator: MI VS Code extension from the Visual Studio Code marketplace. This extension enables you to create, manage, and deploy integration projects with ease. Create or Open an Integration Project Use the extension to Create a new integration project given the name ballerina-module-example or open an existing integration project. This project will serve as the workspace for your Ballerina module development. Create the Ballerina Module¶ Expand the artifact types in the Add artifact view and select Ballerina Module. In the Create Ballerina Module form, enter a name and a version for the module and click Create. Update the generated sample Ballerina code with following transformation logic and save the file. Ballerina Implementation for All Three Examplesimport wso2/mi; // Patient Mapping Logic type Patient record { string patientType; string patientId; string version; string lastUpdatedOn; string originSource; Description description; Identifier[] identifiers; string firstName; string lastName; string gender; LocationDetail[] locationDetail; }; type Identifier record { IdType id_type; string id_value; }; type IdType record { Code[] codes; }; type Code record { string system_source; string identifier_code; }; type Description record { string status; string details?; }; type LocationDetail record { string nation?; string town?; string region?; string zipCode?; string identifier?; string province?; }; @mi:Operation public function mapPatient(json payload) returns json { Patient|error patient = payload.cloneWithType(); if patient is error { return { "error": "Could not convert payload to Patient record" }; } return { name: [ { given: [patient.firstName], family: patient.lastName } ], meta: { versionId: patient.version, lastUpdated: patient.lastUpdatedOn, "source": patient.originSource }, text: { div: patient.description.details ?: "", status: patient.description.status }, gender: patient.gender, identifier: [ { system: patient.identifiers[0].id_type.codes[0].system_source, value: patient.identifiers[0].id_value } ], address: from var {nation, town, region, province, zipCode, identifier} in patient.locationDetail select { country: nation, city: town, district: region, state: province, postalCode: zipCode, id: identifier }, id: patient.patientId }; } // Price Calculation Logic @mi:Operation public function calculateTotal(xml invoice) returns xml { xml<xml:Element> prices = invoice/**/<price>; int total = from xml:Element element in prices let int|error price = int:fromString(element.data()) where price is int collect sum(price); return xml `<total>${total}</total>`; } // Type Processing Logic @mi:Operation public function invertBoolean(boolean b) returns boolean => !b; @mi:Operation public function doubleInt(int n) returns int => n * 2; @mi:Operation public function reciprocalFloat(float f) returns float { if f == 0.0 { return 1; } return 1.0 / f; } @mi:Operation public function addConstantToDecimal(decimal d) returns decimal => d + 10; @mi:Operation public function doubleString(string s) returns string => s + s; @mi:Operation public function getJsonNameProperty(json j) returns json { json jsn = j; if jsn is string { json|error je = jsn.fromJsonString(); if je is error { return {err: je.message()}; } jsn = je; } json|error val = jsn.name; if val is error { return {err: val.message()}; } return {val}; } @mi:Operation public function getXmlNameElement(xml x) returns xml { xml y = x/<name>; return xml `<result>${y}</result>`; } Click the Build Ballerina Module icon. Once the Ballerina module is successfully built, it will appear in the Mediator palette. Create the Integration Logic¶ Lets build the three APIs that will use the above Ballerina module. Go the Project Overview and click on the + button. and select API. Provide the name of the API as patientmap and context as /patientmap and click Create. Follow the same steps to create the other two APIs: /pricecal and /typeprocess. By default, the API will be created with a GET method. Click on the patientmap API and then click Edit. Select the POST method and click on Update. Repeat the above steps for the other two APIs as well. Now, click on the patientmap API and click on + to add a new mediator then select MapPatient operation in Ballerina Module. Click the Ex button and select the payload as the input. Make sure the Overwrite Message Body option is selected, and then click Add. Click on the + button again and add a Respond mediator. We also need to build the other two APIs. For this purpose, you can use the following Synapse configurations. Open the pricecal and typeprocess APIs, navigate to the Code View, and replace the existing code with the following Synapse Code for Price Calculation API<?xml version="1.0" encoding="UTF-8"?> <api context="/pricecal" name="pricecal" xmlns="http://ws.apache.org/ns/synapse"> <resource methods="POST" uri-template="/"> <inSequence> <ballerinaFunctions.calculateTotal> <responseVariable>ballerinaFunctions_calculateTotal_1</responseVariable> <overwriteBody>true</overwriteBody> <invoice>{${xpath('$body/*')}}</invoice> </ballerinaFunctions.calculateTotal> <respond/> </inSequence> <faultSequence> </faultSequence> </resource> </api> Synapse Code for Type Processing API<api xmlns="http://ws.apache.org/ns/synapse" name="typeprocess" context="/typeprocess"> <resource methods="POST" uri-template="/"> <inSequence> <switch source="${payload.type}"> <case regex="string"> <ballerinaFunctions.doubleString> <responseVariable>bal_response</responseVariable> <overwriteBody>false</overwriteBody> <s>{${payload.val}}</s> </ballerinaFunctions.doubleString> </case> <case regex="integer"> <ballerinaFunctions.doubleInt> <responseVariable>bal_response</responseVariable> <overwriteBody>false</overwriteBody> <n>{${payload.val}}</n> </ballerinaFunctions.doubleInt> </case> <case regex="boolean"> <ballerinaFunctions.invertBoolean> <responseVariable>bal_response</responseVariable> <overwriteBody>false</overwriteBody> <b>{${payload.val}}</b> </ballerinaFunctions.invertBoolean> </case> <case regex="float"> <ballerinaFunctions.reciprocalFloat> <responseVariable>bal_response</responseVariable> <overwriteBody>false</overwriteBody> <f>{${payload.val}}</f> </ballerinaFunctions.reciprocalFloat> </case> <case regex="decimal"> <ballerinaFunctions.addConstantToDecimal> <responseVariable>bal_response</responseVariable> <overwriteBody>false</overwriteBody> <d>{${payload.val}}</d> </ballerinaFunctions.addConstantToDecimal> </case> <case regex="json"> <ballerinaFunctions.getJsonNameProperty> <responseVariable>bal_response</responseVariable> <overwriteBody>false</overwriteBody> <j>{${payload.val}}</j> </ballerinaFunctions.getJsonNameProperty> </case> <default> <variable name="bal_response" type="JSON" value="{ "payload": "Unknown message type" }" /> </default> </switch> <payloadFactory media-type="json" template-type="default"> <format>{ "Result" : ${vars.bal_response.payload} }</format> </payloadFactory> <respond /> </inSequence> <faultSequence /> Get the project¶ You can download the ZIP file and extract the contents to get the project code. Run the Project and Test the APIs¶ Click on the Run icon to run the integration project. Open the integrated Try it feature or use a tool like Postman to test the APIs. For the Patient Mapping API, use the following JSON payload: { "patientType": "Patient", "patientId": "123456", "version": "1", "lastUpdatedOn": "2020-02-01T05:30:41.785+00:00", "originSource": "#hYoipn8902", "status": "generated", "identifiers": [ { "id_type": { "codes": [ { "system_source": "http://hl7.org/fhir/v2/0203", "identifier_code": "MR" } ] }, "id_value": "1213I7-bhjasb-80232-82032-shab9201212" } ], "firstName": "Andrew", "lastName": "Simons", "description": { "status": "generated" }, "gender": "male", "locationDetail": [ { "nation": "US", "town": "Seattle", "region": "WA", "zipCode": "98101", "identifier": "5648223", "province": "WA" } ] } You will get a response similar to the following: For the Price Calculation API, use the following XML payload: <items> <item> <name>book</name> <price>180</price> </item> <item> <name>pen</name> <price>25</price> </item> <item> <name>pencil</name> <price>12</price> </item> </items> You will get a response similar to the following: For the Type Processing API, use the following JSON payload: { "type": "decimal", "val": 5.3 } You will get a response similar to the following: