/***
 * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource
 * All rights reserved.
 *
 * 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 br.com.caelum.vraptor;

import static org.slf4j.LoggerFactory.getLogger;

import java.io.IOException;

import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;

import br.com.caelum.vraptor.core.RequestInfo;
import br.com.caelum.vraptor.core.StaticContentHandler;
import br.com.caelum.vraptor.events.NewRequest;
import br.com.caelum.vraptor.events.VRaptorInitialized;
import br.com.caelum.vraptor.http.EncodingHandler;
import br.com.caelum.vraptor.http.VRaptorRequest;
import br.com.caelum.vraptor.http.VRaptorResponse;
import br.com.caelum.vraptor.interceptor.ApplicationLogicException;
import br.com.caelum.vraptor.ioc.ContainerProvider;

/**
 * VRaptor entry point.<br>
 * Provider configuration is supported through init parameter.
 *
 * @author Guilherme Silveira
 * @author Fabio Kung
 */
@WebFilter(filterName="vraptor", urlPatterns="/*", dispatcherTypes={DispatcherType.FORWARD, DispatcherType.REQUEST})
public class VRaptor implements Filter {

	public static final String VERSION = "4.0.0-RC2-SNAPSHOT";

	private final Logger logger = getLogger(VRaptor.class);

	@Inject
	private ContainerProvider provider;

	@Inject
	private Event<ServletContext> contextEvent;

	@Inject
	private Event<VRaptorInitialized> initializedEvent;

	private ServletContext servletContext;

	@Inject
	private StaticContentHandler staticHandler;

	@Inject
	private EncodingHandler encodingHandler;

	@Inject
	private Event<NewRequest> newRequestEvent;

	@Override
	public void init(FilterConfig cfg) throws ServletException {
		servletContext = cfg.getServletContext();

		validateIfCdiIsFound();
		warnIfBeansXmlIsFound();

		contextEvent.fire(servletContext);
		provider.start();

		initializedEvent.fire(new VRaptorInitialized());
		logger.info("VRaptor {} successfuly initialized", VERSION);
	}

	@Override
	public void destroy() {
		servletContext = null;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
			ServletException {

		validateServletEnvironment(req, res);

		final HttpServletRequest baseRequest = (HttpServletRequest) req;
		final HttpServletResponse baseResponse = (HttpServletResponse) res;

		if (staticHandler.requestingStaticFile(baseRequest)) {
			staticHandler.deferProcessingToContainer(chain, baseRequest, baseResponse);
		} else {
			logger.debug("VRaptor received a new request {}", req);

			VRaptorRequest mutableRequest = new VRaptorRequest(baseRequest);
			VRaptorResponse mutableResponse = new VRaptorResponse(baseResponse);

			final RequestInfo request = new RequestInfo(servletContext, chain, mutableRequest, mutableResponse);

			try {
				encodingHandler.setEncoding(baseRequest, baseResponse);
				provider.provideForRequest(request);
				newRequestEvent.fire(new NewRequest());

			} catch (ApplicationLogicException e) {
				// it is a business logic exception, we dont need to show
				// all interceptors stack trace
				throw new ServletException(e.getMessage(), e.getCause());
			}
			logger.debug("VRaptor ended the request");
		}
	}

	private void validateServletEnvironment(ServletRequest req, ServletResponse res) throws ServletException {
		if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) {
			throw new ServletException("VRaptor must be run inside a Servlet environment. Portlets and others aren't supported.");
		}
	}

	private void warnIfBeansXmlIsFound() {
		if (servletContext.getRealPath("/WEB-INF/beans.xml") == null) {
			logger.warn("A beans.xml isn't found. Check if your beans.xml is properly located at /WEB-INF/beans.xml");
		}
	}

	private void validateIfCdiIsFound() throws ServletException {
		if (provider == null) {
			throw new ServletException("Container Provider is null. Do you have a Weld/CDI listener setup in your web.xml?");
		}
	}
}
@@ -2690,16 +2690,48 @@
 ound();%0A
+%09%09validateJavaEE7Environment();%0A
 %09%09warnIf
@@ -2749,16 +2749,16 @@
 ound();%0A
-
 %0A%09%09conte
@@ -2929,73 +2929,8 @@
 %09%7D%0A%0A
-%09@Override%0A%09public void destroy() %7B%0A%09%09servletContext = null;%0A%09%7D%0A%0A
 %09@Ov
@@ -4102,32 +4102,97 @@
 uest%22);%0A%09%09%7D%0A%09%7D%0A%0A
+%09@Override%0A%09public void destroy() %7B%0A%09%09servletContext = null;%0A%09%7D%0A%0A
 %09private void va
@@ -4809,24 +4809,24 @@
  == null) %7B%0A
-
 %09%09%09throw new
@@ -4936,10 +4936,303 @@
 ;%0A%09%09%7D%0A%09%7D
+%0A%0A%09private void validateJavaEE7Environment() throws ServletException %7B%0A%09%09try %7B%0A%09%09%09servletContext.getVirtualServerName();%0A%09%09%7D catch (NoSuchMethodError e) %7B%0A%09%09%09throw new ServletException(%22VRaptor only runs under Servlet 3.1. Please upgrade your Servlet Container or Application Server.%22);%0A%09%09%7D%0A%09%7D
 %0A%7D

Validate if app runs under servlet 3.1 impl