/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.dgfip.xemelios.web.utils.filters;

import fr.gouv.finances.dgfip.xemelios.web.utils.ByteArrayResponseWrapper;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 * @author CBO
 */
public class PerfLoggerServletFilter implements Filter {

  private static Logger logger = org.apache.log4j.Logger.getLogger(PerfLoggerServletFilter.class);

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse && ((HttpServletRequest) request).getRequestURI().endsWith(".do")) {
      long start = System.currentTimeMillis();
      ByteArrayResponseWrapper responseWrapper = new ByteArrayResponseWrapper((HttpServletResponse)response);
      try {
        filterChain.doFilter(request, responseWrapper);
      } finally {
        long stop = System.currentTimeMillis();
        byte content[] = responseWrapper.toByteArray();
        response.getOutputStream().write(content);
        StringBuilder sb = new StringBuilder();
        sb.append("Statistiques pour " + ((HttpServletRequest) request).getRequestURI() + " :\n");
        sb.append(" " + (stop - start) + " ms\n");
        sb.append(" " + (content.length / 1024) + " ko");
        logger.debug(sb.toString());
      }
    } else {
      filterChain.doFilter(request, response);
    }
  }

  public void init(FilterConfig filterConfig) throws ServletException {
  }

  public void destroy() {
  }
}
