I'm a bit new to using Spring Expression Language but I'm trying to see what is the best way to check a that a Boolean value is not null and true?
For type "Display" there is a property "removeMessage" which is of type java.lang.Boolean.
So I want to first check that this value is not null and that it is true. Based on if this is true or not I will either return an empty string or a calculatedMessage.
I am currently checking with below expression:
display?.removeMessage != null && display?.removeMessage ? '' : display.calculatedMessage
While this works, I was hoping to find a more nicer way to do the null and true check. I was thinking/hoping for something more like how we would check normally such as e.g. BoolenUtils.isTrue(value) (apache), or even just checking like Boolean.TRUE.equals(value) which takes care of the null check.
Just having this should work , and already include your null check:
display?.removeMessage ? null : display.calculatedMessage
Related
target = ObjectUtils.defaultIfNull(getCustomerByAddressID(sourceData, supportParam),
createNewCustomer(supportParam));
I am passing 2 functions to ObjectUtils.defaultIfNull. First is function which returns Customer if found by AddressID else null, second param is function which create new Customer.
After execution I am seeing 2 Customers, debug is showing even after getCustomerByAddressID(sourceData, supportParam) returns not null value - createNewCustomer(supportParam) is getting executed.
Is this issue because of Code formatting or what am I missing? Should I use Optional.ofNullable().orElse() instead of ObjectUtils.defaultIfNull?
You can use Optional.ofNullable(getCustomerByAddressID(sourceData, supportParam)).orElseGet(() -> createNewCustomer(supportParam)) if you don't want createNewCustomer(supportParam) to be invoked, even if getCustomerByAddressID(sourceData, supportParam) is null
You should use
target = Optional.ofNullable(getCustomerByAddressID(sourceData, supportParam))
.orElseGet(() -> createNewCustomer(supportParam));
Because both Optional.ofNullable().orElse() and ObjectUtils.defaultIfNull() which uses ternary operator internally, always call "orElse" part.
I know it could be a duplicate, but still posting my question as i could not find the exact answer what i am looking for. I am having an json object (or string) like below.
String str = "{
"status" : {
"timestamp" : "2020-04-30T01:00:00 000Z"
"error" : 0,
"error_message" : null,
"execution" : "completed"
}
}
";
I will get the a same kind of response from my REST API testing, but after each call the 'timestamp' key will be having a dynamic date and time value with the time respect to the call made. And here i compare my expect json with the actual json as a whole sting comparison using JSONAssert. As the timestamp value is different it always fails for me.
So my question is before i do any comparison, i would like to remove the 'timestamp' key and its value from json to compare and so it will pass my case. I tried by using JsonPath also, but did not works. Any help on this please?
JSONAssert allow you to make a customized comparator while doing asserts [1].
In your case it's easy as:
JSONAssert.assertEquals(expectedJson,
actualJson,
new CustomComparator(JSONCompareMode.LENIENT,
skips("status.timestamp","another.json.path", ...)));
private static Customization[] skips(String... jsonPaths) {
return Arrays.stream(jsonPaths)
.map(jsonPath -> Customization.customization(jsonPath, (o1, o2) -> true))
.toArray(Customization[]::new);
}
Here we are defining CustomComparator, with customization which takes JSONPath (status.timestamp) and takes a ValueMatcher (lambda) which compares two values for that specific JSONPath.
In our case we will always return true, which will effectively skips the value (no matter with what we are comparing that value it's always true).
Edit: As you can see CustomComparator's constructor takes varargs of Customizations, hence you can provide more than one field to be ignore from comparison.
[1] http://jsonassert.skyscreamer.org/apidocs/org/skyscreamer/jsonassert/Customization.html
[2] http://jsonassert.skyscreamer.org/apidocs/org/skyscreamer/jsonassert/comparator/CustomComparator.html
I have a project (in Java and Angular) about designing a financial website to manage some data like contracts. In our databases, some columns can't be null.
In SQL for example, it's very easy to set that condition, and for that example, I have to respect that rules :
ID NUMBER NOT NULL ,
USER_ID NUMBER NOT NULL,
PARENT_ID VARCHAR2(280) NULL,
PARENT_LEGAL_NAME VARCHAR2(280) NULL ,
POLICY_BUCODE VARCHAR2(280) NOT NULL,
POLICY_ID VARCHAR2(280) NOT NULL,
POLICY_TYPE_CODE VARCHAR2(280) NOT NULL ,
POLICY_ACTIVE_STATUS NUMBER(1),
POLICY_LEGAL_NAME VARCHAR2(280) NOT NULL ,
PA_FLAG NUMBER(1) DEFAULT 0 NOT NULL ,
RISK_FLAG NUMBER(1) DEFAULT 0 NOT NULL ,
CC_FLAG NUMBER(1) DEFAULT 0 NOT NULL ,
VISIBLE_FLAG NUMBER(1) DEFAULT 1 NOT NULL
The problem is that I had to ensure that in java-side... and I had a lot of difficulty to fix that.
The idea for that is that if we read a Contract object from an array of Contract objects (like when someone want to enter new data in a table in SQL), we will check for that. So, if we are reading an array of contacts and a contract doesn't have a required field (for example POLICY_BUCODE), we will just skip it and jump to the next element. We can do that easily with a for loop.
The problem is that I got lost in the long code and I don't how to find those variables... For example, a Contract object has an ID which is an object of a class called ID!!!! Which I found very strange and I got very confused about that... I found also strange that some classes has name with underscore (ex : Coreinfo_.java)
So, I tried to do something like that :
for (contract in contractList) {
if (contract.getId() == null || contract.getId().getId() == null || contract.getId().getBuCode == null) {
//don't do anything, just jump to the next element
} else {
//the rest of other codes
}
The problem is that I'm not good enough in Java and I REALLY got lost in that long code. With my example, I "think" that i'm ensuring non null values for ID, POLICY_ID and POLICY_BYCODE but i'm not sure at all...
Here is my plunker with some of our java classes :
https://plnkr.co/edit/BylPPjXLJ7PY0aBP5xPF
Can you just give me a little help to do that? at least by understanding the model and where are those variables located?
The problem is that I had to ensure that in java-side... and I had a
lot of difficulty to fix that.
You can set the constraints/rules even in Java classes like how you did in your SQL.
For setting the constraints on Java class variables, you need to use javax.validation.constraints package rules.
For your Contract class #NotNull can be set on id variable as shown below :
public class Contract {
#NotNull
private long id;
//other variables
}
You can apply various constraints like #Min, #Max, etc.. as well and you can look here for more details.
I'm trying to create a string with a character length restriction of 12 for my JBOSS Seam project. The string must either be 12 characters or blank. My length annotation is correct which is the following:
#Length(min = 12,max = 12)
However when I try to put a null value in there I get an InvalidStateException: validation fail error. Any ideas how to allow this?
Null value for String and empty String are not the same thing. You are passing a null value (not a String of length 0). Check this out:
Difference between null and empty ("") Java String
Also, you should try out #Size(min=,max=).
Well I decided to not rely on the #Length annotation and instead created my own custom validator class to do the job and that worked out well. Thanks anyway!
Please see this Expression Language
styleClass="#{obj.validationErrorMap eq null ? ' ' :
obj.validationErrorMap.contains('key')?'highlight_field':'highlight_row'}"
Even if the map is null, highlight_row style is getting applied.
So I changed to
styleClass="#{empty obj.validationErrorMap ? ' ' :
obj.validationErrorMap.contains('key')?'highlight_field':'highlight_row'}"
Even then, highlight_row is getting applied.
if the map is empty OR null I dont want any style to be applied.
Any help? and reasons for this behaviour?
Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"