Setting a Timeout for a download link in Wicket? - java

I just started using Wicket (and really am not too familiar with a lot of web development) and have a question with regards to a download link. I have a web app that simply allows users to upload particular files, processes some of the information in the files, and offers downloads of different formats of the processed information. However this is really supposed to be a lite version of some software I am working on, so I really don't want to do much processing. I am wondering if there is a way to set something like a timeout for the download link, so that if the user clicks on the link and the processing takes longer than 20 seconds or so, it will simply quit the processing and send them an error instead. Thanks!

I agree with Xavi that the processing (and possible termination of the processing) should be done with a thread.
However, especially if it takes more than just a few seconds, it is much better to not just wait with the open connection, but rather to check at regular intervals to see whether the thread is done.
I'd do something like this:
Start the thread doing the actual work
Show a Panel that says "Processing your download" or something like that.
Attach an AbstractAjaxTimerBehavior to the panel with a timer duration of, say, 10 seconds or so.
In the timer behavior's onTimer method, check the state of the processing:
If it's still working, do nothing.
If it's canceled because it took too long, show a message like "Canceled" to the user, e.g. by replacing the panel or setting a warning label to visible.
If it's done, show a message like "Your download is starting" and start the download. See this document for how to do an AJAX response and at the same time initiate a download

To be able to cancel processing if it takes more than a given amount of time, it would be appropriate to perform it in a separate thread. This matter is addressed in the following question: How to timeout a thread.
Now for the Wicket part of it: If I understood what you're trying to achieve, you could for instance roll your own Link that would perform the processing, and respond with the results in case it doesn't timeout. In case the processing takes too much time, you can simply throw an error (remember to have a FeedbackPanel so that it can be shown).
The processing, or generation of the file to download, could be implemented in a LoadableDetachableModel for efficiency. See this question for more details: How to use Wicket's DownloadLink with a file generated on the fly?
For instance:
IModel<File> processedFileModel = new LoadableDetachableModel<File>(){
protected File load(){
// Implement processing in a separate thread.
// If it times out it could return null, for instance
}
}
Link<File> downloadLink = new Link<File>("yourID", processedFileModel) {
#Override
public void onClick() {
File processedFile = getModelObject();
if (file != null) {
IResourceStream rs = new FileResourceStream(file);
getRequestCycle().setRequestTarget(new ResourceStreamRequestTarget(rs));
} else {
error("Processing took too long");
}
}
};

Related

Vaadin7: Tracking whether a user is active (DOM Event Handler)

