Checking if a button is disabled or not - java

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;
}

Related

I can't set a string in a TextView in an Android app (using Java)

I'm building a simple calculator Android app in Java that will receive 2 numbers as inputs and when the user presses one of the 4 action buttons (+, -, *, /) the exercise and it's solution will appear in the bottom of the screen inside a TextView in this format:
{num1} {action} {num2} = {solution}
I tried to declare a string and form the exercise's string in it and in the end I used "setText" to change the TextView but instead of showing the full exercise when I run the app it shows something like "androidx.appcompat.widget.AppCom".
Here is an example for the string I form when the user clicks on the + button:
exerciseStr = etNum1.toString() + " + " + etNum2.toString() + " = " + String.valueOf(Integer.valueOf(etNum1.getText().toString())+Integer.valueOf(etNum2.getText() + ""));
Does anybody know what the issue may be?
You should call getText() befor calling toString():
exerciseStr = etNum1.getText().toString() + " + " + etNum2.getText().toString() + " = " + String.valueOf(Integer.valueOf(etNum1.getText().toString())+Integer.valueOf(etNum2.getText() + ""));
Change it to like this.
exerciseStr = etNum1.getText().toString() + " + " + etNum2.getText().toString() + " = " + String.valueOf(Integer.valueOf(etNum1.getText().toString())+Integer.valueOf(etNum2.getText() + ""));

Parse html content for a value

