Thursday, December 26, 2013

[deltaspike] validate view-config

apache deltaspike provides an improved version of the view-config known from apache myfaces codi. one of many big advantages is the type-safety (even for navigation). the only missing part is the validation against real files and folders. however, if your view-ids correspond with the real file-names (which is good practice anyway), it's easy to do it manually:
public class ViewConfigValidator implements ServletContextListener
{
@Override
public void contextInitialized(ServletContextEvent sce)
{
ViewConfigResolver viewConfigResolver =
BeanProvider.getContextualReference(ViewConfigResolver.class);
for (ConfigDescriptor configDescriptor :
viewConfigResolver.getConfigDescriptors())
{
try
{
if (!isInternal(configDescriptor.getConfigClass()) &&
sce.getServletContext()
.getResource(configDescriptor.getPath()) == null)
{
throw new IllegalStateException("path " +
configDescriptor.getPath() +
" doesn't exist, but it's mapped by " +
configDescriptor.getConfigClass().getName());
}
}
catch (MalformedURLException e)
{
throw ExceptionUtils.throwAsRuntimeException(e);
}
}
}
//needed with deltaspike 0.5
private boolean isInternal(Class configClass)
{
return ViewConfig.class.equals(configClass) ||
DefaultErrorView.class.equals(configClass) ||
ViewRef.class.equals(configClass) ||
ViewRef.Manual.class.equals(configClass);
}
@Override
public void contextDestroyed(ServletContextEvent sce)
{
}
}


in an ee6+ application-server it's possible to annotate this class with @WebListener (-> no further config is needed). in case of a manual cdi-setup (e.g. with tomcat), it's needed to configure the listener after the listener of the cdi-implementation (because cdi needs to be bootstrapped before this listener gets called).

with all versions after v0.5, deltaspike will do this check out-of-the-box.