org.clazzes.util.http
Class ResourceServlet

java.lang.Object
  extended by javax.servlet.GenericServlet
      extended by javax.servlet.http.HttpServlet
          extended by org.clazzes.util.http.AbstractResourceSerlvlet
              extended by org.clazzes.util.http.ResourceServlet
All Implemented Interfaces:
Serializable, javax.servlet.Servlet, javax.servlet.ServletConfig

public class ResourceServlet
extends AbstractResourceSerlvlet

A servlet, which exports parts of the ServletContext's resources as HTTP resources with configuration options on which items should be delivered in compressed form.

This servlet may be configured through initialization parameters inside a classical servlet container like in the following web.xml example:

 <servlet>
  <servlet-name>foobar-resources</servlet-name>
  <servlet-class>org.clazzes.util.http.ResourceServlet</servlet-class>
  <init-param>
   <param-name>resourcePath</param-name>
   <param-value>/foobar</param-value>
  </init-param>
  <init-param>
   <param-name>excludeMimeType</param-name>
   <param-value>image/png,image/jpeg,image/gif</param-value>
  </init-param>
  <init-param>
   <param-name>aliases</param-name>
   <param-value>/=/index.html,/index.htm=/index.html</param-value>
  </init-param>
  <init-param>
   <param-name>redirects</param-name>
   <param-value>/app1=appServlet,/app2=/ctx2/appServlet</param-value>
  </init-param>
  <init-param>
   <param-name>additionalHeader.0</param-name>
   <param-value>X-Frame-Options: DENY</param-value>
  </init-param>
  <init-param>
   <param-name>additionalHeader.0.mimeTypeRegex</param-name>
   <param-value>text/html</param-value>
  </init-param>
  <init-param>
   <param-name>additionalHeader.1</param-name>
   <param-value>X-Frame-Options: SAMEORIGIN</param-value>
  </init-param>
  <init-param>
   <param-name>additionalHeader.1.pathRegex</param-name>
   <param-value>.*\.cache\.html</param-value>
  </init-param>
  <init-param>
   <param-name>additionalHeader.2</param-name>
   <param-value>X-UA-Compatible: IE=edge</param-value>
  </init-param>
  <init-param>
   <param-name>additionalHeader.2.mimeTypeRegex</param-name>
   <param-value>text/html</param-value>
  </init-param>
 </servlet>
 

Additional, seldom used initialization parameters are minCompressionSize and bufferSize, which are actually integer values.

In OSGi frameworks it is recommended to set up this servlet using blueprint or a similar technology using the supplied bean property setters like in the following example:

  <bean id="resourceServlet" class="org.clazzes.util.http.ResourceServlet">
    <property name="resourcePath" value="/foobar-resources"></property>
    <property name="excludeMimeTypes">
      <set>
        <value>image/png</value>
        <value>image/gif</value>
        <value>image/jpeg</value>
        <value>image/tiff</value>
      </set>
    </property>
    <property name="aliases">
      <map>
        <entry key="/"          value="/index.html"/>       
        <entry key="/index.htm" value="/index.html"/>       
      </map>
    </property>
    <property name="redirects">
      <map>
        <entry key="/app1" value="appServlet"/>       
        <entry key="/app2" value="/ctx2/appServlet"/>       
      </map>
    </property>
    <property name="maxAgeSeconds" value="7200"></property>
    <property name="cacheRegex" value=".*\.cache\.\w+"></property>
    <property name="nocacheRegex" value=".*\.nocache\.\w+"></property>
    <bp:property name="additionalHeaders">
      <bp:list>
        <bp:bean class="org.clazzes.util.http.AdditionalHeader">
          <bp:property name="header" value="X-Frame-Options"/>
          <bp:property name="value" value="DENY"/>
          <bp:property name="mimeTypeRegex" value="text/html"/>
        </bp:bean>
        <bp:bean class="org.clazzes.util.http.AdditionalHeader">
          <bp:property name="header" value="X-Frame-Options"/>
          <bp:property name="value" value="SAMEORIGIN"/>
          <bp:property name="pathRegex" value=".*\.cache\.html"/>
        </bp:bean>
        <bp:bean class="org.clazzes.util.http.AdditionalHeader">
          <bp:property name="header" value="X-UA-Compatible"/>
          <bp:property name="value" value="IE=edge"/>
          <bp:property name="mimeTypeRegex" value="text/html"/>
        </bp:bean>
      </bp:list>
    </bp:property>
  </bean>
 

