001package edu.pdx.cs410J.di; 002 003import com.google.inject.Inject; 004import com.google.inject.Singleton; 005 006import javax.servlet.*; 007import javax.servlet.http.HttpServletRequest; 008import java.io.IOException; 009import java.util.logging.Logger; 010 011/** 012 * Logs all calls to the rest services 013 */ 014@Singleton 015public class RestLoggingFilter implements Filter 016{ 017 private final Logger logger; 018 019 private final CreditCardDatabase cards; 020 021 @Inject 022 public RestLoggingFilter(Logger logger, CreditCardDatabase cards) { 023 this.logger = logger; 024 this.cards = cards; 025 } 026 027 public void init( FilterConfig config ) throws ServletException 028 { 029 // Initialize some credit cards for testing purposes. This probably isn't the best place to do this. 030 for (int i = 1; i <= 10; i++) { 031 CreditCard card = new CreditCard(String.valueOf(i)); 032 cards.setBalance( card, 100.0 ); 033 } 034 } 035 036 public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) 037 throws IOException, ServletException 038 { 039 long begin = System.currentTimeMillis(); 040 041 StringBuilder description = new StringBuilder("Request from "); 042 description.append(request.getRemoteAddr()).append(":").append(request.getRemotePort()); 043 044 if (request instanceof HttpServletRequest) { 045 HttpServletRequest http = (HttpServletRequest) request; 046 047 description.append(" for ").append( http.getMethod() ).append(" ").append(http.getRequestURI()); 048 } 049 logger.info("Begin " + description); 050 051 chain.doFilter( request, response ); 052 053 long delta = System.currentTimeMillis() - begin; 054 055 logger.info("End (" + delta + " ms) " + description); 056 057 } 058 059 public void destroy() 060 { 061 062 } 063}