We are currently porting our app to vaadin 7 and I want to track wether a user has been active during the last 30s or so.
We used to track user activity in a custom CommunicationManager, but since this class is deprecated, I figured we might have to try differently.
I created an extension that I extend the UI with.
For simplicity's sake let's say, we count clicking and keyboard usage as user activity:
// this is the extend method in the extension connector
#Override
protected void extend (ServerConnector target) {
UIConnector uiConnector = (UIConnector) target;
VUI uiWidget = uiConnector.getWidget();
uiWidget.addDomHandler(this.keyPressed(), KeyPressEvent.getType());
uiWidget.addDomHandler(this.mouseClicked(), ClickEvent.getType());
}
The extension will then schedule a timer that will call the server via RPC every 30s, but only if the user has been active.
This Timer works. What does not work is the DOM Events, they never seem to reach the Event Listeners I added.
What am I doing wrong?
Based on your implementation, I would suggest you give Refresher add-on a try. It works in similar manner but gives you more control regarding polling interval, server-side listener. Plus, you don't have to maintain it.
The other alternative would be taking advantage of Vaadin polling support (see https://vaadin.com/wiki/-/wiki/Main/Using%20polling).

How to get list of current AJAX Calls in the WebPage and how to track programatically, if there are finished

I have an interesting testing issue.
My requirement is to do performance test on a web site.
Issue here to get the REAL time taking to load the web page (i am testing). The word REAL time i refer here as the total time taken to finished all the (initial) AJAX calls (with some response). I thought of using Page Load Event.
But this approach does not give the REAL time.
Any suggestions how to do it any reference to the information is also great!
My environment: Java and WedDriver.
Tag your request objects with a timestamp and subtract this from the systime when the corresponding response is received.
Depending on your methodology you could have generic Request/Response object with a <T> payload and a demuxer on the server side. These generic objects could then contain code to automagically register the time when sent and received and provide the time spent to the client. Aggregating time spent for an entire page to load is a bit trickier with this approach, but not near impossible I should think - the RPC proxy might keep track of that if requests are also tagged with the originating page.
if you were to provide some concrete example of your setup/code I might be able to be more precise.
Cheers,
As everyone said, WebDriver is not meant for Performance. However, see the following method that I use sometimes.
Following code will work if you can capture the performance against some particular webelement, can be a div or a span block.
1 Use any stopwatch. I am using apache stopwatch.
import org.apache.commons.lang3.time.StopWatch;
2 Initialize the variable
StopWatch timer = new StopWatch();
3 Start the timer and in next line navigate to your page. I prefer driver.navigate().to() than driver.get() as I feel it reduces other processing time to invoke a fresh URL.
timer.start();
driver.navigate().to(URL);
4 Wait for a particular element that can specify page loading finished. Once it appear, in next line stop the timer.
new WebDriverWait(driver, 10).until(ExpectedConditions. presenceOfElementLocated(By.className("demoClass")));
timer.stop();
System.out.println("timer.getTime() + " milliseconds");
Additional Note: If you want to know the loading time of Network calls of any particular webapge load, use webkit like phantomJS or thing like browsermobproxy. It will return network calls in HAR/JSON file. Parse those files and you may get your time.
Hope this helps.

Keeping a reference to a background thread in Grails?

My Grails 1.3.7 app needs to process big XML files, so I have a controller to which I upload the big file, and then I give the path of this file on the server to a background thread that does the processing so that I can return right away from the controller action.
For now, I am using the Grails Executor plugin and it works fine. I have an Upload domain object that is updated as the processing progresses (current status, number of processed elements, etc.). But now I have 2 more requirements:
when the application crashes or the server is shutdown, I would like to intercept that and update my Upload domain to say that the process was interrupted
I want the user to be able to interrupt the processing himself when clicking a link and possibly resume it from controller actions
Is there a way that I can persist a reference to my background task and intercept any interruption with java.util.concurrent framework (which is used by Executor plugin)?
And if I can't do it with util.concurrent, is it possible with other plugins/frameworks? I've had a look at Quartz for example, but I don't see how to do it.
I hate to answer without fully testing it, but the grails-executor plugin docs state that the callAsync method returns a java.util.concurrent.Future object.
This object can be used to do two things:
Determine if a process has completed or been canceled.
Cancel a running process (even interrupting if necessary).
In theory, you should be able to save this Future in your user's session somewhere. Then you could retrieve it later and use it to check the status and/or cancel the process as necessary.
Something like:
session.backgroundProcess = callAsync{...}
// later
def bgProc = session.backgroundProcess
if(bgProc && !(bgProc.done || bgProc.cancelled)) {
// process is still running
}
That's just the idea, it's not tested. I also don't know if there are issues with this leading to memory leaks. You'd need to make sure you detached the Future once the process is completed.

Want to create a synchronized data download in servlet action

I want to create a servlet method like below. In this method I want to perform some data download.So if request for data download comes I just do the download. If already a download is going on I want somehow the second request to wait till the first thread is done with download. Once the first thread is done with download the second thread can start automatically.
DoTheDownloadAction(){
}
How can i achieve the above requirement?
Considering you have a DownloadHelper class and in your Servlet you have created one instance of that class then you can do something like this :
DoTheDownloadAction() {
synchronized(downloadHelper) {
//Downloading something
}
}
Lets imagine you have a button called as "download" with id="download" in your jsp and you have this code in your javascript
var globalDownloadStatus = false;
jQuery(document).ready(function(){
jQuery('#download'(.click(function(){
if(globalDownloadStatus == true) {
alert('download already in progress, please wait');
return;
}
jQuery.get('yourservletpath', function(data){
alert('Download Complete');
});
});
});
Sounds like the perfect candidate for a semaphore, or (depending on the complexity and the downstream effects) the simpler way to affect the same change would be to synchronize the download code to a relevant key for your application.
Take in account that usually web-servers could distributed for scalability. Usually the appropriate solution is to synchronize via database locks. However for you maybe just enough to use synchronized java keyword on an object you want wait to.
Also, you are asking for a pessimistic lock. It's usually bad architecture design.

Java Thread Management and Application Flow

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 :).

Categories