The servlet delivers Expires and Cache-Control headers according to the following rules.

  1. If the name of the resource after applying aliases matches cacheRegex, no Expires and Cache-Control headers are delivered.
  2. If maxAgeSeconds is set to 0 or the name of the resource after applying aliases matches nocacheRegex, Expires: 0 and Cache-Control: no-cache headers are delivered.
  3. If maxAgeSeconds is set to a negative value, no Expires and Cache-Control headers are delivered.
  4. Otherwise, Expires and Cache-Control: max-age=<maxAgeSeconds> are delivered according to the value of the maxAgeSeconds property.

In the default configuration, this servlet delivers resources by calling ServletContext.getResourceAsStream(String). If a resource class loader is configured by setResourceClassLoader(ClassLoader) or setResourceClassLoaderHint(Object), the delivered resources are acquired by calling ClassLoader.getResourceAsStream(String) instead. In traditional web.xml setups, a resource class loader may be configured by setting the init parameter useClassLoaderResources to true.

It is possible to registers delegate servlets as plugins using setGetPlugins(Map), setPostPlugins(Map), addGetPlugin(String, Servlet) or addPostPlugin(String, Servlet) for given extensions, which are applied after resolving the incoming path info using the configured aliases.

See Also:
Serialized Form

Constructor Summary
ResourceServlet()
           
 
Method Summary
 void addAlias(String pathInfo, String alias)
          Add an alias for a given path info.
 void addExcludeMimeType(String excludeMimeType)
          Add an element to the list of MIME types to be excluded from compression.
 void addGetPlugin(String extension, javax.servlet.Servlet plugin)
          Add a plugin for GET requests for a given extension.
 void addPostPlugin(String extension, javax.servlet.Servlet plugin)
          Add a plugin for POST requests for a given extension.
 void addRedirect(String pathInfo, String url)
          Add a path-to-URL redirect.
protected  void clearResourceInfos()
          Clear all cached checksums for delivering ETags.
protected  void doGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp)
           
protected  void doPost(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp)
           
 Map<String,String> getAliases()
           
 int getBufferSize()
           
 Pattern getCacheRegex()
           
 Set<String> getExcludeMimeTypes()
           
 Map<String,javax.servlet.Servlet> getGetPlugins()
           
 int getMaxAgeSeconds()
           
 int getMinCompressionSize()
           
 Pattern getNocacheRegex()
           
 Map<String,javax.servlet.Servlet> getPostPlugins()
           
 Map<String,String> getRedirects()
           
protected  InputStream getResourceAsStream(String resPath)
          This method returns the result of ServletContext.getResourceAsStream(String) if the resource class loader is null or otherwise calls resourceClassLoader.getResourceAsStream().
 ClassLoader getResourceClassLoader()
           
 String getResourcePath()
           
 String getServletInfo()
           
 void init()
           
 boolean isNoETags()
           
protected static boolean maybeCallPlugin(String path, String resolvedPath, Map<String,javax.servlet.Servlet> plugins, javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp)
          Call a plugin based on the extension of the resolved path.
protected  String resolvePath(String path)
          Resolve a path using the configured list of aliases.
 void setAliases(Map<String,String> aliases)
           
 void setBufferSize(int bufferSize)
           
 void setCacheRegex(Pattern cacheRegex)
           
 void setExcludeMimeTypes(Set<String> excludeMimeTypes)
           
 void setGetPlugins(Map<String,javax.servlet.Servlet> getPlugins)
           
 void setMaxAgeSeconds(int seconds)
           
 void setMinCompressionSize(int minCompressionSize)
           
 void setNocacheRegex(Pattern nocacheRegex)
           
 void setNoETags(boolean noETags)
           
 void setPostPlugins(Map<String,javax.servlet.Servlet> postPlugins)
           
 void setRedirects(Map<String,String> redirects)
          The keys of this map are path infos like returned by HttpServletRequest.getPathInfo(), which starts with a '/' sign.
 void setResourceClassLoader(ClassLoader resourceClassLoader)
           
 void setResourceClassLoaderHint(Object hint)
          Set the resource class loader according to the given hint object.
 void setResourcePath(String resourcePath)
           
 
Methods inherited from class org.clazzes.util.http.AbstractResourceSerlvlet
addAdditionalHeader, getAdditionalHeaders, propagateAdditionalHeaders, setAdditionalHeaders
 
Methods inherited from class javax.servlet.http.HttpServlet
doDelete, doHead, doOptions, doPut, doTrace, getLastModified, service, service
 
Methods inherited from class javax.servlet.GenericServlet
destroy, getInitParameter, getInitParameterNames, getServletConfig, getServletContext, getServletName, init, log, log
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ResourceServlet

public ResourceServlet()
Method Detail

getResourceAsStream

protected InputStream getResourceAsStream(String resPath)
This method returns the result of ServletContext.getResourceAsStream(String) if the resource class loader is null or otherwise calls resourceClassLoader.getResourceAsStream().

Parameters:
resPath - The final resource path to open.
Returns:
An input stream to read from.

