View Javadoc
1   package org.andromda.cartridges.jsf;
2   
3   import java.io.BufferedInputStream;
4   import java.io.IOException;
5   import java.io.InputStream;
6   import java.io.OutputStream;
7   
8   import javax.servlet.ServletException;
9   import javax.servlet.http.HttpServlet;
10  import javax.servlet.http.HttpServletRequest;
11  import javax.servlet.http.HttpServletResponse;
12  
13  /**
14   * A servlet allowing us to load resources from a jar and make them available to
15   * the web application.
16   */
17  public class JSFServlet
18      extends HttpServlet
19  {
20      private static final long serialVersionUID = 34L;
21      /**
22       * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
23       *      javax.servlet.http.HttpServletResponse)
24       */
25      public void doGet(
26          HttpServletRequest request,
27          HttpServletResponse response)
28          throws ServletException, IOException
29      {
30          final String uri = request.getRequestURI();
31          final String path =
32              '/' + uri.substring(uri.indexOf(Constants.RESOURCE_CONTEXT) + Constants.RESOURCE_CONTEXT.length() + 1);
33          final InputStream resource = JSFServlet.class.getResourceAsStream(path);
34          if (resource == null)
35          {
36              throw new ServletException("Could not load resource from path '" + path + '\'');
37          }
38  
39          // - write resource to the output stream
40          final OutputStream out = response.getOutputStream();
41          final byte[] buffer = new byte[2048];
42          BufferedInputStream inputStream = new BufferedInputStream(resource);
43          int read = 0;
44          read = inputStream.read(buffer);
45          while (read != -1)
46          {
47              out.write(
48                  buffer,
49                  0,
50                  read);
51              read = inputStream.read(buffer);
52          }
53          inputStream.close();
54          out.flush();
55          out.close();
56      }
57  }