How to check if a key exists in the payload and use that in a choice condition - mule

I want to check if a key exists in the first element(object) of the array.
When I write the following:
flowVars.payloadStored[0].data!=null
inside the when condition of choice, I am getting the following error:
Execution of the expression 'flowVars.payloadStored[0].data!=null' failed. -> [Error: null pointer: flowVars.payloadStored[0].data],[Near : {... flowVars.payloadStored[0].data ....}], ^,[Line: 1, Column: 1] -> ",
Even when trying
flowVars.payloadStored[0].['data']!=null
I am still getting an error:
[Error: unterminated string literal],[Near : {... flowVars.payloadStored[0].['data']!=null ....}], ^,[Line: 1, Column: 35]"
Any clues, how to do that?

It is tempting to do all mapping in one line but in reality you are doing chain of references. You should be sure that each link in the chain does exist.
Based on the message I guess that payloadStored may not exist or it is not an array or it has no elements in the array. To refer first element in the array you should be sure all is true. So, right DW transformation is not elegant but bulletproof should look like this to be sure you will not have null pointer exception:
%dw 1.0
%output application/json
---
{
data: flowVars.payloadStored[0].['data']
} when flowVars.payloadStored is :array and sizeOf (flowVars.payloadStored) > 0
otherwise
{
data: "Not Available"
}
So your logic should look like this:
flowVars.payloadStored is :array and sizeOf (flowVars.payloadStored) > 0 and flowVars.payloadStored[0].['data']!=null
Example is here https://simpleflatservice.com/mule4/DoubleAndTripleCheckTheInput.html

Related

Swift 5.7 RegexBuilder: Nested TryCapture - transform / Mapping Output?

Here in this example I tried to capture two Int values and then capture them together as a struct. This gives a "Thread 1: signal SIGABRT" error.
(NOTE: I know that my example could be fixed by simply not nesting the Captures and handling the pattern matching differently. This is just simplified example code for the sake of this question.)
let intCapture = Regex {
TryCapture(as: Reference(Int.self)) {
OneOrMore(.digit)
} transform: { result in
return Int(result)
}
}
let mainPattern = Regex {
TryCapture(as: Reference(Floor.self)) {
"floor #: "
intCapture
" has "
intCapture
" rooms"
}transform: { ( stringMatch, floorInt, roomInt ) in
return Floor(floorNumber: floorInt, roomCount: roomInt)
}
}
struct Floor {
let floorNumber: Int
let roomCount: Int
}
let testString = "floor #: 34 has 25 rooms"
let floorData = testString.firstMatch(of: mainPattern)
After looking into it, I found that in the mainPattern's 'transform' the 'floorInt' and 'roomInt' are what is causing the problem.
The funny part is that when you look at the 'Quick Help'/Option+click, it shows that they are both type Int! It knows what is there but you are not able to capture it!
Further, when I erase one of them, let's say 'floorInt', it gives this error:
Contextual closure type '(Substring) throws -> Floor?' expects 1 argument, but 2 were used in closure body
So really, even though for SOME reason it does know that there are two captured Int values there, it doesn't let you access them for the sake of the transform.
Not deterred, I was helped out in another question by a very helpful user who pointed me to the Evolution submission where they mentioned a .mapOutput, but sadly it seems this particular feature was never implemented!
Is there no real way to create a new transformed value from nested transformed values like this? Any help would be greatly appreciated.

Can't Emit an Empty Value with yaml-cpp

I would like to emit an empty value but when I assign an empty string to be emitted the output is not technically empty.
Code Snippet:
YAML::Emitter out;
std::string name;
out << YAML::Key << "name";
out << YAML::Value << name;
Expected yaml Output:
name:
Actual yaml Output:
name: ""
As you can see I have an empty string defined and I expect the yaml output to effectively be empty.
Is this intended behavior? If so is there a way to work around this? I'm aiming to have my entire yaml output be quote free.
The YAML
name:
doesn't have a string value for the key name; it's actually a null value. See, e.g., an online parser here; the canonical YAML representation is:
!!map {
? !!str "name"
: !!null "null",
}
yaml-cpp is trying to ensure that what you told it ("write this empty string") is how the resulting YAML will be parsed, so it's writing the empty string as "".
If you want to write a null value, then either don't write a value, or write YAML::Null. The latter (I believe) will produce
name: ~
which is the canonical form of null.

For spirit::x3, what is the right way to deal with unknown symbols?

