JSR 286 Exercise 4 Solution
CountFilter.java
package org.jasig.census;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.filter.ActionFilter;
import javax.portlet.filter.EventFilter;
import javax.portlet.filter.FilterChain;
import javax.portlet.filter.FilterConfig;
import javax.portlet.filter.RenderFilter;
import javax.portlet.filter.ResourceFilter;
public class CountFilter implements RenderFilter, ActionFilter, ResourceFilter, EventFilter {
public static String RENDER_COUNT = "RENDER_COUNT";
public static String ACTION_COUNT = "ACTION_COUNT";
public static String RESOURCE_COUNT = "RESOURCE_COUNT";
public static String EVENT_COUNT = "EVENT_COUNT";
private static int renderCount = 0;
private static int actionCount = 0;
private static int resourceCount = 0;
private static int eventCount = 0;
public void doFilter(RenderRequest request, RenderResponse response, FilterChain chain)
throws IOException, PortletException
{
renderCount++;
request.setAttribute(RENDER_COUNT, renderCount);
request.setAttribute(ACTION_COUNT, actionCount);
request.setAttribute(RESOURCE_COUNT, resourceCount);
request.setAttribute(EVENT_COUNT, eventCount);
chain.doFilter(request, response);
}
public void doFilter(ActionRequest request, ActionResponse response, FilterChain chain)
throws IOException, PortletException
{
actionCount++;
chain.doFilter(request, response);
}
public void doFilter(ResourceRequest request, ResourceResponse response, FilterChain chain)
throws IOException, PortletException
{
resourceCount++;
chain.doFilter(request, response);
}
public void doFilter(EventRequest request, EventResponse response, FilterChain chain)
throws IOException, PortletException
{
eventCount++;
chain.doFilter(request, response);
}
private FilterConfig filterConfig;
public void destroy() {
filterConfig = null;
}
public void init(FilterConfig filterConfig) throws PortletException {
this.filterConfig = filterConfig;
}
public FilterConfig getFilterConfig() {
return filterConfig;
}
}
portlet.xml
...
<filter>
<description>Counts the number of times each lifecycle is called</description>
<display-name>Count Filter</display-name>
<filter-name>CountFilter</filter-name>
<filter-class>org.jasig.census.CountFilter</filter-class>
<lifecycle>ACTION_PHASE</lifecycle>
<lifecycle>RENDER_PHASE</lifecycle>
<lifecycle>EVENT_PHASE</lifecycle>
<lifecycle>RESOURCE_PHASE</lifecycle>
</filter>
<filter-mapping>
<filter-name>CountFilter</filter-name>
<portlet-name>Census*</portlet-name>
</filter-mapping>
...
list.jsp
...
Render calls: ${RENDER_COUNT}<br/>
Action calls: ${ACTION_COUNT}<br/>
Resource calls: ${RESOURCE_COUNT}<br/>
Event calls: ${EVENT_COUNT}<br/>