/* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
 - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 
 - Redistribution in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in
   the documentation and/or other materials provided with the
   distribution.
 
 Neither the name of Sun Microsystems, Inc. or the names of
 contributors may be used to endorse or promote products derived
 from this software without specific prior written permission.
 
 This software is provided "AS IS," without a warranty of any
 kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
 WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
 EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
 SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN
 OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
 FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
 PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
 LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
 EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 
 You acknowledge that Software is not designed, licensed or intended
 for use in the design, construction, operation or maintenance of
 any nuclear facility.
 $Id: TransactionFilter.java,v 1.1 2003/07/23 00:41:30 gmurray Exp $ */

package com.sun.j2ee.blueprints.waf.controller.web;

import java.io.*;
import java.util.*;
import java.net.URL;

// J2EE imports
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.*;

// WAF imports
import com.sun.j2ee.blueprints.waf.controller.web.util.WebKeys;


public class TransactionFilter implements Filter {

    private HashMap urlMappings;
    private ServletContext context;
    private FilterConfig config;

    public void init(FilterConfig config) throws ServletException {
        this.config = config;
        this.context = config.getServletContext();
        try {
            urlMappings = (HashMap)context.getAttribute(WebKeys.URL_MAPPINGS);
        } catch (Exception ex) {
            System.out.println("Error starting TransactionFilter: " + ex);
            ex.printStackTrace();
        }
    }
    
    public void destroy() {
        config = null;
    }

     public  void doFilter(ServletRequest request, ServletResponse  response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest hreq = (HttpServletRequest)request;
        String currentURI = hreq.getRequestURL().toString();
        String currentURL = hreq.getRequestURI();
        // get everything after the context root
        int firstSlash = currentURL.indexOf("/",1); // jump past the starting slash
        String targetURL = null;
        if (firstSlash != -1) targetURL = currentURL.substring(firstSlash + 1, currentURL.length());

        // find out if the patterns match the target URL
        Iterator it = urlMappings.keySet().iterator();
        while (it.hasNext()) {
            String key = (String)it.next();
            URLMapping urlm  = (URLMapping)urlMappings.get(key);

            // now check if the URL uses a transaction
            if (urlm.getURI().equals(targetURL) && urlm.isTransactional()) {
                // start the transaction
                boolean tx_started = false;
                UserTransaction ut = null;
                try {
                    // Lookup the UserTransaction object
                    InitialContext ic = new InitialContext();
                    ut = (UserTransaction) ic.lookup("java:comp/UserTransaction");
                    ut.begin();   // start the transaction. 
                    tx_started = true;
                } catch (NamingException ne) {
                    // it should not have happened, but it is a recoverable error. 
                    // Just dont start the transaction. 
                    ne.printStackTrace();
                } catch (NotSupportedException nse) {
                    // Again this is a recoverable error. 
                    nse.printStackTrace();
                } catch (SystemException se) {
                    // Again this is a recoverable error. 
                    se.printStackTrace();
                }
                try {
                    chain.doFilter(request,response);
                } finally {
                    // commit the transaction if it was started earlier successfully. 
                    try {
                        if (tx_started && ut != null) {
                            ut.commit();
                        }
                    } catch (IllegalStateException re) {
                        re.printStackTrace();
                    } catch (RollbackException re) {
                        re.printStackTrace();
                    } catch (HeuristicMixedException hme) {
                        hme.printStackTrace();
                    } catch (HeuristicRollbackException hre) {
                        hre.printStackTrace();
                    } catch (SystemException se) {
                        se.printStackTrace();
                    }
                }
                // stop the transaction
                // jump out of this processing
                return;
            }
        }
        // No matches if we made it to here
        chain.doFilter(request,response);
    }
 }