A newbie for x3... The code is adapted from the roman.cpp in the x3 tutorial. Suppose I have a symbol table like below:
struct car_models_ : x3::symbols<char, unsigned>
{
car_models_()
{
add
("sedan", 1)
("compact", 2)
("suv", 3)
;
}
} car_models;
Then parse,
char const *first = "Model: sedan";
char const *last = first + std::strlen(first);
parse(first, last, "Model: " >> car_models[action()]);
If there is new model not listed in the symbol table, what would be the right way to handle it? Is there a way to add a wildcard as the last entry in the symbol table, and then somehow pass an unknown model to action (e.g., number "0" in this case)?
There is no way to do it inside the symbol table itself. One possibility is:
auto ext_car_models = car_models | (x3::omit[*x3::lower] >> attr(0))
Then to parse:
parse(first, last, "Model: " >> ext_car_models[action()]);
Ignoring the attribute for a moment, your symbol table is effectively syntactic sugar for:
x3::string("sedan") | "compact" | "suv"
So, handling an unknown string in that position would need to be handled the same way. You will need to define a parser that defines what a model string looks like. Possibly *x3::lower

What could be a reason for `_localctx` being null in an antlr4 semantic predicate?

I'm using list labels to gather tokens and semantic predicates to validate sequences in my parser grammar. E.g.
line
:
(text+=WORD | text+=NUMBER)+ ((BLANK | SKIP)+ (text+=WORD | text+=NUMBER)+)+
{Parser.validateContext(_localctx)}?
(BLANK | SKIP)*
;
where
WORD: [\u0021-\u002F\u003A-\u007E]+; // printable ASCII characters (excluding SP and numbers)
NUMBER: [\u0030-\u0039]+; // printable ASCII number characters
BLANK: '\u0020';
SKIP: '\u0020\u0020' | '\t'; // two SPs or a HT symbol
The part of Parser.validateContext used to validate the line rule would be implemented like this
private static final boolean validateContext(ParserRuleContext context) {
//.. other contexts
if(context instanceof LineContext)
return "<reference-sequence>".equals(Parser.joinTokens(((LineContext) context).text, " "));
return false;}
where Parser.joinTokens is defined as
private static String joinTokens(java.util.List<org.antlr.v4.runtime.Token> tokens, String delimiter) {
StringBuilder builder = new StringBuilder();
int i = 0, n;
if((n = tokens.size()) == 0) return "";
builder.append(tokens.get(0).getText());
while(++i < n) builder.append(delimiter + tokens.get(i).getText());
return builder.toString();}
Both are put in a #parser::members clause a the beginning of the grammar file.
My problem is this: sometimes the _localctx reference is null and I receive "no viable alternative" errors. These are probably caused because the failing predicate guards the respective rule and no alternative is given.
Is there a reason–potentially an error on my part–why _localctx would be null?
UPDATE: The answer to this question seems to suggest that semantic predicates are also called during prediction. Maybe during prediction no context is created and _localctx is set to null.
The semantics of _localctx in a predicate are not defined. Allowable behavior includes, but is not limited to the following (and may change during any release):
Failing to compile (no identifier with that name)
Using the wrong context object
Not having a context object (null)
To reference the context of the current rule from within a predicate, you need to use $ctx instead.
Note that the same applies for rule parameters, locals, and/or return values which are used in a predicate. For example, the parameter a cannot be referenced as a, but must instead be $a.

Why the map values change even if they are not pointers - Golang

I'm trying to test a method. Its signature is func (gv *myType) Update(all map[string][]SomeType) error
Although the test fails (the expected value doesn't match the received value) I've found that also the map it receives(allSub) is "updated" after the method is evaluated. Here is the code:
t.Logf("allsub %v", allSub)
if err := gv.Update(allSub); err != nil {
t.Error(err)
return
}
if !reflect.DeepEqual(egv, gv) {
t.Errorf("allSub %v", allSub)
return
}
The output
mth_test.go:265: allsub map[b:[{1 3 3}] a:[{1 0 0} {1 2 0}]]
mth_test.go:271: allSub map[a:[{1 2 0}]]
As you can see on t.Logf("allsub %v", allSub) we have map[b:[{1 3 3}] a:[{1 0 0} {1 2 0}]] and then after the evaluation if !reflect.DeepEqual(egv, gv) allSub becomes allSub map[a:[{1 2 0}]]. This drives me crazy and I'm wondering how is this possible? allSub is not a pointer.
Map, slice, channels are reference types. The spec is in-process to become clearer about this but basically the implementation of these builtin types entails a reference to an underlying data structure.
So you can consider that an object of type map is actually a reference to an associative array.
Effective Go has a little paragraph on it :
https://golang.org/doc/effective_go.html#maps
I quote :
Like slices, maps hold references to an underlying data structure. If you pass a map to a function that changes the contents of the map, the changes will be visible in the caller.