I receive a Http response after a call as Html String and I would like to scrape certain value stored inside the ReportViewer1 variable.
<html>
....................
...........
<script type="text/javascript">
var ReportViewer1 = new ReportViewer('ReportViewer1', 'ReportViewer1_ReportToolbar', 'ReportViewer1_ReportArea_WaitControl', 'ReportViewer1_ReportArea_ReportCell', 'ReportViewer1_ReportArea_PreviewFrame', 'ReportViewer1_ParametersAreaCell', 'ReportViewer1_ReportArea_ErrorControl', 'ReportViewer1_ReportArea_ErrorLabel', 'ReportViewer1_CP', '/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100', '', 'ReportViewer1_EditorPlaceholder', 'ReportViewer1_CalendarFrame', 'ReportViewer1_ReportArea_DocumentMapCell', {
CurrentPageToolTip: 'STR_TELERIK_MSG_CUR_PAGE_TOOL_TIP',
ExportButtonText: 'Export',
ExportToolTip: 'Export',
ExportSelectFormatText: 'Export to the selected format',
FirstPageToolTip: 'First page',
LabelOf: 'of',
LastPageToolTip: 'Last Page',
ProcessingReportMessage: 'Generating report...',
NoPageToDisplay: 'No page to display.',
NextPageToolTip: 'Next page',
ParametersToolTip: 'Click to close parameters area|Click to open parameters area',
DocumentMapToolTip: 'Hide document map|Show document map',
PreviousPageToolTip: 'Previous page',
TogglePageLayoutToolTip: 'Switch to interactive view|Switch to print preview',
SessionHasExpiredError: 'Session has expired.',
SessionHasExpiredMessage: 'Please, refresh the page.',
PrintToolTip: 'Print',
RefreshToolTip: 'Refresh',
NavigateBackToolTip: 'Navigate back',
NavigateForwardToolTip: 'Navigate forward',
ReportParametersSelectAllText: '<select all>',
ReportParametersSelectAValueText: '<select a value>',
ReportParametersInvalidValueText: 'Invalid value.',
ReportParametersNoValueText: 'Value required.',
ReportParametersNullText: 'NULL',
ReportParametersPreviewButtonText: 'Preview',
ReportParametersFalseValueLabel: 'False',
ReportParametersInputDataError: 'Missing or invalid parameter value. Please input valid data for all parameters.',
ReportParametersTrueValueLabel: 'True',
MissingReportSource: 'The source of the report definition has not been specified.',
ZoomToPageWidth: 'Page Width',
ZoomToWholePage: 'Full Page'
}, 'ReportViewer1_ReportArea_ReportArea', 'ReportViewer1_ReportArea_SplitterCell', 'ReportViewer1_ReportArea_DocumentMapCell', true, true, 'PDF', 'ReportViewer1_RSID', true);
</script>
...................
...................
</html>
The value is a90a0d41efa6429eadfefa42fc529de1 and this is in the middle of this content:
'/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100',
Whats the best way I can parse this value using Java?
Parse the HTML with String class
public class HtmlParser {
public static void main(String args[]){
String result = getValuesProp(html);
System.out.println("Result: "+ result);
}
static String PIVOT = "Telerik.ReportViewer.axd";
public static String getValuesProp(String json) {
String subString;
int i = json.indexOf(PIVOT);
i+= PIVOT.length();
//', chars
i+=2;
subString = json.substring(i);
i = subString.indexOf("'");
i++;
subString = subString.substring(i);
i = subString.indexOf("'");
subString = subString.substring(0,i);
return subString;
}
static String html ="<html>\n" +
"\n" +
"<script type=\"text/javascript\">\n" +
" var ReportViewer1 = new ReportViewer('ReportViewer1', 'ReportViewer1_ReportToolbar', 'ReportViewer1_ReportArea_WaitControl', 'ReportViewer1_ReportArea_ReportCell', 'ReportViewer1_ReportArea_PreviewFrame', 'ReportViewer1_ParametersAreaCell', 'ReportViewer1_ReportArea_ErrorControl', 'ReportViewer1_ReportArea_ErrorLabel', 'ReportViewer1_CP', '/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100', '', 'ReportViewer1_EditorPlaceholder', 'ReportViewer1_CalendarFrame', 'ReportViewer1_ReportArea_DocumentMapCell', {\n" +
" CurrentPageToolTip: 'STR_TELERIK_MSG_CUR_PAGE_TOOL_TIP',\n" +
" ExportButtonText: 'Export',\n" +
" ExportToolTip: 'Export',\n" +
" ExportSelectFormatText: 'Export to the selected format',\n" +
" FirstPageToolTip: 'First page',\n" +
" LabelOf: 'of',\n" +
" LastPageToolTip: 'Last Page',\n" +
" ProcessingReportMessage: 'Generating report...',\n" +
" NoPageToDisplay: 'No page to display.',\n" +
" NextPageToolTip: 'Next page',\n" +
" ParametersToolTip: 'Click to close parameters area|Click to open parameters area',\n" +
" DocumentMapToolTip: 'Hide document map|Show document map',\n" +
" PreviousPageToolTip: 'Previous page',\n" +
" TogglePageLayoutToolTip: 'Switch to interactive view|Switch to print preview',\n" +
" SessionHasExpiredError: 'Session has expired.',\n" +
" SessionHasExpiredMessage: 'Please, refresh the page.',\n" +
" PrintToolTip: 'Print',\n" +
" RefreshToolTip: 'Refresh',\n" +
" NavigateBackToolTip: 'Navigate back',\n" +
" NavigateForwardToolTip: 'Navigate forward',\n" +
" ReportParametersSelectAllText: '<select all>',\n" +
" ReportParametersSelectAValueText: '<select a value>',\n" +
" ReportParametersInvalidValueText: 'Invalid value.',\n" +
" ReportParametersNoValueText: 'Value required.',\n" +
" ReportParametersNullText: 'NULL',\n" +
" ReportParametersPreviewButtonText: 'Preview',\n" +
" ReportParametersFalseValueLabel: 'False',\n" +
" ReportParametersInputDataError: 'Missing or invalid parameter value. Please input valid data for all parameters.',\n" +
" ReportParametersTrueValueLabel: 'True',\n" +
" MissingReportSource: 'The source of the report definition has not been specified.',\n" +
" ZoomToPageWidth: 'Page Width',\n" +
" ZoomToWholePage: 'Full Page'\n" +
" }, 'ReportViewer1_ReportArea_ReportArea', 'ReportViewer1_ReportArea_SplitterCell', 'ReportViewer1_ReportArea_DocumentMapCell', true, true, 'PDF', 'ReportViewer1_RSID', true);\n" +
" </script>\n" +
"\n" +
"</html>";
}
I would read the text a line at a time like how most files are read. Because the format will always be the same, you look for a line that begins with the characters "var ReportViewer1." Then you know you have found the line you want. You may need to strip some white space, although it will always be formatted with the same whitespace too (up to you really.)
When you have the line, use the String .split() method to split that line into an array. There are nice delimiters there to split on ... "," or " " or ", " ... again, see what works best for you.
Test the split up line parts for '/app/Telerik.ReportViewer.axd' ... the next member of your split array will be the value you are looking for.
Again, the formatting will always be the same, so you can rely on that to find your variable. Of course, study the html text to make sure it does always follow the same format within the line you are investigating, but looking at it, I assume it probably does.
Again, find your line ... split it on a delimiter ... and use some logic to find the element you are after in the split up line parts.

Java and if NULL

