/* Copyright 2004-2005 Graeme Rocher
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.codehaus.groovy.grails.orm.hibernate.support;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil;
import org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractSavePersistentMethod;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.sitemesh.GrailsContentBufferingResponse;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.WebRequest;

/**
 * Extends the default spring OSIVI and doesn't flush the session if it has been set
 * to MANUAL on the session itself.
 *
 * @author Graeme Rocher
 * @since 0.5
 */
public class GrailsOpenSessionInViewInterceptor extends OpenSessionInViewInterceptor {
    private static final String IS_FLOW_REQUEST_ATTRIBUTE = "org.codehaus.groovy.grails.webflow.flow_request";

    @Override
    public void preHandle(WebRequest request) throws DataAccessException {
        GrailsWebRequest webRequest = GrailsWebRequest.lookup();
        final boolean isFlowRequest = webRequest != null && webRequest.isFlowRequest();
        if (isFlowRequest) {
            webRequest.setAttribute(IS_FLOW_REQUEST_ATTRIBUTE, "true", WebRequest.SCOPE_REQUEST);
        }
        else {
            super.preHandle(request);
            SessionFactory sessionFactory = getSessionFactory();
            SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory);
            Session session = sessionHolder.getSession();
            GrailsHibernateUtil.enableDynamicFilterEnablerIfPresent(sessionFactory, session);
        }
    }

    @Override
    public void postHandle(WebRequest request, ModelMap model) throws DataAccessException {
        final boolean isFlowRequest = request.getAttribute(IS_FLOW_REQUEST_ATTRIBUTE, WebRequest.SCOPE_REQUEST) != null;
        if (isFlowRequest) {
            return;
        }

        try {
            super.postHandle(request, model);
        }
        finally {
            SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.getResource(getSessionFactory());
            Session session = sessionHolder.getSession();
            session.setFlushMode(FlushMode.MANUAL);
        }
    }

    @Override
    public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
        try {
            final boolean isWebRequest = request.getAttribute(IS_FLOW_REQUEST_ATTRIBUTE, WebRequest.SCOPE_REQUEST) != null;
            if (isWebRequest) {
                return;
            }

            request = (WebRequest) RequestContextHolder.currentRequestAttributes();
            if (!(request instanceof GrailsWebRequest)) {
                super.afterCompletion(request, ex);
                return;
            }

            GrailsWebRequest webRequest = (GrailsWebRequest) request;
            HttpServletResponse response = webRequest.getCurrentResponse();
            if (!(response instanceof GrailsContentBufferingResponse)) {
                super.afterCompletion(request, ex);
                return;
            }

            GrailsContentBufferingResponse bufferingResponse = (GrailsContentBufferingResponse) response;
            // if Sitemesh is still active disconnect the session, but don't close the session
            if (!bufferingResponse.isActive()) {
                super.afterCompletion(request, ex);
                return;
            }

            try {
                Session session = SessionFactoryUtils.getSession(getSessionFactory(), false);
                if (session != null) {
                    session.disconnect();
                }
            }
            catch (IllegalStateException e) {
                super.afterCompletion(request, ex);
            }
        } finally {
            AbstractSavePersistentMethod.clearDisabledValidations();
        }
    }

    @Override
    protected void flushIfNecessary(Session session, boolean existingTransaction) throws HibernateException {
        if (session != null && session.getFlushMode() != FlushMode.MANUAL) {
            super.flushIfNecessary(session, existingTransaction);
        }
    }
}

@@ -698,16 +698,70 @@
 esponse;
+%0Aimport javax.servlet.http.HttpServletResponseWrapper;
 %0A%0Aimport
@@ -4201,41 +4201,122 @@
     
-if (!(response instanceof GrailsC
+GrailsContentBufferingResponse contentBufferingResponse = getContentBufferingResponse(response);%0A            if (c
 onte
@@ -4334,17 +4334,24 @@
 Response
-)
+ == null
 ) %7B%0A    
@@ -4441,114 +4441,8 @@
  %7D%0A%0A
-            GrailsContentBufferingResponse bufferingResponse = (GrailsContentBufferingResponse) response;%0A
     
@@ -4549,17 +4549,24 @@
    if (!
-b
+contentB
 uffering
@@ -5114,32 +5114,486 @@
        %7D%0A    %7D%0A%0A
+    private GrailsContentBufferingResponse getContentBufferingResponse(HttpServletResponse response) %7B%0A        while(response instanceof HttpServletResponseWrapper) %7B%0A            if(response instanceof GrailsContentBufferingResponse) %7B%0A                return (GrailsContentBufferingResponse) response;%0A            %7D%0A            response = (HttpServletResponse) ((HttpServletResponseWrapper) response).getResponse();%0A        %7D%0A        return null;%0A    %7D%0A%0A
     @Override%0A  

fix for GRAILS-8450 "Grails 2.0 RC3 spring security org.hibernate.LazyInitializationException: could not initialize proxy - no Session"