View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.myfaces.shared.util.servlet;
20  
21  import javax.servlet.*;
22  import javax.servlet.http.*;
23  import java.io.*;
24  
25  public class SourceCodeServlet extends HttpServlet 
26  {
27      public void doGet(HttpServletRequest req, HttpServletResponse res)
28          throws IOException, ServletException
29      {
30          String webPage = req.getServletPath();
31          
32          // remove the '*.source' suffix that maps to this servlet
33          int chopPoint = webPage.indexOf(".source");
34          
35          webPage = webPage.substring(0, chopPoint - 1);
36          webPage += "p"; // replace jsf with jsp
37          
38          // get the actual file location of the requested resource
39          String realPath = getServletConfig().getServletContext().getRealPath(webPage);
40  
41          // output an HTML page
42          res.setContentType("text/plain");
43  
44          // print some html
45          ServletOutputStream out = res.getOutputStream();
46  
47          // print the file
48          InputStream in = null;
49          try 
50          {
51              in = new BufferedInputStream(new FileInputStream(realPath));
52              int ch;
53              while ((ch = in.read()) !=-1) 
54              {
55                  out.print((char)ch);
56              }
57          }
58          finally {
59              if (in != null) in.close();  // very important
60          }
61      }
62  }