View Javadoc

1   package com.atlassian.cache.servlet.resolver;
2   
3   import com.atlassian.cache.servlet.CombinedCachingServlet;
4   import org.apache.commons.io.IOUtils;
5   
6   import javax.servlet.ServletConfig;
7   import javax.servlet.ServletContext;
8   import javax.servlet.ServletException;
9   import javax.servlet.http.HttpServletRequest;
10  import javax.servlet.http.HttpServletResponse;
11  import java.io.ByteArrayOutputStream;
12  import java.io.IOException;
13  import java.io.InputStream;
14  
15  /**
16   * Implements a simple resolver that tries to find the resource off of the classpath.
17   */
18  public class ResourceStreamResolver implements ContentResolver
19  {
20      public String getContent(String path, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
21      {
22          return writeFile(request.getSession().getServletContext(), path);
23      }
24  
25      public void init(ServletConfig servletConfig) throws ServletException
26      {
27          // Do nothing here
28      }
29  
30      private String writeFile(ServletContext context, String path) throws IOException, ServletException
31      {
32          final ByteArrayOutputStream os = new ByteArrayOutputStream();
33          final InputStream is = context.getResourceAsStream(path);
34          if (is != null)
35          {
36              IOUtils.copy(is, os);
37          }
38          else
39          {
40              throw new ServletException("resource " + path + " not found.");
41          }
42          return os.toString(CombinedCachingServlet.DEFAULT_ENCODING);
43      }
44  }