package com.angkorteam.mbaas.server.spring;

import com.angkorteam.mbaas.server.bean.GroovyClassLoader;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by socheat on 12/12/16.
 */
public class ServletRequestListener implements javax.servlet.ServletRequestListener {

    private Connection connection;

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        if (this.connection != null) {
            try {
                this.connection.commit();
            } catch (SQLException e) {
                try {
                    this.connection.rollback();
                } catch (SQLException e1) {
                }
            }
            try {
                this.connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            this.connection = null;
        }
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        ServletContext servletContext = sre.getServletContext();
        ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        GroovyClassLoader classLoader = applicationContext.getBean(GroovyClassLoader.class);
        if (Thread.currentThread().getContextClassLoader() instanceof GroovyClassLoader) {
        } else {
            Thread.currentThread().setContextClassLoader(classLoader);
        }
        DataSource dataSource = applicationContext.getBean(DataSource.class);
        try {
            this.connection = dataSource.getConnection();
            this.connection.setAutoCommit(false);
        } catch (SQLException e) {
        }
    }
}

@@ -678,38 +678,232 @@
 ) %7B%0A            
-try %7B%0A
+boolean closed = true;%0A            try %7B%0A                closed = this.connection.isClosed();%0A            %7D catch (SQLException e) %7B%0A            %7D%0A            if (!closed) %7B%0A                try %7B%0A    
                 
@@ -924,24 +924,28 @@
 n.commit();%0A
+    
             
@@ -979,38 +979,46 @@
                 
+   
+ 
 try %7B%0A
+    
                 
@@ -1045,24 +1045,28 @@
 rollback();%0A
+    
             
@@ -1105,34 +1105,42 @@
                 
-%7D%0A
+    %7D%0A    
             %7D%0A  
@@ -1141,38 +1141,46 @@
   %7D%0A            
+    
 try %7B%0A
+    
                 
@@ -1208,32 +1208,36 @@
 ();%0A            
+ 
+   
 %7D catch (SQLExce
@@ -1263,16 +1263,20 @@
         
+    
 e.printS
@@ -1292,38 +1292,62 @@
 ();%0A            
+ 
+   
 %7D%0A    
+        %7D%0A        %7D%0A
         this.con
@@ -1362,26 +1362,16 @@
 = null;%0A
-        %7D%0A
     %7D%0A%0A 

check close