Skip to content

Instantly share code, notes, and snippets.

@jonnywray
Last active September 3, 2021 15:16
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonnywray/636875 to your computer and use it in GitHub Desktop.
Save jonnywray/636875 to your computer and use it in GitHub Desktop.
Wicket FutureUpdateBehavior: allows asynchronous update of components.
import org.apache.wicket.ajax.AbstractAjaxTimerBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.util.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* An Ajax timer behavior that polls a future waiting for it to be done and
* once it is updates the component model, stops the timer and calls a callback function.
*
* @author Jonny Wray
*/
public abstract class FutureUpdateBehavior<T> extends AbstractAjaxTimerBehavior{
private final Logger logger = LoggerFactory.getLogger(FutureUpdateBehavior.class);
private transient Future<T> future;
public FutureUpdateBehavior(Duration updateInterval, Future<T> future) {
super(updateInterval);
this.future = future;
}
protected abstract void onPostSuccess(AjaxRequestTarget target);
protected abstract void onUpdateError(AjaxRequestTarget target, Exception e);
protected void onTimer(final AjaxRequestTarget target){
if(future.isDone()){
try{
T data = future.get();
getComponent().setDefaultModelObject(data);
stop(target);
onPostSuccess(target);
}
catch(InterruptedException e){
stop(target);
String message = "Error occurred while fetching data: "+e.getMessage();
logger.error(message, e);
onUpdateError(target, e);
}
catch(ExecutionException e){
stop(target);
String message = "Error occurred while fetching data: "+e.getMessage();
logger.error(message, e);
onUpdateError(target, e);
}
}
}
}
@chrisco484
Copy link

I like the idea of this panel.

I was wondering is it possible to have a Wicket component updated without polling? i.e. the server can send a message back to the browser to tell it to update a panel.

Is that what Wicket's Websocket impl is designed for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment