001    package net.databinder.cay;
002    
003    import net.databinder.CookieRequestCycle;
004    
005    import org.apache.cayenne.access.DataContext;
006    import org.apache.wicket.Response;
007    import org.apache.wicket.protocol.http.WebApplication;
008    import org.apache.wicket.protocol.http.WebRequest;
009    
010    /**
011     * Request cycle that binds Cayenne context to current thread. Context is
012     * rolled back at the end of the request if it contains uncomitted changes.
013     */
014    public class DataRequestCycle extends CookieRequestCycle implements CayenneRequestCycle {
015            private DataContext context;
016            public DataRequestCycle(WebApplication app, WebRequest request, Response response) {
017                    super(app, request, response);
018            }
019            /** Binds context to this thread. */
020            public void contextRequested() {
021                    if (context == null) {
022                            context = DataContext.createDataContext();
023                            DataContext.bindThreadDataContext(context);
024                    }
025            }
026            /** Unbinds, rolling back uncomitted changes if any. */
027            @Override
028            protected void onEndRequest() {
029                    if (context != null) {
030                            if (context.hasChanges())
031                                    context.rollbackChanges();
032                            context = null;
033                            DataContext.bindThreadDataContext(null);
034                    }
035            }
036    }