Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Logs message when a techrevel page is requested
package blog.techrevel.service.impl;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import static org.apache.sling.engine.EngineConstants.*;
import org.apache.sling.api.resource.Resource;
import org.osgi.service.component.annotations.Component;
import org.osgi.framework.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
@Component(service = Filter.class, name = "Custom Logging Filter", property = {
SLING_FILTER_SCOPE + "=" + FILTER_SCOPE_REQUEST, Constants.SERVICE_RANKING + ":Integer=1",
SLING_FILTER_PATTERN + "=/content/techrevelblog/.*" })
public class RequestLoggingFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(RequestLoggingFilter.class.getName());
// Called by the web container to indicate to a filter that it is being placed
// into service.
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
// Called by the web container to indicate to a filter that it is being taken
// out of service.
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request instanceof SlingHttpServletRequest && response instanceof SlingHttpServletResponse) {
// Do work before sending the request down the Filter AND Sling processing chain
final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
final Resource resource = slingRequest.getResource();
if (resource.getResourceType().equals("cq:Page")) {
PageManager pageManager = resource.getResourceResolver().adaptTo(PageManager.class);
Page page = pageManager.getPage(resource.getPath());
String templatePath = page.getContentResource().getResourceType();
if (templatePath.equals("techrevelblog/components/structure/page")) {
log.info("Pages from techrevel accessed !!!!");
}
}
chain.doFilter(request, response);
// The Request/Response have now been fully processed by Sling/AEM
} else {
// Else process the chain as usual.
chain.doFilter(request, response);
return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment