How to execute code at the end of the application

Hello!

How can I execute a piece of code any time the application is stopped (i. e. I press Ctrl-C or invoke “mvn jetty:stop”) ?

I tried this:

public class MyApplication extends TPTApplication 
{
    @Override
    public final void close() {
        exportData();
        super.close();
    }
}

but it doesn’t work.

Thanks in advance

Dmitri

Hello,
The close method is actually called within vaadin as part of your event mechanism i.e. when clicking on an exit button etc

What you want is to call your logic when the http session ends via a session listener. When you shut down the application/web server i’m not certain whether the closing of a session will be signaled as part of the servlet container shutdown process (this is part of the application server or servlet container you are using has nothing to do with vaadin, for example for jetty something like this might be required http://docs.codehaus.org/display/JETTY/How+to+gracefully+shutdown).

So a way to implement such logic would be to use a httpsessionlistener which you register in your web.xml
i.e.


<listener>
        <listener-class>my.httplistener.MyHttpListener</listener-class>
</listener>

</web-app>

This MyHttpListener class will have to implement the javax.servlet.http.HttpSessionListener interface.

Hello!

Thanks for your answer.

I have a reference to a DI container in my application, which is created in the application class.

What is the best way to pass it to the HttpSessionListener sub-class/instance?

Thanks

Dmitri

Hello,
Dmitri use the httpsession
i.e.


public static final String PARAM_DI_CONTAINER = "PARAM_DI_CONTAINER";
....
((WebApplicationContext)getContext()).getSession().setAttribute(PARAM_DI_CONTAINER, diContainer);//if inside your Application class
....
//otherwise if called not inside your Application class then,
((WebApplicationContext)getApplication().getContext()).getSession().setAttribute(PARAM_DI_CONTAINER, diContainer);
.....

then in httpsessionlistener either in sessionCreated or sessionDestroyed you have access to the HttpSessionEvent
which can give you the session


....
httpSessionEvent.getSession().getAttribute(MyApplication_Or_Other_Class.PARAM_DI_CONTAINER);
....

Thanks, now it works!

Dmitri