public void printManagerAvailable(Manager mgr) {
System.out.println(" Is Manager object available : " + mgr!=null);
}
Output:
true
Why output is only true here? I'm expecting:
Is Manager object available : true
because it thinks that you are saying " Is Manager object available : " + mgr is all to the left of != null. In other words, it does " Is Manager object available : " + mgr first and then it compares " Is Manager object available : [Object:Manager]" != null.
Do this.
Manager mgr = new Manager();
mgr.setChangeClass(5);
mgr.setChangeClockIn(10);
System.out.println(" Is Manager object available : " + (mgr!=null));
Other answers cover what is happening, this is why it is happening:
The order of operator precedence in Java puts addition, +, ahead of equality, !=.
It's important to realize that it's not caused by left-to-right ordering here.
So what you have is applying the operators in the order like so:
("Is null : " + mgr) != null
And to fix it you can use brackets to force the precedence the other way:
"Is null : " + (mgr != null)
Try using this line of code.
System.out.println(" Is Manager object available : " + (mgr == null ? "is null" : "not null"));
Related
How can I write that if more compact using java 8?
Optional.ofNullable(city).ifPresent(c -> {
if (!city.equalsIgnoreCase(district)) {
address.setCity(district + ", " + c);
}
});
As Eran commented, you can avoid the spurious detour over Optional by just directly checking for null:
if (city != null && !district.equalsIgnoreCase(city)) {
address.setCity(district + ", " + city);
}
Why am I getting null pointer exception in this code?
BigDecimal test = null;
String data = "";
try {
System.out.println(test==null?"":test.toString());
data = test==null?"":test.toString();
System.out.println(data);
data = data + " " + test==null?"":test.toString(); // catching null pointer in this line
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
It's evaluating the expressions as:
data = (data + " " + test==null)?"":test.toString();
so, since data + " " + test is not null, it attempts to call test.toString() even when test is null.
Change
data = data + " " + test==null?"":test.toString();
to
data = data + " " + (test==null?"":test.toString());
Since Java 8 there is also an alternative way to deal with potential null references: Optional
To prevent an NPE while converting a BigDecimal to a String you can use an Optional like that:
String data = Optional.ofNullable(test).map(BigDecimal::toString).orElse("");
This way you don't need to check test several times if it is null. Having test once wrapped in an Optional you could work on being safe, that any conversion (map) will be performed only if test is not referencing null.
my issue i am having is that selenium is saying that the next arrow button is enabled when it is disabled/grayed out. what i am trying to do is this
1 click next arrow button
2 sleep for 5 seconds
3 check if disabled
4 click next arrow button
5 check if disabled
( loop repeat steps 1 -5)
if button is disabled break do while loop
my code that is not working is below
PS_OBJ_CycleData.Nextbtn(driver).click();
Thread.sleep(5000);
WebElement element = driver.findElement(By.id("changeStartWeekGrid_next"));
if (element.isEnabled()) {
System.out.println("Good next arrow enabled");
} else {
System.out.println("next arrow disabled");
PS_OBJ_CycleData.Cancelbtn(driver).click();
break dowhileloop;
}
my console output is "Good next arrow enabled" instead of going to the else statment.
Button HTML is here
<div id="changeStartWeekGrid_next" class="paginationButton" disabled="disabled" data-xpal="xpath-selected">
<a tabindex="0" href="#" id="changeStartWeekGrid_next_link" onclick="var registry = require('dijit/registry'); registry.byId('changeStartWeekGrid').next(); return false;">
<span class="icon-pagination-next"></span>
</a>
</div>
As you can see the button is actually disabled there another way to check is button is really disabled? Any help would be appreciated.
this is an additional picture of the inspected element
The documentation for isEnabled.
Sadly, using the isEnabled method doesn't work in this case, as stated by the documentation:
This will generally return true for everything but disabled input elements.
A proper alternative is using JavaScript to check for the attribute's existence, and its value. You can inject JavaScript through the executeScript method of the webdriver classes. The first argument is the script, all following arguments are passed to the script, accessible as arguments[i], ...
For example:
Boolean disabled = driver.executeScript("return arguments[0].hasAttribute(\"disabled\");", element);
I In this case since i did not have an actual button I needed to find it attribute to see if it was disabled or not.
PS_OBJ_CycleData.Nextbtn(driver).click();
Thread.sleep(4000);
// check is arrow button is disabled
if (driver.findElement(By.id("changeStartWeekGrid_next")).getAttribute("disabled") != null) {
PS_OBJ_CycleData.Cancelbtn(driver).click();
break dowhileloop;
}
You can check it with this simple code:
Boolean isbutton;
isbutton=button1.isEnable()
Make sure you have the correct element. I've wasted hours trying to figure out why an element was enabled when it shouldn't have been, when I was actually looking at the wrong one! Inspecting the element in the browser did not help, because it wasn't the same element that the java code was looking at. The following code turned out to be helpful:
System.out.println("Actual element=" + describeElement(yourElement));
public static String describeElement(WebElement element) {
String result = "";
if (element == null ) {
log.error("Could not describe null Element");
return "null";
}
// Look for common attributes, such as id, name, value, title, placeholder, type, href, target, role, class,
String id = element.getAttribute("id");
String name = element.getAttribute("name");
String value = element.getAttribute("value");
String title = element.getAttribute("title");
String placeholder = element.getAttribute("placeholder");
String type = element.getAttribute("type");
String href = element.getAttribute("href");
String target = element.getAttribute("target");
String role = element.getAttribute("role");
String thisClass = element.getAttribute("class");
result = "WebElement [tag:" + element.getTagName() + " text:'" + limit(element.getText()) + "' id:'" + id + "' " +
(StringUtils.isEmpty(name) ? "" : (" name:'" + name + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" value:'" + value + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" title:'" + title + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" placeholder:'" + placeholder + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" type:'" + type + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" href:'" + href + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" target:'" + target + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" name:'" + name + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" role:'" + role + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" class:'" + thisClass + "' ")) +
" isDisplayed: " + element.isDisplayed() +
" isEnabled: " + element.isEnabled() +
" isSelected: " + element.isSelected() + "]";
return result;
}
I have a string input in my Mule flow. It passes through my Groovy Script and outputs XML. I originaly had the script followed by an XSLT converter to remove empty nodes and set the indent to "no" in the output tag. But now I removed it as I cannot use it in conjunction with my script if I want to keep the special characters (see previous question here).
Instead I now check each value before printing the nodes. But the problem I have is my XML needs to be unindented in order to work with my InDesign project I adapt the XML for. I lost that ability when I removed the XSLT so I fixed one problem but created another.
I found the method getPrinter(), I used it with the setAutoIndent(false) but it didn't change anything to the output and created no errors. Not to sure where to use it.
Here's my script :
public Boolean isEmpty(value){
if(value.toString().trim() == "" || value.toString().trim() == '' || value == null)
return true;
}
root = new XmlSlurper(false,false).parseText(payload)
if(root.name() == 'GetActivitiesResponse')
startEach = root.children().children()
else
startEach = root.children()
def xml = new StringWriter().with { w -> new groovy.xml.MarkupBuilder(w).with {
mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
escapeAttributes = false
getPrinter().setAutoIndent(false);
"w_import_saisie_web"() {
startEach.each { p -> "w_evenement"() {
if(!isEmpty(p.PresentationDate))
"w_dates"{ mkp.yieldUnescaped (p.PresentationDate.toString() + "
") }
if(!isEmpty(p.SubTitle))
"w_contexte"{ mkp.yieldUnescaped (p.SubTitle.toString() + "
") }
//if(!isEmpty(p.SubTitle))
"w_nom_evenement"{ /*p.GEVT_Type*/ mkp.yieldUnescaped ("Nom evenement" + "
") }
if(!isEmpty(p.Name))
"w_titre"{ mkp.yieldUnescaped (p.Name.toString() + "
")}
if(!isEmpty(p.ShortDescription) || !isEmpty(p.Teaser))
"w_texte"{mkp.yieldUnescaped (p.ShortDescription.toString() + p.Teaser.toString() + "
")}
p.SubEvents.children().each { q -> "w_bloc_sous_evenement"() {
if(!isEmpty(q.PresentationDate) || !isEmpty(q.Name))
"w_sous_eve_titre"{ mkp.yieldUnescaped (q.PresentationDate.toString() + q.Name.toString() + "
")}
if(!isEmpty(q.ShortDescription) || !isEmpty(q.Teaser) || !isEmpty(q.WebDescription))
"w_sous_eve_desc"{mkp.yieldUnescaped (q.ShortDescription.toString() + q.Teaser.toString() + q.WebDescription.toString() + "
")}
}
}
if(!isEmpty(p.Site) || !isEmpty(p.PresentationHours))
"w_coordonnees"{ mkp.yieldUnescaped ("teeeessdfsdfsdfst" + p.Site.toString() + ' - ' + p.PresentationHours.toString() + "
")}
}
}
}
}
w.toString()
}
Add an IndentPrinter when you create the MarkupBuilder.
def xml = new MarkupBuilder(new IndentPrinter(new PrintWriter(writer), "", true))
See this question:
groovy.xml.MarkupBuilder disable PrettyPrint
I tried a bunch of different things to see if setAutoIndent was effective (setting it before passing the IndentPrinter to the MarkupBuilder for example) and it didn't seem to have any effect. So, like you, I'm wondering about its purpose.
Realised I was searching too hard... just added this simple line to the toString() at the end...
w.toString().replaceAll(">\\s+<", "><").trim();
I found below sysout in our project and it is always printing 'Not Null'. Even I have initialize the Val variable or not, it is printing 'Not Null'.
Also why it is not printing the "mylog" in front? Can someone explain?
String Val = null;
System.out.println("mylog : " + Val!=null ? "Not Null" :"Is Null");
Use paranthesis:
System.out.println("mylog : " + (Val!=null ? "Not Null" :"Is Null"));
Otherwise it gets interpreted as:
whatToCheck = "mylog: " + val
System.out.println(whatToCheck !=null ? "Not Null" : "Is Null"
which evaluates to something like "mylog: null" or "mylog: abc".
And that is always a non-null String.
"mylog : " + Val!=null
will be evaluated to
"mylog : null"
which is not null.
Parenthesis for the rescue.
Why is null converted to the String "null"? See the JLS - 15.18.1.1 String Conversion:
... If the reference is null, it is converted to the string "null"
Also it's very important to understand that this is happening because of Java operator precedence.
Use brackets around your expression:
System.out.println("mylog : " + (Val!=null ? "Not Null" :"Is Null"));
Check it following way:
String Val = null;
System.out.println("mylog : " + (Val!=null ? "Not Null" :"Is Null"));
Output :
mylog : Is Null