Mule ESB : Traverse a json payload and make where clause condition for Salesforce - json

Following is the input in terms of json payload and what is required is to form a where clause statement which I can use for salesforce query.
Note: The number of query fields can vary from 1 to n.
Input payload
{
"object_type": "contact",
"query_fields": [
{
"field_name": "CreatedById", "field_value": "005g0000003qelYAAQ"},
{
"field_name": "BillingState", "field_value": "KA"}
]
}
Sample output:
#[json:query_fields[0]/field_name] = '#[json:query_fields[0]/field_value]' AND #[json:query_fields[0]/field_name] = '#[json:query_fields[0]/field_value]'

I figured out the solution to this problem and thought of sharing the same with us all.
Step 1: Transformed the above mentioned input payload into array:
<dw:set-payload><![CDATA[%dw 1.0
%output application/java
---
payload map {
field_name : $.field_name,
field_value : $.field_value
}]]></dw:set-payload>
Step 2: Used an expression component to traverse the array and take the value of it so that I can use the values to form a where clause for the Salesforce query further in my flow.
<![CDATA[String wrcls ="";
int m=1;
int n=0;
for (String counter : flowVars.queryfields)
{
wrcls += payload[m].field_name[n] + " = " + "'" + payload[m].field_value[n] + "'" + " AND "
m = m + 1;
n = n + 1;
}
payload = wrcls;
payload = payload.replaceAll(" AND $", "");]]>

Related

Create nested reponse from sql view with spring boot DTO

