Blog Archives

Problem with DescriptorEventAdapter and EJBContext

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();
	}

JPA and then?

Some tests with JPA (EclipseLink as implementation) were not successful. I need a persistence.xml file to define different persistence contexts, but what is if I need a new context at runtime? I have to provide such an xml file, but how I can merge the new one with the already existing file without restarting the core system? It’s not nice to define all classes within the xml too, so I have closed this chapter.

I have found another interesting approach: Apache Cayenne. It seems to meet the requirements, especially the use of events during insert/update/commits etc. would allow me to integrate the ACS component of PhOSCo. So I’m thinking about a migration to this framework. Maybe I only can get some ideas from there or the complete framework. I will see.