Mule ESB: Can not get MEL to access field - mule

I have the following flow, that accepts a JSON object from http, then
converts the JSON object to a standard Object, and then performs
a CHOICE on the object.
Below is the flow:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns:json="http://www.mulesoft.org/schema/mule/json" version="EE-3.5.0" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:core="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd">
<json:object-to-json-transformer name="Object_to_JSON" doc:name="Object to JSON"/>
<flow doc:name="HelloWorldFlow1" name="HelloWorldFlow1">
<http:inbound-endpoint doc:description="This endpoint receives an HTTP message." doc:name="HTTP" exchange-pattern="request-response" host="localhost" port="8081" contentType="application/json"/>
<json:json-to-object-transformer doc:name="JSON to Object"/>
<choice doc:name="Choice-Determine-Route" tracking:enable-default-events="true">
<when expression="#[payload.uid == 'ABC']">
<set-payload value="#['When ABC case']" doc:name="Set Payload"/>
</when>
<otherwise>
<set-payload value="#['Default case, payload: ' + payload + ', payload.uid: ' + payload.uid]" doc:name="Set Payload"/>
</otherwise>
</choice>
</flow>
</mule>
Below is the test of the flow
C:\curl>type input2.txt
{ "uid" : "ABC" }
C:\curl>curl -H "Content-Type: application/json" -i -d #input2.txt http://localh
ost:8081
Content-Type: application/json
Default case, payload: {"uid":"ABC"}, payload.uid: null
So even though my input2.txt contained:
{ "uid" : "ABC" }
I could not get the following expression to trigger successfully
#[payload.uid == 'ABC']
Now notice the Set Payload expression
#['Default case, payload: ' + payload + ', payload.uid: ' + payload.uid]
... and what it reported:
Default case, payload: {"uid":"ABC"}, payload.uid: null
So it does not seem to recognize payload.uid
How should I reference this in MEL ?
Thanks

Because you haven't defined the returnClass attribute,it will by default return an instance of org.mule.module.json.JsonData - http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/module/json/JsonData.html
So in that case you need to use:
when expression="#[payload.get('UID') == 'ABC']"
If instead you set the transformer to return a map or an object with a uid field you can navigate it using the . notation you tried.
So to make your expression work use:
<json:json-to-object-transformer returnClass="java.util.HashMap" doc:name="JSON to Object"/>

Related

Sending Multipart Requests in mule