I have a view generated form multiple tables, I want to return a nested response from the view like the following.
[
{
"id":"c2bb81dd-6837-4dd7-b903-4c2ec938f78a",
"name":"Olive Oil",
"date":"2023-01-05",
"quantity":180,
"consumption":50,
"demand":0.00,
"max":100.00,
"safety":20.00,
"unit":"L",
"consumedProducts":[
{
"id":"197f88e6-b941-414d-b571-8be6a64ce82f",
"name":"Burger",
},
{
"id":"0010f6d6-71d3-4553-aaf5-96383b3c0c28",
"name":"Sandwich",
}
],
"wastage":{
"preparation":15.25,
"expiration":1
}
}
]
I want to write hibernate query with projection to return this response
The view data.
enter image description here
I tried the following query but it didn't get the right response
select new com.intelmatix.demo.service.dto.IngredientViewDTO( iview.id as id,\n"
+ "iview.name as name,\n"
+ "iview.date as date,\n"
+ "iview.quantity as quantity,\n"
+ "iview.consumption as consumption,\n"
+ "iview.demand as demand,\n"
+ "iview.max as max,\n"
+ "iview.safety as safety,\n"
+ "iview.type as type,\n"
+ "iview.pid as pid,\n"
+ "iview.productname as productname)\n"
+ "from IngredientView iview\n"
+ "group by
iview.id,iview.date,iview.quantity,iview.consumption,iview.demand,iview.type,iview.pid, iview.wastage \n

How can I use JSON logic in an AWS Cloudwatch custom event?

I'm trying to get a custom event setup in AWS CloudWatch. My goal is to trigger on either:
event:pullRequestMergeStatus AND isMerged:True
OR
event:pullRequestStatusChanged AND isMerged:False
I've tried using JSOM logical operators, such as:
{"$and":[{"event":"pullRequestMergeStatus"}, {"isMerged":"True"}]}
However either AWS doesn't support that or the syntax is incorrect. I've also tried adding an array into my detail part of the JSON string, but that ends with a syntax error, and adding 2 details entries just makes the bottom one stomp on the top.
Any input on how to setup logic, in an AWS CloudWatch custom event, to allow multiple sets of events like this?
My current, working but ugly, solution is to have 2 separate CloudWatch events, one per event/isMerged set.
e.g.
{
"source": [
"aws.codecommit"
],
"detail-type": [
"CodeCommit Repository State Change"
],
"detail": {
"event": [
"pullRequestStatusChanged"
],
"isMerged": [
"False"
]
}
}
You can target a Lambda function with the original CW Event, then have the Lambda make the decision (check multiple parameters in the JSON strings), then this Lambda can post an SNS message to a Topic which has a subscription to a Lambda etc -- the options are endless.
A sample code for Lambda may be as follows (Python) - Its purpose is different but you will get the idea:
import json
import boto3
from pprint import pprint
from datetime import datetime
def datetime_handler(x, y):
if isinstance(y, datetime):
return y.isoformat()
raise TypeError("Unknown type")
def alarm_handler(event, context):
pprint("Received the message and start to check alarm state..........")
json.JSONEncoder.default = datetime_handler
cw = boto3.client('cloudwatch')
response = cw.describe_alarms(ChildrenOfAlarmName='cw-alarm')
length = len(response["MetricAlarms"])
count = 0
flag = 0
messagetobesent = ""
print("length is " + str(length))
while (count < length):
check_msg = response["MetricAlarms"][count]
print("count is" + str(count))
currentvalue = check_msg["StateValue"]
print ("Current Alarm value is " + str(currentvalue))
if (currentvalue == 'ALARM'):
messagetobesent = messagetobesent + response["MetricAlarms"][count]["AlarmName"] + " ,"
flag = flag + 1
count = count + 1
#sendingdata = message["StateReason"]
pprint("Alarm reason is " + messagetobesent)
pprint("Alarm state is " + messagetobesent)
if (flag > 0):
sns = boto3.client('sns')
responseSNS = sns.publish(TopicArn='arn:aws:sns:aaaaaaaaa:sns',
Message=messagetobesent,
Subject='Notification from cw-alarm')
pprint("Send SNS notification!")
return("Alarm!")
else:
pprint("No alarm!")
return("No alarm!")

Karate -- JSON Response Parsing

Below is the JSON response I receive when I am hitting a particular web service:
[
{
"sId" : "0001",
"sName" : "abc1",
"sPlace" : "abc11"
}, {
"sId" : "0002",
"sName" : "abc2",
"sPlace" : "abc12"
}, {
"sId" : "0003",
"sName" : "abc3",
"sPlace" : "abc13"
}, {
"sId" : "0004",
"sName" : "abc4",
"sPlace" : "abc14"
}
]
I don't know which index has my expected values (I need to validate multiple values after identifying which has sId == '0003'), this is dynamic. Don't want to user hard coded value.
And match response.[3].sId == '0003'
because this will be changed next time.
I have two questions regarding this:
How can I pass response to java code and get the array index which having sId == '0003' so that I can use this index to validate?
How can I pass a variable value as an array index in response?
The code below is not working.
def ind = Java.type('karate.Utility.FindIndex')
response.['#ind'].sId == '0003'
karate uses json-path which allows writing conditions to read data from JSON.
example:
* def sId = "0003"
* def sValue = karate.jsonPath(response, "$[?(#.sId == '" + sId + "')]")
* match sValue[0] == {"sId" : "0003","sName" : "abc3","sPlace" : "abc13"}
now if there is a match in sId on the response JSON array, all such matches will be returned.
No need to do * match sValue[0].sId == "0003" as this is your filter
criteria
More about JSON path
online JSON path evaluator
karate doc refernce

how to read an attribute name in json in google script

I have the following object structure and for each record I need to display the attribute name and its value. for the following example, I need to display "Name " = xxx. The attribute name can be different for each json response. These are field names of a table so I cann't use hard coded names.
How do I read the attribute value?
I tried var propname = DataInObj.DataSet[0].Record[0].properties[1] but it didn't work. Pls help
object
REcord
+attributes
-0
Name xxx
Amount 100
+attributes
-1
Name yyy
Amount 200
See this other post: Iterate over an object in Google Apps script
Code goes like this:
var dict = { "foo": "a", "bar": "b" };
function showProperties(){
var keys = [];
for(var k in dict) keys.push(k+':'+dict[k]);
Logger.log("total " + keys.length + "\n" + keys.join('\n'));
}

DataTables Error: "Requested unknown parameter"

I'm new to the DataTables jquery plugin. After discovering that IE 8 had performance issues with Javascript I decided to change the way I use DataTables to do server side processing. I'm getting this error message when my JSP loads ( I'm using Spring 3 ):
DataTables warning (table id = 'results_table'): Requested unknown parameter '0' from the data source for row 0
I Googled around and found that many causes of that error message come down to malformed JSON so I found a way to output my JSON from my Spring 3 controller function to take a look at the JSON it makes and I changed my code to get it to be pretty close to what the DataTables site says it should look like.
Still no joy, still getting that error message.
The server side processing examples I found for DataTables didn't include code for specifying the columns used on the client side, so I assumed I don't need it. Do I?
Here are the relevant parts of my results.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ACME: search results in a nice DataTables.net Plugin</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css" />
<script language = "JavaScript" type = "text/javascript" src = "../nsd/js/jquery-1.7.js"></script>
<script language = "JavaScript" type = "text/javascript" src = "../nsd/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#results_table').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sScrollX": "600px",
"sServerMethod": "POST",
"sAjaxSource": "/acme/resultstable",
} );
} );
</script>
<form id="command" name="f" action="employee" method="post">
<div id = "results">
<table id = "results_table">
<thead>
<tr>
<th> </th>
<th>ID</th>
<th>NO_PRINT</th>
<th>Full Name</th>
<th>Email Address</th>
<th>Phone Number</th>
<th>Organization</th>
<th>Organization Code</th>
<th>Position</th>
<th>Employee Type</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
Here is the JSON response I've been sending to it:
{
"sEcho" : 1,
"iTotalRecords" : 1,
"iTotalDisplayRecords" : 1,
"aaData" : [ {
"person_id" : "888888",
"ID" : "999999",
"no_print" : " ",
"fullname" : "Obama, Willard",
"email_address" : "barry#whitehouse.gov",
"current_phone_number" : "303-867-5309",
"title" : " ",
"office" : " ",
"position" : "Contractor",
"empl_code" : "CONT"
} ]
}
Here is my Spring controller function I am using to send the JSON response via Jackson. This includes code to output my JSON so I can see what it looks like. Could the JSON it outputs to stdout and what I am sending back to DataTables be different?
#RequestMapping(value = "/resultstable", method = RequestMethod.POST)
public #ResponseBody LinkedHashMap resultstable(ModelMap model,
HttpSession session,
#RequestParam (required=true) int sEcho,
#RequestParam (required=true) int iDisplayStart,
#RequestParam (required=true) int iDisplayLength,
#RequestParam (required=true) int iColumns,
#RequestParam (required=true) int iSortCol_0,
#RequestParam (required=false)String sSortDir_0,
#RequestParam (required=true) String sSearch ) {
/*
**********************************************************************
** These come from the DataTables.net Jquery plugin on results.jsp
**********************************************************************
** sEcho, - just send it back, used by DataTables for synching
** iDisplayStart - index of the record to start with, ie 3 for the 3rd of 100 records
** iDisplayLength - number of records to send back starting with iDisplayStart
** iColumns - number of columns to be displayed in the table
** iSortCol_0 - the number of thee column to be sorted on
** sSortDir_0 - direction of sorting: asc or desc
** sSearch - from the search box, filter results further on this term
**********************************************************************
*/
String nextView = "results";
String usertype = (String)session.getAttribute("usertype");
Search search = new Search(usertype);
List<LinkedHashMap> records = null;
String results = null;
int number_of_records = (Integer)session.getAttribute("number_of_records_found");
ResultsView rv = new ResultsView();
ResultsScreenTableHolder rstrh = null;
SearchScreenDataHolder ssdh2 = (SearchScreenDataHolder)session.getAttribute("search_screen_data_holder");
ObjectMapper mapper = new ObjectMapper();
logger.debug("started");
logger.debug("sEcho, == " + sEcho );
logger.debug("iDisplayStart == " + iDisplayStart );
logger.debug("iDisplayLength == " + iDisplayLength );
logger.debug("iColumns == " + iColumns );
logger.debug("iSortCol_0 == " + iSortCol_0 );
logger.debug("sSortDir_0 == " + sSortDir_0 );
logger.debug("sSearch == " + sSearch );
try {
records = search.searchForAnEmployee(ssdh2,usertype,sSearch,"asc",
iSortCol_0,iDisplayStart,
iDisplayLength);
LinkedHashMap lhm= new java.util.LinkedHashMap();
lhm.put("sEcho", sEcho);
lhm.put("iTotalRecords",number_of_records);
lhm.put("iTotalDisplayRecords",9);
lhm.put("aaData",records);
// convert user object to json string, and save to a file
mapper.writeValue(new File("c:\\Downloads\\rstrh.json.txt"), lhm);
// display to console
logger.debug("My JSON: " + mapper.defaultPrettyPrintingWriter().writeValueAsString(lhm));
}
catch (Exception e) {
logger.debug("\n",e);
}
return lhm;
}// end function
I ran into the same warning as well, but the cause was different. I had null values in my data. The JSON format was correct, but DataTables does not know have a default rule for displaying nulls. The solution was to use the sDefaultContent property.
Sample aaData:
aaData: [
{ "Field1": "Foo", "Field2":null },
{ "Field1": "Bar", "Field2":null },
]
And then on the aoColumns, you can use the property as follows:
aoColumns: [
{ "mData": "Field1", sDefaultContent: "n/a" },
{ "mData": "Field2", sDefaultContent: "" }
]
This is not your current problem, but you may encounter this issue in the future.
Hope this was helpful.
I was having this same problem this morning. You need to have the aoColumns parameter and use mDataProp As in this:
https://gist.github.com/1660712
At least it solved my problem.
sDefaultContent option prevents displaying alert boxes only. Data tables wil not find the rule for displaying null values.
Changing null values in the table will eliminate this warning..
If it helps anyone I had a similar error because I had periods in my mRender function name:
My.Namespace.MyFunction(data, row);
This line:
var a = _fnSplitObjNotation( src );
Splits that into separate objects, which obviously generates an error.
Using
My_Namespace_MyFunction(data, row);
Additionally I noticed this error when passing a string function name instead of the JavaScript function object.
To avoid this error, your table number of "th" columns should equal to returning data columns(in numbers), in the above problem it is aaData.
"aaData" : [
[
"person_id" : "888888",
"ID" : "999999",
],
[
"person_id" : "8888889",
"ID" : "9999990",
]
]
This is correct format to return data from server side language.
I have solved my problem in same way.