If you have an AuditListener for your EclipseLink entities, you may have a problem to get the name of the current user at this level. You could use the InitialContext.lookup("java:comp/EJBContext") method, but it fails on my application. Another way is to use a servlet filter.
Define a filter class within your web.xml:
<filter> <filter-name>PrincipalServletFilter</filter-name> <filter-class>de.uni_leipzig.smo.acltest.server.filter.PrincipalServletFilter</filter-class> </filter> <filter-mapping> <filter-name>PrincipalServletFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Implement a singleton enum, which stores a ThreadLocal variable to hold the current principal object.
public enum PrincipalSingleton {
INSTANCE;
private ThreadLocal<Principal> principal = new ThreadLocal<Principal>();
public Principal get() {
return principal.get();
}
public void set(Principal user) {
this.principal.set(user);
}
}
Set the current principal within the filter.
public class PrincipalServletFilter
implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
PrincipalSingleton.INSTANCE.set(((HttpServletRequest) request).getUserPrincipal());
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig config)
throws ServletException {
}
}
And finally use the principal within your audit class.
private Principal getPrincipal() {
return PrincipalSingleton.INSTANCE.get();
}