clearResourceInfos

protected void clearResourceInfos()
Clear all cached checksums for delivering ETags. This method might be needed by classes overriding getResourceAsStream(String).


resolvePath

protected String resolvePath(String path)
Resolve a path using the configured list of aliases.

Parameters:
path - The path, which should be set to the empty string, if HttpServletRequest.getPathInfo() returned null.
Returns:
The path mapped to it's alias or the original path, if no alias is configured.

maybeCallPlugin

protected static boolean maybeCallPlugin(String path,
                                         String resolvedPath,
                                         Map<String,javax.servlet.Servlet> plugins,
                                         javax.servlet.http.HttpServletRequest req,
                                         javax.servlet.http.HttpServletResponse resp)
                                  throws javax.servlet.ServletException,
                                         IOException
Call a plugin based on the extension of the resolved path.

Parameters:
path - The original path, which is the empty string ,if HttpServletRequest.getPathInfo() returned null.
resolvedPath - The resolved server-side path to be propagated via RequestHelper.setResolvedPath(HttpServletRequest, String) if it differs from path
plugins - A list of plugins by their extensions.
req - The servlet request.
resp - The serlvet response.
Returns:
Whether a plugin has been found and called.
Throws:
javax.servlet.ServletException - Upon failure calling the plugin.
IOException - Upon failure calling the plugin.

doGet

protected void doGet(javax.servlet.http.HttpServletRequest req,
                     javax.servlet.http.HttpServletResponse resp)
              throws javax.servlet.ServletException,
                     IOException
Overrides:
doGet in class javax.servlet.http.HttpServlet
Throws:
javax.servlet.ServletException
IOException

doPost

protected void doPost(javax.servlet.http.HttpServletRequest req,
                      javax.servlet.http.HttpServletResponse resp)
               throws javax.servlet.ServletException,
                      IOException
Overrides:
doPost in class javax.servlet.http.HttpServlet
Throws:
javax.servlet.ServletException
IOException

getBufferSize

public int getBufferSize()
Returns:
the internal buffer size.

setBufferSize

public void setBufferSize(int bufferSize)
Parameters:
bufferSize - the internal buffer size to set. The default value is 4096 and should be suitable for almost any purpose.

getResourcePath

public String getResourcePath()
Returns:
the resource path, which is exported from the given ClassLoader. If set to null, only redirections are available.

setResourcePath

public void setResourcePath(String resourcePath)
Parameters:
resourcePath - the resource path, which is exported from the given ClassLoader to set. All request exports resources acquired through ServletContext.getResourceAsStream(String) using this resource path appended by HttpServletRequest.getPathInfo().

getMinCompressionSize

public int getMinCompressionSize()
Returns:
the the minimal size of objects to be compressed.

setMinCompressionSize

public void setMinCompressionSize(int minCompressionSize)
Parameters:
minCompressionSize - the minimal size of objects to be compressed to set.

getExcludeMimeTypes

public Set<String> getExcludeMimeTypes()
Returns:
The list of MIME types to be excluded from compression.

setExcludeMimeTypes

public void setExcludeMimeTypes(Set<String> excludeMimeTypes)
Parameters:
excludeMimeTypes - The list of MIME types to be excluded from compression to set. Most image types are already compressed, so should consider to include their MIME types in this list.

addExcludeMimeType

public void addExcludeMimeType(String excludeMimeType)
Add an element to the list of MIME types to be excluded from compression.

Parameters:
excludeMimeType - The MIME type to add.

getServletInfo

public String getServletInfo()
Specified by:
getServletInfo in interface javax.servlet.Servlet
Overrides:
getServletInfo in class javax.servlet.GenericServlet

init

public void init()
          throws javax.servlet.ServletException
Overrides:
init in class AbstractResourceSerlvlet
Throws:
javax.servlet.ServletException

setMaxAgeSeconds

public void setMaxAgeSeconds(int seconds)
Parameters:
seconds - The value of the Cache-Control: max-age=<sec> header delivered to all resources, which are not explicitly marked as cacheable by matching against getCacheRegex(). If set to 0 all resources are marked as non-cacheable. If set to -1 all resources are delivered without a Cache-Control header.

getMaxAgeSeconds

public int getMaxAgeSeconds()
Returns:
The value of the Cache-Control: max-age=<sec> header delivered to all resources, which are not explicitly marked as cacheable by matching against getCacheRegex().

getCacheRegex

public Pattern getCacheRegex()
Returns:
A regular expression, which is used to determine resources, which are delivered with no Expires: and Cache-Control: max-age=<max-age> headers. The default value is ".*\.cache\.\w+"

setCacheRegex

