Home page‎ > ‎Sling and CQ5‎ > ‎

CQ5 NPE when Resource has no path

Developing a custom Sling ResourceProvider you can get this kind of NullPointerException:

22.03.2010 15:55:41.417 *ERROR* [ [1269269683276] GET /content/mynamespace/products/6 HTTP/1.1] org.apache.sling.engine.impl.SlingMainServlet service: Uncaught Throwable java.lang.NullPointerException
    at com.day.cq.wcm.core.impl.WCMRequestFilter.filterRootInclude(WCMRequestFilter.java:275)
    at com.day.cq.wcm.core.impl.WCMRequestFilter.doFilter(WCMRequestFilter.java:161)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:60)
    at org.apache.sling.engine.impl.SlingMainServlet.processRequest(SlingMainServlet.java:427)
    at org.apache.sling.engine.impl.filter.RequestSlingFilterChain.render(RequestSlingFilterChain.java:48)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:64)
    at com.day.j2ee.servletengine.RequestDispatcherImpl.service(RequestDispatcherImpl.java:378)
    at com.day.j2ee.servletengine.ServletHandlerImpl.execute(ServletHandlerImpl.java:313)
    at com.day.j2ee.servletengine.DefaultThreadPool$DequeueThread.run(DefaultThreadPool.java:134)
    at java.lang.Thread.run(Thread.java:619)
Debbugging I saw that:

  1. The filterRootInclude try to "adapt" my Resource to a com.day.cq.wcm.api.Page, with no success
  2. Then, I think because it's unable to get the Page, tries to get it from the parent, and for this the Resource.getPath() is called
  3. Because I forgot to populate the path property of my resource, this return null
  4. Then I think some calculation on the path doesn't check for nulls and fail with a NPE

From this we can learn three things:
  1. Always remember to assign an URL to a Resource
  2. Given that a Resource should always have an URL, or the Resource class is not well implemented (doesn't check for invariant) or the filter doesn't do a good job at signaling them.
  3. It's a best practice to be able to adapt to Page to be CQ5 "ready" ;)

Conversation Element