I'm working on big liferay project and I have the following problem :
everytime when something is loading, processing etc. I should change cursor to waiting gif. It's easy when using Ajax, but in many cases here I don't use it. So I thought maybe if I could catch any action phase I'd somehow set cursor to wait at the beginning of action method and then turn back to regular 'auto' at the end.
Is that possible ? I don't like this 'solution' but I can't think of any better. Currently I have div with loading image in my jsp which is then removed by jquery document.ready() - not satisfied at all, because all the proccessing have been performed earlier in action phase.
I'd appreciate any suggestions.
Well, if you are not using Ajax, it might be difficult to achieve what you are looking for.
You could start showing the throbber ("loading image") once the link on the first page is clicked, keep it on the next page and remove it on document.ready().
But you'll still have a few ms or seconds without throbber, during page load.
If the processing time is really long, you could do the following :
The idea is to use a thread for the processing. A reference to the thread is stored in server's session. When the link is clicked :
Display a page with the loading image and start the processing in the thread
Poll the server every X second to check if the thread (in session !) is done
When the thread is done, display the result.
Related
I have a ArrayList with urls pointing to html files that need to be downloaded and displayed. Right now I'm just looping through the ArrayList and downloading all files on the Main Thread.
After all files have been downloaded, I display the first html page in a jxbrowser. I also made "next" and "prev" buttons so the user can cycle through the html pages.
Currently I need to wait till all Files have been downloaded and sometimes it takes a really long time.
I would like to download all the Files in seperate Threads and to display the first page after it has been downloaded. Other files would continue to download in background. If the user clicks on next button and the Thread downloading that file isn't completed, user should get a an error Message.
I have no clue how to accomplish this as i´m a beginner in java so any help would be appreciated.
Giving an error to a user when they perform a correct action like pressing your Next button is poor interface design.
I suggest creating dummy page content that explains that target URL is loading. Create as many of these pages as you have URLs in your list of downloads. Display those dummy pages to the user initially.
Store the content for those dummy pages in a thread-safe Map implementation, such as ConcurrentHashMap. The key for the map should be the URLs to be downloaded. The values of the map would be the page content. Initially all the values are the dummy page. Then using background threads, you replace each dummy page with the content of a successfully downloaded page.
Use an executor service to perform the downloads. Submit one instance of the downloader for each URL, as the Runnable/Callable task.
As each task completes, put the page content into the map to replace the dummy page.
Then use the JavaFX mechanism to ask the user-interface thread to update its display, transitioning from the dummy page to the downloaded page. Never access or modify the user-interface widgets from a background thread. For more info, search Stack Overflow for posts such as Complex concurrency in JavaFX: using ObservableLists and Properties from multiple worker threads.
Remember to gracefully shut down the executor service. Otherwise its backing pool of threads may continue to run indefinitely like a zombie 🧟♂️.
All of these topics have been addressed many times already on Stack Overflow. So search to learn more.
I have a Dynamic web page that refreshes and loads new data. I am using Selenium and I need to wait till the page has finished rendering before I can continue checking the page. I have seen many posts about waiting for the page to load or using explicit waits (implicit wait could solve the problem but is very unelegant and not fast enough). The problem with using explicit waits is not having any info on what will come up after the refresh. I have seen some solutions talking about waiting for all the connections to the server to end but that will not promise me that the actual UI has finished rendering.
What I need is a way to know if a page has finished to render (not load!!)
First of all you DO KNOW what sctructure will come after the page will load. You don't know what tags were not on the page, but you know what DOM will look like. That's why usually it's worst practice to test with page text, but a good one to have a website tested by DOM only. So, depending on what structure appears on the page you will need to have explicit ways waiting for specific tags will appear on the page.
One more solution (but as I told it's not really the best practice) is to wait for document.readystate is "complete". This state will not help in every situation, but if you have something still loading on the page, in more then half cases it will not return complete. So, you should have some kind of implicit state that is executing:
string readyState = javascript.ExecuteScript("if (document.readyState) return document.readyState;").ToString();
and then checking:
readyState.ToLower() == "complete";
btw if you will use protractor as an angular js application test executor, it's waiting for angular page loaded by default, or in some difficult situations you can use:
browser.waitForAngular();
OR do something in a callback
button.click().then(function() {
// go next step
});
I have had similar problem with the product I am testing. I had to create special functions for click,click_checkbox,sendKeys and getText for example. These include try catch methods for cathcing NoSuchElement StaleElementReference exceptions. Also it retries if the actions fail, like sending the wrong text.
document.readyState
This isnt enough for you. It only waits for the DOM to load. WHen the HTML tag are loaded, it returns "complete". So you have to wait for each individual item.
This works for me well with dynamically rendered websites - I do not have a time constraint in getting the data as it would run in background for me, if efficiency is an issue may be this is not the solution for you (50s is a huge time for any website to load after the ready state is completed) :
Wait for complete page to load
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));
Make another implicit wait with a dummy condition which would always fail
try {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'" + "This text will always fail :)" + "')]"))); // condition you are certain won't be true
}
catch (TimeoutException te) {
}
Finally, instead of getting the html source - which would in most of one page applications would give you a different result , pull the outerhtml of the first html tag
String script = "return document.getElementsByTagName(\"html\")[0].outerHTML;";
content = ((JavascriptExecutor) driver).executeScript(script).toString();
I am calling a thread in JSP page and that thread keeps on running. I want this thread to terminate when I close the JSP page. Wow would that be possible ?
my code put it in body tag JSP:
<%
Thread Ping=new PingThread();
Ping.Start();
%>
Thanks in Advance
You mean close it when the user closes the window? There is no event fired for that, so you can't do it. You could do that via JavaScript by making an Ajax call when the user closes the window, but it's probably not going to work anyway.
The doubt that comes to mind is: why would you do such an horrible thing as starting a thead in a JSP page? By spamming the F5 button someone could obtain the easiest DOS attack of the history! Rethink your application to avoid such a solution (launching threads blindly on request, not just the fact that you do it from a JSP).
If you start a thread from a JSP, it is to impossible to guarantee that the thread will be stopped when the user exits the page.
No notification is sent from the client to server when the user closes or moves away from a plain HTML page. None whatsoever.
You could include some javascript in a web page to perform an AJAX call to your server when the user closes the window or moves to a different page. However, there are scenarios where call won't get made; e.g.
the user's machine dies,
the user's browser crashes,
the user has javascript turned off,
the user sets a breakpoint in your code,
etcetera.
And even if the call is made, there's no guarantee that it won't get lost due to some transient networking problem.
The end result will be that your server has an orphaned thread that will keeping doing whatever it is doing (in this case, pounding some other machine with ICMP packets) until you kill your web container.
That's a really, really bad idea.
You can use the Javascript beforeunload or unload events to determine that the window is being closed, though which one you use and how depends on precisely what it is you want to do.
As Anthony Grist's answer says (sort of), you can embed javascript in your web page to be executed when the browser detects that the current browser window is being closed. Refer to this page for more details about DOM Events and their handling.
Notes:
This stuff works whether or not the page is a JSP. (For instance ... it would work if the page was plain HTML ... provided that there was something on the server end to deal with the notification.)
This event handling is performed in the users web browser.
The server side doesn't get told about the window closing, unless the event handlers send an (AJAX) request to the server to tell it.
As I said in an answer to a previous question, there event handling can be disabled on the client side by the user.
As I said in an answer to a previous question, there is no guarantee that the AJAX request will actually make it back to the server.
All of this adds up to the fact that any server side handling of the window close event is unreliable. And there's no solution to that. Not in theory, and not in practice.
you could enclose the above in another loop which is set to true by the jsp page throuh ajax call on a time to time basis. if the jsp page is not setting the value to true then you can safely assume that the browser is closed. But you would need an identifier for your thread like say session id or ip of the user.
I have a Java application that downloads information (Entities) from our server. I use a Download thread to download the data.
The flow of the download process is as follows:
Log in - The user entity is downloaded
Based on the User Entity, download a 'Community' entities List and Display in drop down
Based on Community drop down selection, Download and show 'Org Tree' in a JTree
Based on Node selection, download Category entities and display in drop down
Based on Category selection, download Sub Category entities and display in drop down
Based on Sub Category selection download a large data set and save it
The download occurs in a thread so the GUI does not 'freeze'. It also allows me to update a Progress Bar.
I need help with managing this process. The main problem is when I download entity data I have to find a way to wait for the thread to finish before attempting to get the entity and move to the next step in the app flow.
So far I have used a modal dialog to control flow. I start the thread, pop up a modal and then dispose of the modal when the thread is finished. The modal/thread are Observer/Observable the thread does a set changed when it is finished and the dialog disposes. Displaying a modal effectively stops the flow of the application so it can wait for the download to finish.
I also tried just moving all the work flow to Observers. All relevant GUI in the process are Observers. Each update method waits for the download to finish and then calls the next piece of GUI which does its own downloading.
So far I found these two methods produce code that is hard to follow. I would like to 'centralize' this work flow so other developers are not pulling out their hair when they try to follow it.
My Question is: Do you have any suggestions/examples where a work flow such as this can be managed in a way that produces code that is easy to follow?
I know 'easy' is a relative term and I know my both my options already work but I would like to get some ideas from other coders while I still have time to change it.
Thank you very much.
You might want to look into using the Future interface.
Stop by http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html
It has all you might need to make these tasks easier.
I think the most common method to do this in recent versions of Java is to use SwingWorker:
http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html
It allows you to fire off background tasks and gives you a convenient done() method that executes on the Swing EDT.
You have to create a "model" for your view, representing the current state of your application. For a tree e.g. it is reasonable to show a "Loading"-node when someone openes a treenode, because else the GUI hangs on opening a node.
If the loading thread finishes loading the node, the "Loading"-node is replaced with the results of the asynchronous action. This makes it easy to open multiple nodes in parallel, because the worker threads all are just responsible for a single child node.
Similar when downloading something: The workers then update a download progress. The downloads-Dialog of Firefox comes to mind here.
Good GUIs aren't easy :).
I've been playing with Java Servlets and Ajax a bit, and I've got
a situation on which I would really appreciate advice.
Let's say I have HTML page with a start and stop buttons, and as a result of clicking start button,
overridden doGet (or doPost) method on a servlet is invoked which computes something that takes a long time to complete.
(e.g. a giant loop, or even Infinite loop, doesn't matter, I'm interested in concepts here).
So, I'm asking you:
1.What would be my options to kill / shut down / halt / exit
doGet method whan I hit stop button on a web page?
Do I use threading here, or there is simpler way?
I take it that using System exit is not a very good idea, right? ;)
2.So, let's say I implement code for stopping doGet method.
What would happen If I hit start on one browser(e.g.IE), and while this long
computation takes place open new tab or other browser(e.g.Firefox) and open same url
and hit stop? Would that stop my original computation? Is there any easy way to avoid this?
I know that questions are a bit off, as I'm just starting with server-side of things. :)
Any suggestions would be greatly appreciated!
your stop handler can set a flag in the session context, which the long-running thread will occasionally check and exit if necessary.
you can avoid the multiple browser issue, by generating a unique task id each time the page is loaded. then you can only start or stop a specific task. this id can be a key in the session.
I think you need some kind of new process started after you submit request and this process should answer responses during runtime (showing progress for example via AJAX). Also it should check if there is new request with stop command. Page should be AJAX one with progress/result/stop button.