I am developing web application with java-gwt. In one case i need to reload the browser tab, for that i used
"Window.Location.reload()", but it is reloading the browser continuosly, I do not know what might be the reason, Please look into the following code:
String existedLoginId = (String) Offline.get(GroupCookies.grpId.getCookieName());
String updatedLoginId = com.google.gwt.user.client.Window.Location.getParameter("groupId");
if (existedLoginId.equals(updatedLoginId)) {
LoginInfo.setSessionId(Cookies.getCookie(GroupCookies.dsessionId.getCookieName()));
} else {
**Window.Location.reload();**
}
Window.Location.reload() reloads the webpage once, as intended. The issue is that your code is being executed everytime.
If existedLoginId.equals(updatedLoginId) returns false, it will reload, then it will return false again, then it will reload ad nauseum.
If it is false, once, when it reloads, something should happen to make existedLoginId.equals(updatedLoginId), otherwise you will get a infinite loop.
Related
I have an API that on each call return me a random document from MongoDB collection.
This is code:
AtomicInteger countSummerCamps = new AtomicInteger();
#GetMapping("/getRandomSummerCamps")
public String getRandomSummerCamps(Model model) {
countSummerCamps.incrementAndGet();
if (getCountSummerCamps() <= adventureHolidaysService.countAdventureHolidays("summerCamps")) {
model.addAttribute("randomSummerCamps", adventureHolidaysService.findRandomAdventureHolidays("summerCamps"));
return "randomSummerCamps";
} else {
return "noMoreDoc";
}
}
What is my problem and how I tried.
So in this situation the program will return me four elements in HTML. And after that the program will show me a noMoreDoc page. That works fine. But the problem is when I refresh the page. It’s still page noMoreDoc even if I go on the home page and hit the API again. It’s still the noMoreDoc page. I want to avoid that and after the user refreshes the page and get back on /getRandomSummerCamps show the user random documents again on every call.
I tried to set counterSummerCamps.set(0) inside }else{, but I got "Unreachable statement".
Is there a way to fix this, so after the user got the noMoreDoc page and after the user get back on, to /getRandomSummerCamps show the user random documents again on each call?
If you call counterSummerCamps.set(0) after the return statement of else, you will get unreachable code. Try to set it before the return statement.
I created few test cases on Selenium using Java. Unfortunately when I click an element on the page, before I could move on to any other action, I have to wait till the page loads.
I have tried driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);. Unfortunately this creates another problem. Even if the page loads, it waits 30 seconds before it started testing on the page.
What I found the best way is to send ESCAPE key to stop page load.
Is there anyway I could check if an element exists and when it does, send ESCAPE key to the browser to stop page load?
This part is bugging my mind as I have to wait till page loads before Java reads the next line of the code so I can't send ESCAPE key to browser till the page actually stops loading.
Edit
I have just tried using a new thread to do the job but it seems driver is completely locked out, can't do any process on it before page stops loading.
I'm out of ideas for the moment but I believe there should be a way.
Using timeouts() is causing whole test case to stop.
First I'd like to say this isn't a best practice. The selenium click method states that if the click triggers a page load, selenium will do its best to block until the page is loaded. Instead of clicking via the click method you could try sending the click event via JavaScript. Then wait for the element like normal.
You can try driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); It is supposed to throw an error after timeout is over. I have never used it but maybe you can try and catch this error and continue with your test. But your page could end up in an unstable state with everything not loading and test interacts with elements.
I did it in C#, scenario is the same elsewhere.
Define driver like this:
var firefoxOptions = new FirefoxOptions();
firefoxOptions.PageLoadStrategy = PageLoadStrategy.None;
driver = new FirefoxDriver(firefoxOptions);
PageLoadStrategy.None means when open a URL, continue to next line regardless of the results and do not wait to load the page.
Usually, it takes some seconds to load a page and element appears, suppose I'm waiting for email_user element to appears:
int user_emailID = 0, popupAlert = 0;
do
{
float timeToWait = 0;
driver.Navigate().GoToUrl("https://stackoverflow.com");
do
{
await Task.Delay(500);
timeToWait += 0.5F;
user_emailID = driver.FindElements(By.XPath("//input[#id=\'user_email\']")).Count;
}
while (user_emailID == 0 && timeToWait < 10);
if (user_emailID == 1)
{
//Element exists now!do something and don't wait for page to load completely
}
}
while (user_emailID != 1);
More explanation: when open a URL, first loop check the presence of element every 0.5 second, if it appears, the loop stops. If after 10 seconds it couldn't find the element, the page will reloaded !!
Hope this get you the idea.
Remember, exception must not happen in your codes !!
I want to check the following (on ie8):
After clicking on a link, popup window is launched, then I want to check if flash content inside has loaded.
For some reason waitForPopUp does not work, it just keeps waiting and times out but I've solved it this way:
selenium.waitForCondition("selenium.getAllWindowTitles().length > 1;", "30000");
String windowID = selenium.getAllWindowTitles()[1];
selenium.selectWindow(windowID);
Then I want to check if the flash content is there before checking anything on it (webpage is very slow and the popup takes a while to show something)
selenium.waitForCondition("selenium.isElementPresent(\"//*[#id='flashcontent']\");",
"30000");
FlashSelenium flashApp = new FlashSelenium(selenium, "flashClient");
assertTrue ( flashApp.PercentLoaded() == 100 );
I've tried hundreds of ways to do this but none works,
I've also tried to check if a text is present but nothing, always times out even if the webpage is completely loaded.
For some reason everything works OK if I execute step by step in the debugger :S
I gave this a little more thought.
There is no way to test an object if it is truely loaded and the flash app is ready and initialized.
The only true way of letting selenium know the flash object is loaded and ready is for flash to use the ExternalInterface method and call a JavaScript function that will assign a var and then have selenium test that var on a timer.
Example<br/>
// in JavaScript
var isFlashLoaded = false;
function cbIsLoaded( ){
isFlashLoaded = true;
}
// in AS3
var retVal:int = ExternalInterface.call("cbIsLoaded");
I have been running into intermittent errors with some java selenium-rc tests which I think are related to a page which has an ajax poll and automatically refreshes when some condition is reached on the server. In this scenario, I have no way of asking selenium to wait for the page to load, and so I run into a bunch of random "Couldn't access document.body" errors.
So, is there some way I can cause selenium to gracefully handle this situation? If not, is there some way I could detect whether the user is selenium from the page's javascript, and disable the automatic refresh?
If it helps at all, the javascript code in the page looks something like...
var ajax = new Ajax(url, {
update: state,
method: 'get',
onComplete: function(message) {
if (some_condition) {
window.location.replace(unescape(window.location));
}
}
});
One solution might be to always use a waitForCondition using isElementPresent before attempting to interact with the application under test. You could put the following method in a superclass to keep your tests more readable. Alternatively you could create helper methods for common Selenium commands that perform this wait.
/** Waits for an element to be present */
public static void waitForElementToBePresent(String locator) {
session().waitForCondition("var value = selenium.isElementPresent('" + locator.replace("'", "\\'") + "'); value == true", "60000");
}
You may also want to wait for the element to be visible, as waiting for it to just be present isn't always enough (imagine a textbox that is always present but hidden until a certain condition). You can combine this with the above method:
/** Waits for an element to be visible */
public static void waitForElementToBeVisible(String locator) {
waitForElementToBePresent(locator);
session().waitForCondition("var value = selenium.isVisible('" + locator.replace("'", "\\'") + "'); value == true", TIMEOUT);
}
Incidentally, the WebDriver (Selenium 2) team are working on having implicit waits, specifically to address AJAX issues where elements are not present immediately.
My solution was to disable the refresh in javascript by wrapping it in something like the following...
var isSeleniumActive = parent.seleniumAlert;
if (isSeleniumActive) {
alert("Selenium");
} else {
alert("Not selenium");
}
I'm not sure if the seleniumAlert function here is likely to sick around forever, so be aware if you're taking this that you may be relying on internal selenium implementation details of selenium.
There i was facing the same problem and i use a single line of code and it helps.
i was getting the error about the page is getting auto refresh
plus this warning:
-1490472087141 Marionette WARN Using deprecated data structure for setting timeouts
all i use is
Thread.sleep(2000)
and it worked for me.
I think that you can pause, or use a click and wait. There are a few good articles on the google. Good luck.
Edit for your comment:
How about the waitFor command?
In my GWT application, I want to ask a user confirmation when he navigates out of the current application, i.e. by entering a URL or closing the browser. This is typically done by registering a ClosingHandler and setting the desired dialog message in the onWindowClosing method. This seems to work well.
However, if the user tries to navigate say to http://www.gmail.com (by typing it in the URL bar) and hits Cancel to indicate he doesn't want to navigate, then my app keeps running but the browser's URL bar keeps indicating http://www.gmail.com. This causes a number of problems later in my application and will give the wrong result if the user bookmarks the page.
Is there a way to automatically reset the URL when the user presses Cancel?
Or, alternatively, is there a way to detect the user pressed the Cancel button? If so, is there a way to set the URL without triggering a ValueChangeEvent? (I could add some logic to prevent this, but I'd rather use a built-in mechanism if it exists.)
Not sure if this works but did you try: History.newItem(History.getToken(), false); to reset the URL? It does set the history token without triggering a new history item.
I managed to do this. It looks like GWT DeferredCommand are executed after the confirmation window has been closed. This, combined with Hilbrand's answer above, give me exactly what I want. Here is exactly what I do:
public final void onWindowClosing(Window.ClosingEvent event) {
event.setMessage(onLeaveQuestion);
DeferredCommand.addCommand( new Command() {
public void execute() {
Window.Location.replace(currentLocation);
}
});
}
Where currentLocation is obtained by calling Window.Location.getHref() every time the history token changes.
I solved this by creating a custom PlaceController and replacing the token in the url. Not an ideal solution but it works!
if (warning == null || Window.confirm(warning)) {
where = newPlace;
eventBus.fireEvent(new PlaceChangeEvent(newPlace));
currentToken = History.getToken();
} else {
// update the url when user clicks cancel in confirm popup.
History.replaceItem(currentToken, false);
}