/*
 * Copyright 2004-2005 the original author or authors.
 *
 * 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.web.servlet.mvc;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.groovy.grails.web.servlet.FlashScope;
import org.codehaus.groovy.grails.web.util.WebUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Binds a {@link GrailsWebRequestFilter} to the currently executing thread.
 *
 * @author Graeme Rocher
 * @since 0.4
 */
public class GrailsWebRequestFilter extends OncePerRequestFilter {

    /* (non-Javadoc)
     * @see org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(
     *     javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        LocaleContextHolder.setLocale(request.getLocale());
        GrailsWebRequest webRequest = new GrailsWebRequest(request, response, getServletContext());
        configureParameterCreationListeners(webRequest);

        if (logger.isDebugEnabled()) {
            logger.debug("Bound Grails request context to thread: " + request);
        }

        try {
            WebUtils.storeGrailsWebRequest(webRequest);

            // Set the flash scope instance to its next state. We do
            // this here so that the flash is available from Grails
            // filters in a valid state.
            FlashScope fs = webRequest.getAttributes().getFlashScope(request);
            fs.next();

            // Pass control on to the next filter (or the servlet if
            // there are no more filters in the chain).
            filterChain.doFilter(request, response);
        }
        finally {
            webRequest.requestCompleted();
            WebUtils.clearGrailsWebRequest();
            LocaleContextHolder.setLocale(null);
            if (logger.isDebugEnabled()) {
                logger.debug("Cleared Grails thread-bound request context: " + request);
            }
        }
    }

    private void configureParameterCreationListeners(GrailsWebRequest webRequest) {
        ApplicationContext appCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        String[] paramListenerBeans = appCtx.getBeanNamesForType(ParameterCreationListener.class);
        for (int i = 0; i < paramListenerBeans.length; i++) {
            ParameterCreationListener creationListenerBean = (ParameterCreationListener)appCtx.getBean(paramListenerBeans[i]);
            webRequest.addParameterListener(creationListenerBean);
        }
    }
}

@@ -694,16 +694,45 @@
 ception;
+%0Aimport java.util.Collection;
 %0A%0Aimport
@@ -1449,16 +1449,76 @@
 ilter %7B%0A
+%09Collection%3CParameterCreationListener%3E paramListenerBeans;%0A%09
 %0A    /* 
@@ -3226,193 +3226,129 @@
     
-ApplicationContext appCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());%0A        String%5B%5D paramListenerBeans = appCtx.getBeanNamesForType(ParameterC
+for (ParameterCreationListener creationListenerBean : paramListenerBeans) %7B%0A            webRequest.addParameterListener(c
 reat
@@ -3362,14 +3362,12 @@
 ener
-.class
+Bean
 );%0A 
@@ -3377,270 +3377,324 @@
     
-for (int i = 0; i %3C paramListenerBeans.length; i++) %7B%0A            ParameterCreationListener creationListenerBean = (Param
+%7D%0A    %7D%0A%0A%09@Override%0A%09protected void initFilterBean() throws ServletException %7B%0A%09%09super.initFilterBean();%0A        ApplicationContext appCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(g
 et
+S
 er
-CreationListener)appCtx.getBean(paramListenerBeans%5Bi%5D);%0A            webRequest.addParameterListener(creationListenerBean);%0A        %7D%0A    
+vletContext());%0A        paramListenerBeans=appCtx.getBeansOfType(ParameterCreationListener.class).values();%0A%09
 %7D%0A%7D%0A

Fix for GRAILS-6758 (performance optimization)