View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package chapters.mdc;
15  
16  import java.io.IOException;
17  import java.security.Principal;
18  
19  import javax.servlet.Filter;
20  import javax.servlet.FilterChain;
21  import javax.servlet.FilterConfig;
22  import javax.servlet.ServletException;
23  import javax.servlet.ServletRequest;
24  import javax.servlet.ServletResponse;
25  import javax.servlet.http.HttpServletRequest;
26  
27  import org.slf4j.MDC;
28  
29  /**
30   * A simple servlet filter that puts the username
31   * found either in the Principal.
32   * 
33   * <p> The value is removed from the MDC once the request has been
34   * fully processed.
35   *
36   * @author S&eacute;bastien Pennec
37   */
38  public class UserServletFilter implements Filter {
39  
40    private final String USER_KEY = "username";
41    
42    public void destroy() {
43    }
44  
45    public void doFilter(ServletRequest request, ServletResponse response,
46        FilterChain chain) throws IOException, ServletException {
47  
48      boolean successfulRegistration = false;
49      HttpServletRequest req = (HttpServletRequest) request;
50      Principal principal = req.getUserPrincipal();
51      // Please note that we also could have used a cookie to 
52      // retrieve the user name
53      
54      if (principal != null) {
55        String username = principal.getName();
56        successfulRegistration = registerUsername(username);
57      }
58      
59      try {
60        chain.doFilter(request, response);
61      } finally {
62        if (successfulRegistration) {
63          MDC.remove(USER_KEY);
64        }
65      }
66    }
67  
68    public void init(FilterConfig arg0) throws ServletException {
69    }
70    
71    /**
72     * Register the user in the MDC under USER_KEY.
73     * 
74     * @param username
75     * @return true id the user can be successfully registered
76     */
77    private boolean registerUsername(String username) {
78      if (username != null && username.trim().length() > 0) {
79        MDC.put(USER_KEY, username);
80        return true;
81      }
82      return false;
83    }
84  
85  }