I have never done anything in java before so I really am a newb but while building the program I have ran into a snag that i just can't figure out. I will try to explain and show to the best of my abilities.
Here is what I am building
The UI
Here is the code I have so far to make it work.
private void jButtonGenerateActionPerformed(java.awt.event.ActionEvent evt) {
String ObjectName = jtObjectName.getText();
String ObjectBase = jcbBaseNPC.getSelectedItem().toString();
String NPCName = jtNPCName.getText();
String MinLevel = jtMinLevel.getText();
if (MinLevel != null && MinLevel.isEmpty())
MinLevel = MinLevel.replace(MinLevel, "minLevel" + MinLevel);{
}
//Alignment Combo Box Start
String Alignment = jcbAlignment.getSelectedItem().toString();
if (Alignment.contains("Good")) {
Alignment = Alignment.replace("Good", "255");
}
if (Alignment.contains("Neutral")) {
Alignment = Alignment.replace("Neutral", "127");
}
if (Alignment.contains("Evil")) {
Alignment = Alignment.replace("Evil", "0");
}
//Alignment Combo Box End
// Print to Output Box
jaOutput.append("object" + " " + ObjectName + " " + "of" + " " + ObjectBase +
"\n\tproperties" + "\n\tname" +" " + "\"" + NPCName + "\"" + MinLevel
);
What I can not understand it how to check to see if there is something entered in a String and if there is I need to add to it so the output looks like this.
minLevel 1100
maxLevel 1500
only thing I will be adding is the numbers so i need to add something like
minLevel + MinLevel
and if it is empty just skip it all together. If I add it to the append and its empty I will just get minLevel and i can't have it like that.
Any tips would be great.
Thank you all
Donald

Unable to Select option from dropdown using JavascrtptExecutor

Can anyone provide me a failsafe(ish) method for selecting text from dropdowns on this page I am practicing on?
https://www.club18-30.com/club18-30
Specifically, the 'from' and 'to' airport dropdowns. I am using the following code:
public void selectWhereFrom(String query, String whereFromSelect) throws InterruptedException {
WebElement dropDownContainer = driver.findElement(By.xpath(departureAirportLocator));
dropDownContainer.click();
selectOption(query,whereFromSelect);
}
public void selectOption(String query, String option) {
String script =
"function selectOption(s) {\r\n" +
" var sel = document.querySelector(' " + query + "');\r\n" +
" for (var i = 0; i < sel.options.length; i++)\r\n" +
" {\r\n" +
" if (sel.options[i].text.indexOf(s) > -1)\r\n" +
" {\r\n" +
" sel.options[i].selected = true;\r\n" +
" break;\r\n" +
" }\r\n" +
" }\r\n" +
"}\r\n" +
"return selectOption('" + option + "');";
javaScriptExecutor(script);
}
This seems to successfully populate the box with text but when I hit 'Search' I then receive a message saying I need to select an option, suggesting it has not registered the selection?
I would rather avoid JavaScriptExecutor but haven't been able to make these Selects work with a regular Selenium Select mechanism
I would set up a function for each dropdown, one for setting the departure airport and another for setting the destination airport. I've tested the code below and it works.
The functions
public static void setDepartureAirport(String airport)
{
driver.findElement(By.cssSelector("div.departureAirport div.departurePoint")).click();
String xpath = "//div[contains(#class, 'departurePoint')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
public static void setDestinationAirport(String airport)
{
driver.findElement(By.cssSelector("div.destinationAirport div.airportSelect")).click();
String xpath = "//div[contains(#class, 'destinationAirport')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
and you call them like
driver.get("https://www.club18-30.com/club18-30");
setDepartureAirport("(MAN)");
setDestinationAirport("(IBZ)");
I would suggest that you use the 3-letter airport codes for your search, e.g. "(MAN)" for Manchester. That will be unique to each airport but you can use any unique part of the text.

iterate over a set and create a string containing HTML

I have the following code that is used in the Image gallery generating program Jalbum to generate all keywords used for the images in the gallery.
Set allKeywords = new HashSet();
for (AlbumObject ao : currentObjects) {
XmpManager mgr = ao.getXmpManager();
if (mgr != null) {
allKeywords.addAll(mgr.getKeywordSet());
}
}
//get the Iterator
Iterator itr = allKeywords.iterator();
while(itr.hasNext())
out.println(itr.next());
My question is when out.print:
out.println(itr.next());
how can I add html to each individual keyword? I basically want to outprint:
keyword
I am a newbie in this realm so please be gentle!
out.println("" + itr.next() + "");
If you want to call iterator.next() two times
out.println("<a href=\"#\" class=\"label list2\""
+ " data-filter=\"" + "." + itr.next() + "\">"
+ (itr.hasNext() ? itr.next() : "") + "</a>");
For your requirement I hope mgr.getKeywordSet() returns string
String str = itr.next();
System.out.println("<a href=\"#\" class=\"label list2\""
+ " data-filter=\"" + "." + str + "\">" + str + "</a>");

Categories

Resources