Cannot coerce String { class: java.lang.String } - mule

I am trying to send email from the flow and stored all the email addresses in the yaml file like below
# Email
email:
toEmail: "abc.123#gg.org,def.456#gg.org"
fromEmail: "ms-dev#gg.org"
ccAddress: "abc123#gmail.com"
I am trying use the above values in to the send email connector like
<email:send doc:name="Send" doc:id="fd09c56f-eaed-44c4-ab06-aa0417f2fdbf" config-ref="Email_SMTP" subject="Error with SOW integration between D365 and Salesforce " fromAddress='#[p("email.fromEmail")]' toAddresses='#[p("email.toEmail") splitBy ","]' ccAddresses='#[p("email.ccAddress")]'>
<email:body contentType="text/html">
<email:content ><![CDATA[#[vars.emailBody]]]></email:content>
</email:body>
</email:send>
But when debugging Iam getting the error like below
org.mule.runtime.core.internal.exception.OnErrorPropagateHandler:
********************************************************************************
Message : "Cannot coerce String { class: java.lang.String } ("abc123#gmail.com" as String {class: "java.lang.String"}) to Array" evaluating expression: "p("email.ccAddress")".
Element : salesforce-proc-SendEmail_Flow/processors/1 # salesforce-proc:salesforce-proc-implementation.xml:566 (Send)
Element DSL : <email:send doc:name="Send" doc:id="fd09c56f-eaed-44c4-ab06-aa0417f2fdbf" config-ref="Email_SMTP" subject="Error with SOW integration between D365 and Salesforce " fromAddress="#[p("email.fromEmail")]" toAddresses="#[p("email.toEmail") splitBy ","]" ccAddresses="#[p("email.ccAddress")]">
<email:body contentType="text/html">
<email:content><![CDATA[
#[vars.emailBody]
]]></email:content>
</email:body>
</email:send>
Error type : MULE:EXPRESSION
FlowStack : at salesforce-proc-SendEmail_Flow(salesforce-proc-SendEmail_Flow/processors/1 # salesforce-proc:salesforce-proc-implementation.xml:566 (Send))
at listener-flow(listener-flow/errorHandler/0/processors/2 # salesforce-proc:salesforce-proc-implementation.xml:547 (Flow Reference))\
After fixing ccAddresses error I get below error
caf9-11ec-b461-025041000001] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler:
********************************************************************************
Message : Error while sending email: Exception reading response
Element : salesforce-proc-SendEmail_Flow/processors/1 # salesforce-proc:salesforce-proc-implementation.xml:566 (Send)
Element DSL : <email:send doc:name="Send" doc:id="fd09c56f-eaed-44c4-ab06-aa0417f2fdbf" config-ref="Email_SMTP" subject="Error with SOW integration between D365 and Salesforce " fromAddress="#[p("email.fromEmail")]" toAddresses="#[p("email.toEmail") splitBy ","]" ccAddresses="#[p("email.ccAddress") splitBy ","]">
<email:body contentType="text/html">
<email:content><![CDATA[
#[vars.emailBody]
]]></email:content>
</email:body>
</email:send>
Error type : EMAIL:SEND
FlowStack : at salesforce-proc-SendEmail_Flow(salesforce-proc-SendEmail_Flow/processors/1 # salesforce-proc:salesforce-proc-implementation.xml:566 (Send))
at listener-flow(listener-flow/errorHandler/0/processors/2 # salesforce-proc:salesforce-proc-implementation.xml:547 (Flow Reference))
Can anyone please suggest what is that I am missing here.

The problem is that ccAddresses expects an array. Because you are using an expression to configure that attribute you need to convert the string value from the configuration file explicitly to an array, for example using the splitBy() function as you did in toAddresses.
Or if you will only use one address simply remove the expression and use a property placeholder (ccAddresses="${email.ccAddress}").

Related

Karate Api : check if a phrase is available response object array

I've a response
{ errors: [
{
code: 123,
reason: "this is the cause for a random problem where the last part of this string is dynamically generated"
} ,
{
code: 234,
reason: "Some other error for another random reason"
}
...
...
}
Now when I validate this response
I use following
...
...
And match response.errors[*].reason contains "this is the cause"
This validation fails, because there is an equality check for complete String for every reason ,
I all I want is, to validate that inside the errors array, if there is any error object, which has a reason string type property, starting with this is the cause phrase.
I tried few wild cards but didn't work either, how to do it ?
For complex things like this, just switch to JS.
* def found = response.errors.find(x => x.reason.startsWith('this is the cause'))
* match found == { code: 123, reason: '#string' }
# you can also do
* if (found) karate.log('found')
Any questions :)

Parse a web activity error message into a synapse field

I have been trying to log an error from a web activity (POST method) into a field in a synapse table. The problem is, there are some special characters in the message key string like:
{
"value": [
{
"id": "",
"runId": "",
"debugRunId": ,
"runGroupId": "",
"pipelineName": "my_dynamic_pipeline_name",
"parameters": {
"region_code": "",
"data_start_date": "",
"data_end_date": "",
"etl_insert_batch_id": "",
"pipeline_subject_area": "",
"type_of_request": "",
"pipeline_name": "",
"pipeline_requested_by": "",
"debug": "",
"cdmloadtype": ""
},
"invokedBy": {
"id": "",
"name": "",
"invokedByType": ""
},
"runStart": "",
"runEnd": "",
"durationInMs": ,
"status": "",
"message": "Operation on target my_dynamic_pipeline_name failed: Operation on target my_dynamic_dataflow_name failed: {\"StatusCode\":\"DFExecutorUserError\",\"Message\":\"Job failed due to reason: at Sink 'SinkutilFailedDummy': java.sql.BatchUpdateException: Execution Status - FAILED ;Error number - 15165 ;Pipeline name - my_dynamic_pipeline_name; Stored procedure name - my_stored_proc_name ; Error step - Step 3: Key Hash and Util Type Hash Generation ; Insert batch ID - 1816 ; Error Message - Could not find object 'my object' or you do not have permission.\",\"Details\":\"java.sql.BatchUpdateException: Execution Status - FAILED ;Error number - 15165 ;Pipeline name - my_dynamic_pipeline_name; Stored procedure name - my_stored_proc_name ; Error step - Step 3: Key Hash and Util Type Hash Generation ; Insert batch ID - 1816 ; Error Message - Could not find object 'my_object' or you do not have permission.\\n\\tat shaded.msdataflow.com.microsoft.sqlserver.jdbc.SQLServerStatement.executeBatch(SQLServerStatement.java:1845)\\n\\tat com.microsoft.dataflow.transformers.store.JDBCWriter.executeBatchSQLs(JDBCStore.scala:462)\\n\\tat com.microsoft.dataflow.transformers.store.JDBCWriter.executeSQL(JDBCStore.scala:440)\\n\\tat com.microsoft.dataflow.transformers.store.JDBCWriter$$anonfun$executeTableOpAndPostSQLAndDDL$2.apply$mcV$sp(JDBCStore.scala:494)\\n\\tat com.microsoft.dataflow.transformers.store.JDBCWriter$$anonfun$executeTableOpAndPostSQLAndDDL$2.apply(JDBCStore.scala:494)\\n\\tat com.microsoft.dataflow.transformers.store.JDBCWriter$$anonfun$executeTableOpAndPostS\"}",
...
}
So I can filter down the output with:
#activity('pingPL').output.value[0].message
but there are {} and $ special characters that the Data Flow expression is trying to evaluate.
I already try to use replace or string functions in the pipeline expression or in the dataflow expression without success.
Is there a way to parse this as a string or get to the Message key?, something like:
#activity('pingPL').output.value[0].message*.failed*.failed.Message
Update:
This seems to be working:
#json(split(activity('pingPL').output.value[0].message, 'failed: ')[2]).Message
I can split by failed: and the index 2 will give me the error logs within the {...}. I can parse that as a json and use the Message key. It is working but it is not the ideal dynamic solution since the error message wouldn't have always the same structure.
Got a solution using substring and indexof to extract the {...} info:
substring(activity('pingPL').output.value[0].message,indexof(activity('pingPL').output.value[0].message,'{'),sub(indexof(activity('pingPL').output.value[0].message,'}'),sub(indexof(activity('pingPL').output.value[0].message,'{'),1)))
Getting this string as the output:
{\"StatusCode\":\"DFExecutorUserError\",\"Message\":\"Job failed due to reason: at Sink 'SinkutilFailedDummy': java.sql.BatchUpdateException: Execution Status - FAILED ;Error number - 15165 ;Pipeline name - my_dynamic_pipeline_name; Stored procedure name - my_stored_proc_name ; Error step - Step 3: Key Hash and Util Type Hash Generation ; Insert batch ID - 1816 ; Error Message - Could not find object 'my object' or you do not have permission.\",\"Details\":\"java.sql.BatchUpdateException: Execution Status - FAILED ;Error number - 15165 ;Pipeline name - my_dynamic_pipeline_name; Stored procedure name - my_stored_proc_name ; Error step - Step 3: Key Hash and Util Type Hash Generation ; Insert batch ID - 1816 ; Error Message - Could not find object 'my_object' or you do not have permission.\\n\\tat shaded.msdataflow.com.microsoft.sqlserver.jdbc.SQLServerStatement.executeBatch(SQLServerStatement.java:1845)\\n\\tat com.microsoft.dataflow.transformers.store.JDBCWriter.executeBatchSQLs(JDBCStore.scala:462)\\n\\tat com.microsoft.dataflow.transformers.store.JDBCWriter.executeSQL(JDBCStore.scala:440)\\n\\tat com.microsoft.dataflow.transformers.store.JDBCWriter$$anonfun$executeTableOpAndPostSQLAndDDL$2.apply$mcV$sp(JDBCStore.scala:494)\\n\\tat com.microsoft.dataflow.transformers.store.JDBCWriter$$anonfun$executeTableOpAndPostSQLAndDDL$2.apply(JDBCStore.scala:494)\\n\\tat com.microsoft.dataflow.transformers.store.JDBCWriter$$anonfun$executeTableOpAndPostS\"}
Then I used json expression to extract the key message:
json('extracted string').message
Then use replace to remove the single quotations ' to avoid a sql error.
This is the final expression I got to extract the error message:
#replace(json(substring(activity('pingPL').output.value[0].message,indexof(activity('pingPL').output.value[0].message,'{'),sub(indexof(activity('pingPL').output.value[0].message,'}'),sub(indexof(activity('pingPL').output.value[0].message,'{'),1)))).message,'''','-')

Mysterious error when accessing BRENDA with zeep

I'm trying to get all human Kcats and KMs from BRENDA using SOAP (technically zeep with Python3 I guess). I used this code, which follows the example code given here:
from zeep import Client
import hashlib
wsdl = "https://www.brenda-enzymes.org/soap/brenda_zeep.wsdl"
password = hashlib.sha256("password".encode("utf-8")).hexdigest()
client = Client(wsdl)
parameters = (
"email#email.com",
password,
"organism*Homo sapiens"
)
resultString = client.service.getKcatKmValue(*parameters)
and it gives me the error "Missing element organism (getKcatKmValue.organism)"
It's not clear to me what I'm doing wrong. Any insight would be appreciated.
If you run this command to inspect the definition of methods/operations:
python -mzeep https://www.brenda-enzymes.org/soap/brenda_zeep.wsdl
you can see the definition of getKcatKmValue as follows:
getKcatKmValue(email: xsd:string, password: xsd:string, ecNumber: xsd:string, organism: xsd:string, kcatKmValue: xsd:string, kcatKmValueMaximum: xsd:string, substrate: xsd:string, commentary: xsd:string, ligandStructureId: xsd:string, literature: xsd:string) -> return: ns0:ArrayOfKcatKmValues
so all of these parameters must be supplied which you are not passing in parameters hence the error.
a dict can also be passed to operation for a better visibility of passed arguments like this:
parameters = {
'email': "email#email.com",
'password': password,
'ecNumber': ecNumber,
'organism': "organism*Homo sapiens",
'kcatKmValue': kcatKmValue,
'kcatKmValueMaximum': kcatKmValueMaximum,
'substrate': substrate,
'commentary': commentary,
'ligandStructureId': ligandStructureId,
'literature' : literature
}
# then pass dict as follows:
resultString = client.service.getKcatKmValue(**parameters)
hope this helps.

Mule 4, get uri params with Anypoint application

I'm new in Mulesoft, I'm following Quickstart guide. In Step 2 (https://developer.mulesoft.com/guides/quick-start/developing-your-first-mule-application), I need to receive variables from URI in this way:
[{'id' : attributes.uriParams.productId}]
But when I try my GET I have the following error in console:
**Message : "Cannot coerce Array ([{id: "2" as String {class: "java.lang.String"}}]) to Object 1| [{'id' : attributes.uriParams.productId}] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Trace: at main (line: 1, column: 1)" evaluating expression: "[{'id' : attributes.uriParams.productId}]". Error type : MULE:EXPRESSION Element : get:\products(productId):test_daniel-config/processors/1 # test6_db_connection:test_daniel.xml:133 (Select) Element XML : SELECT product.,CONCAT('["', (GROUP_CONCAT(variant.picture SEPARATOR '","')),'"]') AS pictures,CONCAT('[', GROUP_CONCAT('{"',variant.identifierType, '":"', variant.identifier, '"}'),']') AS identifiersFROM product INNER JOIN variant ON product.uuid = variant.productUUIDWHERE product.uuid = :id; #[[{'id' : attributes.uriParams.productId}]] *
Any Ideas? Thanks!
cannot coerce Array to object error pop's up when you are using an array where you were supposed to use an object.
in the exception above the uri-param should be treated as ab object i.e. enclosed in {} but its being treated as an array of objects [{}].
this is causing the error.

Karate API Testing - verify if "retriever" breed is within the list

I am testing a public API that lists all types of breeds.
'https://dog.ceo/api/breeds/list/all'
Within the response I need to verify if "retriever" breed is within the list. My feature file looks like this
Feature: Testing a REST API
Scenario: Testing valid GET endpoint
Given url 'https://dog.ceo/api/breeds/list/all'
When method GET
Then status 200
And print response
And match response.message contains 'retriever'
However I get the following error:
com.intuit.karate.exception.KarateException: path: $.message, actual:
{affenpinscher=[], african=[], airedale=[], akita=[], appenzeller=[],
basenji=[], beagle=[], bluetick=[], borzoi=[], bouvier=[], boxer=[],
brabancon=[], briard=[], bulldog=["boston","french"],
bullterrier=["staffordshire"], cairn=[], cattledog=["australian"],
chihuahua=[], chow=[], clumber=[], cockapoo=[], collie=["border"],
coonhound=[], corgi=["cardigan"], cotondetulear=[], dachshund=[],
dalmatian=[], dane=["great"], deerhound=["scottish"], dhole=[],
dingo=[], doberman=[], elkhound=["norwegian"], entlebucher=[],
eskimo=[], frise=["bichon"], germanshepherd=[], greyhound=["italian"],
groenendael=[],
hound=["afghan","basset","blood","english","ibizan","walker"],
husky=[], keeshond=[], kelpie=[], komondor=[], kuvasz=[], labrador=[],
leonberg=[], lhasa=[], malamute=[], malinois=[], maltese=[],
mastiff=["bull","tibetan"], mexicanhairless=[], mix=[],
mountain=["bernese","swiss"], newfoundland=[], otterhound=[],
papillon=[], pekinese=[], pembroke=[], pinscher=["miniature"],
pointer=["german","germanlonghair"], pomeranian=[],
poodle=["miniature","standard","toy"], pug=[], puggle=[], pyrenees=[],
redbone=[], retriever=["chesapeake","curly","flatcoated","golden"],
ridgeback=["rhodesian"], rottweiler=[], saluki=[], samoyed=[],
schipperke=[], schnauzer=["giant","miniature"],
setter=["english","gordon","irish"], sheepdog=["english","shetland"],
shiba=[], shihtzu=[],
spaniel=["blenheim","brittany","cocker","irish","japanese","sussex","welsh"], springer=["english"], stbernard=[],
terrier=["american","australian","bedlington","border","dandie","fox","irish","kerryblue","lakeland","norfolk","norwich","patterdale","russell","scottish","sealyham","silky","tibetan","toy","westhighland","wheaten","yorkshire"],
vizsla=[], weimaraner=[], whippet=[], wolfhound=["irish"]}, expected:
'retriever', reason: actual value is not a string
Look at the response structure carefully. These will work:
And match response.message contains { retriever: '#array' }
And match response.message.retriever == ['chesapeake', 'curly', 'flatcoated', 'golden']
Do read the documentation and examples.