I have an Database connector from the selected data i use to create a file and I want to do HTTP post with file (created from the selected data in csv) along with other data (text) as attached in the screenshot. According to the mule documentation, the payload must be an outbound attachment which I am doing by using Set Attachment property. With this approach, I am setting the Content-Type for one of my attachment as application/CVS (as my file is of CVS type) and as text/plain for the other parameter. Any thoughts on achieving this? I have attached the screenshot of how the request looks like in Postman.
Below is the config XML..!!
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:file="http://www.mulesoft.org/schema/mule/file"
xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd">
<spring:beans>
<spring:bean id="CSFMDataSource" name="CSFMDataSource" class="oracle.jdbc.pool.OracleDataSource">
<spring:property name="user" value="XXCCS_OSB_O"/>
<spring:property name="password" value="OrG2_BtN"/>
<spring:property name="dataSourceName" value="ds"/>
<spring:property name="URL" value="jdbc:oracle:thin:#(DESCRIPTION=(CONNECT_TIMEOUT=5)(TRANSPORT_CONNECT_TIMEOUT=3)(RETRY_COUNT=1)(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=scan-nprd-2023)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=DV3CSF_SRVC_OTH.cisco.com)(SERVER=DEDICATED)))"/>
</spring:bean>
</spring:beans>
<db:oracle-config name="Oracle_Configuration" dataSource-ref="CSFMDataSource" doc:name="Oracle Configuration"/>
<http:request-config name="HTTP_Request_Configuration" host="tools-stage.cisco.com" port="80" doc:name="HTTP Request Configuration"/>
<flow name="testFlow">
<poll doc:name="Poll">
<fixed-frequency-scheduler frequency="1" timeUnit="MINUTES"/>
<logger message="Log-1" level="INFO" doc:name="Logger"/>
</poll>
<db:select config-ref="Oracle_Configuration" doc:name="Database">
<db:parameterized-query><![CDATA[SELECT sol.SW_UPG_CONTRACT_NUMBER,
sol.service_level,
sol.BILL_TO_SITE_USE_ID,
sol.SERVICE_BEGIN_DATE,
sol.SERVICE_END_DATE,
0 Net_Price,
sol.PRODUCT_ORDER_NUMBER,
sol.SERIAL_NUMBER,
sol.SW_UPG_FULFILLMENT_PID,
sol.INSTALL_SITE_USE_ID,
sii.INSTANCE_ID,
DECODE (sii.INSTANCE_ID, 'Yes', 'No') softline,
'1232' cs_cse_number,
lg.error_message
FROM apps.XXCSS_SFM_ORDER_LINES sol,
apps.XXCSS_SFM_ERROR_LOG lg,
apps.XXCSS_SFM_INSTANCE_INTERFACE sii
WHERE 1 = 1
AND sol.order_type = 'INNVO_LINE'
AND sol.entitlement_status IN ('CSFM_ERROR', 'QA_FAILED')
--AND lg.so_header_id = sol.header_id
--AND lg.so_line_id = sol.line_id
AND lg.ERROR_TYPE = 'ERROR'
AND sol.header_id = sii.so_header_id(+)
AND sol.line_id = sii.so_line_id(+)
AND lg.sfdc_case_req = 'Y'
AND lg.sfdc_case_no IS NULL]]></db:parameterized-query>
</db:select>
<dw:transform-message doc:name="Transform Message" metadata:id="38e67a04-7f03-4261-a450-72b69ae0fff1">
<dw:set-payload><![CDATA[%dw 1.0
%output application/csv
---
payload map ((payload01 , indexOfPayload01) -> {
BILL_TO_SITE_USE_ID: payload01.BILL_TO_SITE_USE_ID as :number,
CS_CSE_NUMBER: payload01.CS_CSE_NUMBER,
ERROR_MESSAGE: payload01.ERROR_MESSAGE,
INSTALL_SITE_USE_ID: payload01.INSTALL_SITE_USE_ID as :number,
INSTANCE_ID: payload01.INSTANCE_ID,
NET_PRICE: payload01.NET_PRICE as :number,
PRODUCT_ORDER_NUMBER: payload01.PRODUCT_ORDER_NUMBER,
SERIAL_NUMBER: payload01.SERIAL_NUMBER,
SERVICE_BEGIN_DATE: payload01.SERVICE_BEGIN_DATE,
SERVICE_END_DATE: payload01.SERVICE_END_DATE,
SERVICE_LEVEL: payload01.SERVICE_LEVEL,
SOFTLINE: payload01.SOFTLINE,
SW_UPG_CONTRACT_NUMBER: payload01.SW_UPG_CONTRACT_NUMBER,
SW_UPG_FULFILLMENT_PID: payload01.SW_UPG_FULFILLMENT_PID
})]]></dw:set-payload>
</dw:transform-message>
<byte-array-to-object-transformer doc:name="Byte Array to Object"/>
<set-attachment attachmentName="filedata" value="#[payload]" contentType="application/csv" doc:name="Attachment"/>
<set-attachment attachmentName="casedata" value="{ "Origin":"Web", "CaseNumber":"33315931584", "SearchCCOID":"vimerugu"}" contentType="text/plain" doc:name="Attachment"/>
<set-payload value="#[null]" doc:name="Set Payload"/>
<http:request config-ref="HTTP_Request_Configuration" path="/cvcm/was70/pwc036/caseApi/updateCaseAttach/33315931584" method="POST" doc:name="HTTP" parseResponse="false">
<http:request-builder>
<http:header headerName="Authorization" value="Basic Q1BFQ2FzZUFQSS5nZW46Y2FzZTFnZW4="/>
</http:request-builder>
</http:request>
<logger message="#[flowVars.varCaseUpdate]" level="INFO" doc:name="Logger"/>
<catch-exception-strategy doc:name="Catch Exception Strategy">
<db:insert config-ref="Oracle_Configuration" doc:name="Log_DB">
<db:parameterized-query><![CDATA[insert into XXCSS_SFM_OSB_EXECUTION_LOG (PROCESS_STATUS) values ('SFDCCaseCreationService-Exception')]]></db:parameterized-query>
</db:insert>
<db:insert config-ref="Oracle_Configuration" doc:name="SFDCCaseCreation- Exception">
<db:parameterized-query><![CDATA[insert into XXCSS_SFM_CESB_LOG_ERROR ( LOG_ERROR_ID,SERVICE_NAME,SERVICE_TYPE,SERVICE_ACTIVITY,SERVICE_PAYLOAD,LOG_ERROR_STATUS,
LOG_ERROR_MESSAGE,ERROR_CODE,ERROR_MESSAGE,ERROR_DETAILS,LOG_ERROR_SEVERITY,SUGGESTED_ACTION,NOTIFY_MAIL,NOTIFY_COUNT,ATTRIBUTE_1,
ATTRIBUTE_2,ATTRIBUTE_3,ATTRIBUTE_4,ATTRIBUTE_5,ATTRIBUTE_6,ATTRIBUTE_7,ATTRIBUTE_8,ATTRIBUTE_9,ATTRIBUTE_10,CREATED_BY,CREATION_DATE,LAST_UPDATED_BY,LAST_UPDATE_DATE,BATCH_ID)
values ('1000','SFDCCaseCreationService','SFDCCaseCreationServiceType','SFDCCaseCreationServiceActivity','SFDCCaseCreationServicePayload','ERROR','','Error_Code','Error_Message',
#[exception.getSummaryMessage()],'Critical','','NA',3,'','','','','','','','','','','SFDCCaseCreationService',sysdate,'SFDCCaseCreationService',sysdate,'1000')]]></db:parameterized-query>
</db:insert>
</catch-exception-strategy>
</flow>
</mule>
Please check if below link helps you.It tells how to read multiple files and process them.You can send them to required endpoint instead of FTP
How send a file in an HTTP request and upload it to file server via FTP in Mule

Add new line to custom Exception message in Anypoint Studio Mule

I am using Anypoint Studio 6.1 and Mule 3.8.1 and want to return an Exception message with the "\n" returned as a new line. I am trying to use System.getProperty("line.separator") but the "\n" still appear in the message as text and not a new line.
How can I get this to work?
XML Test Flow:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd">
<flow name="tempflowFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/test-flow" allowedMethods="GET" doc:name="HTTP"/>
<set-payload value="{
"Exception": {
"status": -1,
"description": "\nJson content is not compliant with schema\ncom.github.fge.jsonschema.core.report.ListProcessingReport: failure\n--- BEGIN MESSAGES ---\nerror: object has too many properties (found 2 but schema requires at most 1)\n level: \"error\"\n schema: {\"loadingURI\":\"file:/C:/temp.json#\",\"pointer\":\"/properties/field1\"}\n instance: {\"pointer\":\"/field1\"}\n domain: \"validation\"\n keyword: \"maxProperties\"\n found: 2\n required: 1\n--- END MESSAGES ---\n (org.mule.module.json.validation.JsonSchemaValidationException)."
}
}" encoding="UTF-8" mimeType="application/json" doc:name="Set Payload"/>
<logger message="#[payload.replace("\n", System.getProperty('line.separator'))]" level="INFO" doc:name="Logger"/>
<set-payload value="#[payload.replace("\n", System.getProperty('line.separator'))]" encoding="UTF-8" mimeType="application/json" doc:name="Set Payload"/>
</flow>
</mule>
Thanks
Looks like you need to escape the newline character. Also, use single quotes (') instead of double quotes (") inside MEL expression.
<logger message="#[payload.replace('\\n', System.getProperty('line.separator'))]" level="INFO"
doc:name="Logger" />
<set-payload value="#[payload.replace('\\n', System.getProperty('line.separator'))]" encoding="UTF-8"
mimeType="application/json" doc:name="Set Payload" />
Above code seems to work:
INFO 2017-02-09 18:03:09,349 [Mule.app.deployer.monitor.1.thread.1] org.mule.module.launcher.MuleDeploymentService:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Started app 'test2' +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO 2017-02-09 18:03:17,280 [[test2].HTTP_Listener_Configuration.worker.01] org.mule.api.processor.LoggerMessageProcessor: { "Exception": { "status": -1, "description": "
Json content is not compliant with schema
com.github.fge.jsonschema.core.report.ListProcessingReport: failure
--- BEGIN MESSAGES ---
error: object has too many properties (found 2 but schema requires at most 1)
level: \"error\"
schema: {\"loadingURI\":\"file:/C:/temp.json#\",\"pointer\":\"/properties/field1\"}
instance: {\"pointer\":\"/field1\"}
domain: \"validation\"
keyword: \"maxProperties\"
found: 2
required: 1
--- END MESSAGES ---
(org.mule.module.json.validation.JsonSchemaValidationException)." } }
Mule log

How to get refresh_token with the Box Connector in Mule

I'm using the 3.0.0.201609092037 version (the latest one) of the Box connector as I don't find any documentation or sample code to get the refresh token, I wrote my own flow to get it.
I achieve to execute the Authorize action with the connector and then my intension is to send a request to Box API to this url: https://api.box.com/oauth2/token in order to get an access_token and also a refresh_token (I got the API info from here https://docs.box.com/reference#token).
The problem is, once my flow has been authorized and I get access_code, and I'm using it to send it to Box I always am receiving this:
{
"error": "invalid_grant",
"error_description": "The authorization code has expired"
}
I checked all the information and I it suppose to be good, the response I'm expecting is:
{
"access_token": "T9cE5asGnuyYCCqIZFoWjFHvNbvVqHjl",
"expires_in": 3600,
"restricted_to": [],
"token_type": "bearer",
"refresh_token": "J7rxTiWOHMoSC1isKZKBZWizoRXjkQzig5C6jFgCVJ9bUnsUfGMinKBDLZWP9BgR"
}
So I'll be able to store those properties and refresh the token if is needed.
Here how my flow looks like:
and Here my XML definition:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:tls="http://www.mulesoft.org/schema/mule/tls" xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:objectstore="http://www.mulesoft.org/schema/mule/objectstore" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns:box="http://www.mulesoft.org/schema/mule/box" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/box http://www.mulesoft.org/schema/mule/box/current/mule-box.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/objectstore http://www.mulesoft.org/schema/mule/objectstore/current/mule-objectstore.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd
http://www.mulesoft.org/schema/mule/tls http://www.mulesoft.org/schema/mule/tls/current/mule-tls.xsd">
<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration" protocol="HTTPS">
<tls:context>
<tls:key-store type="jks" path="OBKeytore.jks" keyPassword="password" password="password"/>
</tls:context>
</http:listener-config>
<box:config-with-oauth name="Box__OAuth_2_0" clientId="my_client_id" clientSecret="My_secret" doc:name="Box: OAuth 2.0">
<box:oauth-callback-config domain="localhost" localPort="8081" remotePort="8081" path="callback" connector-ref="HTTP_Listener_Configuration"/>
<box:oauth-store-config objectStore-ref="_defaultInMemoryObjectStore"/>
</box:config-with-oauth>
<objectstore:config name="ObjectStore__Connector" partition="BoxAccessToken" persistent="true" doc:name="ObjectStore: Connector"/>
<http:request-config name="HTTP_Request_Configuration" host="api.box.com" port="443" basePath="/oauth2/" doc:name="HTTP Request Configuration" protocol="HTTPS"/>
<tls:context name="TLS_Context" doc:name="TLS Context">
<tls:trust-store path="OBKeytore.jks" password="password" type="jks"/>
<tls:key-store type="jks" path="OBKeystore.jks" keyPassword="password" password="password"/>
</tls:context>
<flow name="Authorize">
<http:listener config-ref="HTTP_Listener_Configuration" path="/authorize" doc:name="HTTP"/>
<box:authorize config-ref="Box__OAuth_2_0" doc:name="Box"/>
<flow-ref name="GenerateAcessToken" doc:name="GenerateAcessToken"/>
</flow>
<flow name="GenerateAcessToken">
<logger message="Acess Token: #[flowVars['_oauthVerifier']]" level="INFO" doc:name="Logger"/>
<set-payload value="#[[
'grant_type' :'authorization_code',
'code':flowVars['_oauthVerifier'],
'client_id':'my_client_id',
'client_secret':'my_secret'
]]" doc:name="Set Payload"/>
<http:request config-ref="HTTP_Request_Configuration" path="token" method="POST" doc:name="HTTP">
<http:success-status-code-validator values="200,400"/>
</http:request>
<object-to-string-transformer doc:name="Object to String"/>
<logger message="#[payload]" level="INFO" doc:name="Logger"/>
<catch-exception-strategy doc:name="Catch Exception Strategy">
<object-to-string-transformer doc:name="Object to String"/>
<logger message="#[payload]" level="INFO" doc:name="Logger"/>
</catch-exception-strategy>
</flow>
</mule>
I have to mention that I already tried to use POSTMAN with the same params, replacing the code (as far I know it is valid for 30 secs) and getting the same response.
Here some more information:
Anypoint Studio version: 6.1.1
Server Runtime: 3.8.1 EE
It sounds like the OAuth authorization configuration of the HTTP requester might be required as described for a Mule Server trying to access the resources that belong to a Box user and that are held in a Box server: https://docs.mulesoft.com/mule-user-guide/v/3.8/authentication-in-http-requests
http://mulesoft.github.io/box-connector/3.0.0/apidocs/box-apidoc.html#_oauth_2_0_server_to_server and this example of managing OAuth tokens that uses Box as an example might be worth a look if you haven't seen it.

Handling Accept encoding in esb mule

I have mule flow look like below
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata" xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd">
<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8111" doc:name="HTTP Listener Configuration"/>
<http:request-config name="HTTP_Request_Configuration" host="api.bonanza.com" port="443" doc:name="HTTP Request Configuration" protocol="HTTPS"/>
<flow name="bonanza_fetchtoken_ceFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/add" allowedMethods="GET,POST" doc:name="HTTP" />
<flow-ref name="bonanza_addfixedpriceitemSub_Flow" doc:name="bonanza_addfixedpriceitemSub_Flow"/>
</flow>
<sub-flow name="bonanza_addfixedpriceitemSub_Flow">
<message-properties-transformer doc:name="Message Properties">
<add-message-property key="X-BONANZLE-API-DEV-NAME" value="t******I"/>
<add-message-property key="X-BONANZLE-API-CERT-NAME" value="l*****F"/>
</message-properties-transformer>
<set-property propertyName="Content-Type" value="application/x-www-form-urlencoded" doc:name="Property"/>
<set-property propertyName="Accept" value="application/json" doc:name="Property"/>
<set-variable variableName="sim" value="{requesterCredentials:{bonanzleAuthToken:nWn1a9l3NT}}" doc:name="Variable"/>
<scripting:transformer returnClass="java.util.Map" doc:name="Groovy">
<scripting:script engine="Groovy"><![CDATA[import groovy.json.JsonBuilder
m = [addFixedPriceItemRequest:'{requesterCredentials:{bonanzleAuthToken:n*****T}}']
builder = new JsonBuilder()
builder(m)
]]></scripting:script>
</scripting:transformer>
<logger message="payload :#[payload]" level="INFO" doc:name="Logger"/>
<http:request config-ref="HTTP_Request_Configuration" path="/api_requests/secure_request" method="POST" followRedirects="true" parseResponse="false" doc:name="HTTP">
<http:success-status-code-validator values="0..599"/>
</http:request>
<logger message="resp :#[message.payloadAs(java.lang.String)]" level="INFO" doc:name="Logger"/>
</sub-flow>
</mule>
I am able to receiving successful response from API using postman tool. I try to simulate same thing using above ESB mule flow. But API throws me an error as like below. Hence i have used requestb.in to compare the requests going from esb mule and postman tool. i found differences in the HTTP headers alone.
RAW body from postman to requestb.in -
addFixedPriceItemRequest={requesterCredentials:{bonanzleAuthToken:nW*****NT}}
RAW Body from ESB mule to requestb.in
addFixedPriceItemRequest=%7BrequesterCredentials%3A%7BbonanzleAuthToken%3AnW****NT%7D%7D
It seems that i have to serialize the json content before sending as content type - application/x-www-form-urlencoded. I found this info in this mule doc
How can i serialize json payload in groovy and sending as map payload?
API Error Response
{
"ack": "Failure",
"version": "1.0beta",
"timestamp": "2016-03-15T07:18:11.000Z",
"errorMessage": {
"message": "Cannot determine what type of request you are making. Often this can be the result of data that has not been escaped before being passed to the API. If you are passing data with quotation marks or other special characters, you should translate it to JSON, then escape it, before sending it over the API."
}
}
Please let me know for any additional info. Thanks in advance!
The flow got worked by adding key value pair in query parms in the http component. The flowVariable requestpayload has json string. So my Mule http component looks like below.
<http:request config-ref="HTTP_Request_Configuration" path="/api_requests/secure_request" method="POST" followRedirects="true" parseResponse="false" doc:name="HTTP">
<http:request-builder>
<http:query-param paramName="addFixedPriceItemRequest" value="#[flowVars.requestpayload]"/>
</http:request-builder>
<http:success-status-code-validator values="0..599"/>
</http:request>

Mule DataWeave JSON content is null

Mule version: 3.7.3
Anypoint Studio: 5.4.0
To learn DataWeave, I've created a simple flow that executes twitter search, loops through each tweet, attempts to use DataWeave to condense the payload, then logs the results. The issue I'm running into is that the json seems to be null coming out of DW.
Tweet Text before DW:
Welcome to the world of #APILedConnectivity Lebron James! Your request has been processed by #MuleSoft #AnypointPlatform # 1986
The payload coming out of DW is not null:
org.mule.api.processor.LoggerMessageProcessor: DW Payload: com.mulesoft.weave.mule.WeaveMessageProcessor$WeaveOutputHandler#1657d772
However, the 'tweet' json element is null when outputting to logs:
org.mule.api.processor.LoggerMessageProcessor: Found Tweet: null
Here's my sample mule flow:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata" xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:twitter="http://www.mulesoft.org/schema/mule/twitter" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/twitter http://www.mulesoft.org/schema/mule/twitter/current/mule-twitter.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd">
<flow name="test-dataweaveFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/>
<twitter:search config-ref="TwitterConnection" query="#[json:hashtag]" doc:name="Twitter"/>
<foreach collection="#[payload.tweets]" doc:name="For Each">
<logger message="Payload before DW: #[payload.text]" level="INFO" doc:name="Logger"/>
<dw:transform-message metadata:id="99e88418-ce6a-4d18-a900-6c35d7f36c83" doc:name="Transform Message">
<dw:input-payload doc:sample="QueryResult.dwl"/>
<dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
{
tweet: {
screenName: payload.user.screenName,
tweetId: payload.id,
tweetContent: payload.text
}
}
]]></dw:set-payload>
</dw:transform-message>
<logger message="DW Payload: #[payload]" level="INFO" doc:name="Logger"/>
<logger message="Found Tweet: #[payload.tweet]" level="INFO" doc:name="Logger"/>
</foreach>
<json:object-to-json-transformer doc:name="Object to JSON"/>
</flow>
</mule>
Screenshot of the mapping:
Any ideas where I might be messing things up?
Don't put the DataWeave transformer in the for each scope!
You can iterate in DataWeave, that will give you a better result probably.
You will create a map from the payload, the map operator accepts a collection.
The twitter connector will give you a collection of JSON objects.
The clue here is, drag the DataWeave transformer after the Twitter connector.
The input data in DataWeave will be provided and you will have autocomplete in you DataWeave script.
Docs: https://docs.mulesoft.com/mule-user-guide/v/3.7/dataweave-reference-documentation
Some examples in how to map form JSON here:
https://docs.mulesoft.com/mule-user-guide/v/3.7/dataweave-examples#json-to-xml