public void setCacheRegex(Pattern cacheRegex)
Parameters:
cacheRegex - A regular expression, which is used to determine resources, which are delivered with no Expires: and Cache-Control: max-age=<max-age> headers. The default value is ".*\.cache\.\w+"

getNocacheRegex

public Pattern getNocacheRegex()
Returns:
A regular expression, which is used to determine resource, which are delivered with Expires: 0 and Cache-Control: no-cache headers. The default value is ".*\.nocache\.\w+"

setNocacheRegex

public void setNocacheRegex(Pattern nocacheRegex)
Parameters:
nocacheRegex - A regular expression, which is used to determine resource, which are delivered with Expires: 0 and Cache-Control: no-cache headers. The default value is ".*\.nocache\.\w+"

getRedirects

public Map<String,String> getRedirects()
Returns:
The mapping of requests path infos to redirect URLs.

setRedirects

public void setRedirects(Map<String,String> redirects)

The keys of this map are path infos like returned by HttpServletRequest.getPathInfo(), which starts with a '/' sign. The values are relative or absolute URLs, which are passed to HttpServletResponse.sendRedirect(String).

The key may be optionally postfixed by a list of locales in the format /localized-url?locales=de,en meaning that any request for /localized-url with an appropriate Accept-Language HTTP header will be redirected to the target with an URL parameter named locale with a value of the selected domain as per LocaleHelper.selectLocale(String, String[]) using the comma-separated list of server-side locales de or en.

Parameters:
redirects - The mapping of requests path infos to redirect URLs to set.

addRedirect

public void addRedirect(String pathInfo,
                        String url)
Add a path-to-URL redirect.

Parameters:
pathInfo - A path info as returned by HttpServletRequest.getPathInfo().
url - A redirect URL passed to HttpServletResponse.sendRedirect(String).

getAliases

public Map<String,String> getAliases()
Returns:
the resource aliases.

setAliases

public void setAliases(Map<String,String> aliases)
Parameters:
aliases - the resource aliases to set. The keys of this map are path infos like returned by HttpServletRequest.getPathInfo(), which start with a '/' sign. The values are translated path infos and should therefore start with a '/' sign, too.

addAlias

public void addAlias(String pathInfo,
                     String alias)
Add an alias for a given path info.

Parameters:
pathInfo - A path info as returned by HttpServletRequest.getPathInfo().
alias - An alias path info, which should start with a '/' sign.

getResourceClassLoader

public ClassLoader getResourceClassLoader()
Returns:
a class loader to resolve resources from instead of resolving from ServletContext.getResourceAsStream(String)

setResourceClassLoader

public void setResourceClassLoader(ClassLoader resourceClassLoader)
Parameters:
resourceClassLoader - a class loader to resolve resources from instead of resolving from ServletContext.getResourceAsStream(String) to set.

setResourceClassLoaderHint

public void setResourceClassLoaderHint(Object hint)
Set the resource class loader according to the given hint object. If hint is null, the resource class loader is set to null. If hint is an instance of ClassLoader, the resource class loader is set to hint .If hint is an instance of Class, the resource class loader is set to hint.getClassLoader(). Otherwise, the resource class loader is set to hint.getClass().getClassLoader().

Parameters:
hint - An object to deduce the resource class loader from.

isNoETags

public boolean isNoETags()
Returns:
Whether no ETag-specific headers should be sent. If set to true, the Last-Modified header will also be omitted.

setNoETags

public void setNoETags(boolean noETags)
Parameters:
noETags - Whether no ETag-specific headers should be sent. If set to true, the Last-Modified header will also be omitted.

getGetPlugins

public Map<String,javax.servlet.Servlet> getGetPlugins()
Returns:
The map of registered plugins for GET requests by their extension.

addGetPlugin

public void addGetPlugin(String extension,
                         javax.servlet.Servlet plugin)
Add a plugin for GET requests for a given extension.

Parameters:
extension - The extension, which will be matched against the resolved path.
plugin - The serlvet to call for requests on resources with the given extension.

setGetPlugins

public void setGetPlugins(Map<String,javax.servlet.Servlet> getPlugins)
Parameters:
getPlugins - The map of registered plugins for GET requests by their extension to set.

getPostPlugins

public Map<String,javax.servlet.Servlet> getPostPlugins()
Returns:
The map of registered plugins for POST requests by their extension.

addPostPlugin

public void addPostPlugin(String extension,
                          javax.servlet.Servlet plugin)
Add a plugin for POST requests for a given extension.

Parameters:
extension - The extension, which will be matched against the resolved path.
plugin - The serlvet to call for requests on resources with the given extension.

setPostPlugins

public void setPostPlugins(Map<String,javax.servlet.Servlet> postPlugins)
Parameters:
postPlugins - The map of registered plugins for POST requests by their extension to set.


Copyright © 2013. All Rights Reserved.