View Javadoc

1   /*
2    *  Java HTML Tidy - JTidy
3    *  HTML parser and pretty printer
4    *
5    *  Copyright (c) 1998-2000 World Wide Web Consortium (Massachusetts
6    *  Institute of Technology, Institut National de Recherche en
7    *  Informatique et en Automatique, Keio University). All Rights
8    *  Reserved.
9    *
10   *  Contributing Author(s):
11   *
12   *     Dave Raggett <dsr@w3.org>
13   *     Andy Quick <ac.quick@sympatico.ca> (translation to Java)
14   *     Gary L Peskin <garyp@firstech.com> (Java development)
15   *     Sami Lempinen <sami@lempinen.net> (release management)
16   *     Fabrizio Giustina <fgiust at users.sourceforge.net>
17   *     Vlad Skarzhevskyy <vlads at users.sourceforge.net> (JTidy servlet  development)
18   *
19   *  The contributing author(s) would like to thank all those who
20   *  helped with testing, bug fixes, and patience.  This wouldn't
21   *  have been possible without all of you.
22   *
23   *  COPYRIGHT NOTICE:
24   *
25   *  This software and documentation is provided "as is," and
26   *  the copyright holders and contributing author(s) make no
27   *  representations or warranties, express or implied, including
28   *  but not limited to, warranties of merchantability or fitness
29   *  for any particular purpose or that the use of the software or
30   *  documentation will not infringe any third party patents,
31   *  copyrights, trademarks or other rights.
32   *
33   *  The copyright holders and contributing author(s) will not be
34   *  liable for any direct, indirect, special or consequential damages
35   *  arising out of any use of the software or documentation, even if
36   *  advised of the possibility of such damage.
37   *
38   *  Permission is hereby granted to use, copy, modify, and distribute
39   *  this source code, or portions hereof, documentation and executables,
40   *  for any purpose, without fee, subject to the following restrictions:
41   *
42   *  1. The origin of this source code must not be misrepresented.
43   *  2. Altered versions must be plainly marked as such and must
44   *     not be misrepresented as being the original source.
45   *  3. This Copyright notice may not be removed or altered from any
46   *     source or altered source distribution.
47   *
48   *  The copyright holders and contributing author(s) specifically
49   *  permit, without fee, and encourage the use of this source code
50   *  as a component for supporting the Hypertext Markup Language in
51   *  commercial products. If you use this source code in a product,
52   *  acknowledgment is not required but would be appreciated.
53   *
54   */
55  package org.w3c.tidy.servlet;
56  
57  import java.io.IOException;
58  import java.io.InputStream;
59  import java.io.OutputStream;
60  import java.io.PrintWriter;
61  
62  import javax.servlet.ServletConfig;
63  import javax.servlet.ServletException;
64  import javax.servlet.http.HttpServlet;
65  import javax.servlet.http.HttpServletRequest;
66  import javax.servlet.http.HttpServletResponse;
67  
68  import org.apache.commons.logging.Log;
69  import org.apache.commons.logging.LogFactory;
70  import org.w3c.tidy.servlet.properties.JTidyServletProperties;
71  import org.w3c.tidy.servlet.reports.Report;
72  
73  
74  /***
75   * This calss produce JTidy processing results and icons in your web application.
76   * @author Vlad Skarzhevskyy <a href="mailto:skarzhevskyy@gmail.com">skarzhevskyy@gmail.com </a>
77   * @version $Revision: 1.5 $ ($Author: fgiust $)
78   */
79  public class TidyServlet extends HttpServlet
80  {
81  
82      /***
83       * Stable <code>serialVersionUID</code>.
84       */
85      private static final long serialVersionUID = 29137L;
86  
87      /***
88       * name of the parameter containing the properties file path.
89       */
90      public static final String CONFIG_PROPERTIES_FILE_NAME = Consts.CONFIG_PROPERTIES_FILE_NAME;
91  
92      /***
93       * The form parameter which defines what should be returned.
94       */
95      public static final String PARAM_REQUEST_ID = "requestID";
96  
97      public static final String PARAM_ACTION = "action";
98  
99      public static final String ACTION_IMAGE = "image";
100 
101     public static final String ACTION_IMAGE_PARAM_SRC_ONLY = "srcOnly";
102 
103     public static final String ACTION_VIEW = "view";
104 
105     public static final String ACTION_REPORT = "report";
106 
107     public static final String ACTION_REPORT_PARAM_SRC_ORG = "src";
108 
109     public static final String ACTION_REPORT_PARAM_SRC_RESULT = "result";
110 
111     private static final String RESOURCE_PREFIX = "";
112 
113     /***
114      * Logger.
115      */
116     private Log log = LogFactory.getLog(TidyServlet.class);
117 
118     private JTidyServletProperties properties = JTidyServletProperties.getInstance();
119 
120     /***
121      * Retrieve the confiuration parameters and set the properties.
122      * @param servletConfig ServletConfig
123      * @throws ServletException generic exception
124      * @see javax.servlet.Servlet#init(ServletConfig)
125      */
126     public final void init(ServletConfig servletConfig) throws ServletException
127     {
128 
129         super.init(servletConfig);
130 
131         // get the parameter and initialize properties
132         properties.loadFile(getInitParameter(CONFIG_PROPERTIES_FILE_NAME));
133     }
134 
135     public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
136     {
137         selectAction(request, response);
138     }
139 
140     public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
141     {
142         selectAction(request, response);
143     }
144 
145     void selectAction(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
146     {
147         String action = request.getParameter(PARAM_ACTION);
148         String id = request.getParameter(PARAM_REQUEST_ID);
149         if (action == null)
150         {
151             return;
152         }
153 
154         if (action.equalsIgnoreCase(ACTION_IMAGE))
155         {
156             redirect2Image(request, response, id);
157         }
158         else if (action.equalsIgnoreCase(ACTION_REPORT))
159         {
160             printReport(request, response, id, false);
161         }
162         else if (action.equalsIgnoreCase(ACTION_VIEW))
163         {
164             printReport(request, response, id, true);
165         }
166     }
167 
168     void redirect2Image(HttpServletRequest request, HttpServletResponse response, String id) throws IOException,
169         ServletException
170     {
171 
172         String imageNamePrefix = properties.getProperty(
173             JTidyServletProperties.PROPERTY_STRING_IMAGENAMEPREFIX,
174             Consts.DEFAULT_IMAGE_NAME_PREFIX);
175         String imageNameExtension = properties.getProperty(
176             JTidyServletProperties.PROPERTY_STRING_IMAGENAMEEXTENSION,
177             ".png");
178 
179         ResponseRecordRepository rrr = JTidyServletProperties.getInstance().getRepositoryInstance(request.getSession());
180         if (rrr == null)
181         {
182             log.info("No ResponseRecordRepository");
183             // Return empty image
184             response.setContentType("image/png");
185             response.setContentLength(0);
186             return;
187         }
188         Object key = rrr.getResponseID(id);
189 
190         ResponseRecord record = rrr.getRecord(key, properties.getIntProperty(
191             JTidyServletProperties.PROPERTY_INT_IMAGEGETTIMEOUT,
192             2000));
193 
194         String imageName = "unknown";
195         if (record != null)
196         {
197             imageName = record.getImageName();
198         }
199         else
200         {
201             log.debug("ResponseRecord not found for ID " + id);
202         }
203 
204         StringBuffer imageURL = new StringBuffer(40);
205         imageURL.append(imageNamePrefix).append(imageName).append(imageNameExtension);
206         if (log.isDebugEnabled())
207         {
208             log.debug("ResultsDO for ID " + id + " -> " + imageURL);
209         }
210 
211         String src = request.getParameter(ACTION_IMAGE_PARAM_SRC_ONLY);
212         if (src != null)
213         {
214             PrintWriter out = response.getWriter();
215             out.print(imageURL);
216         }
217         else
218         {
219             if (!streamResource(imageURL.toString(), response))
220             {
221                 getServletContext().getRequestDispatcher(imageURL.toString()).forward(request, response);
222             }
223         }
224     }
225 
226     private boolean streamResource(String resource, HttpServletResponse response) throws IOException
227     {
228         InputStream in = this.getClass().getClassLoader().getResourceAsStream(RESOURCE_PREFIX + resource);
229 
230         if (in == null)
231         {
232             // Load image from application if not found in jar
233             in = getServletContext().getResourceAsStream("/" + RESOURCE_PREFIX + resource);
234         }
235 
236         if (in == null)
237         {
238             log.warn("resource not found:" + resource);
239             return false;
240         }
241         if (resource.endsWith(".png"))
242         {
243             response.setContentType("image/png");
244         }
245         else if (resource.endsWith(".gif"))
246         {
247             response.setContentType("image/gif");
248         }
249 
250         else if (resource.endsWith(".jpg") || resource.endsWith(".jpeg"))
251         {
252             response.setContentType("image/jpeg");
253         }
254         else
255         {
256             in.close();
257             return false;
258         }
259 
260         final int BUFFER_SIZE = 2048;
261         byte[] buffer = new byte[BUFFER_SIZE];
262         int r = 0;
263         OutputStream out = response.getOutputStream();
264 
265         while ((r = in.read(buffer)) != -1)
266         {
267             out.write(buffer, 0, r);
268         }
269         out.flush();
270         in.close();
271         return true;
272     }
273 
274     void printReport(HttpServletRequest request, HttpServletResponse response, String id, boolean view)
275         throws IOException
276     {
277         response.setContentType("text/html");
278 
279         Report report = new Report(request.getSession());
280 
281         report.setCompletePage(true);
282 
283         report.setView(view);
284 
285         if (request.getParameter(ACTION_REPORT_PARAM_SRC_ORG) != null)
286         {
287             report.setPrintSource(true);
288         }
289         if (request.getParameter(ACTION_REPORT_PARAM_SRC_RESULT) != null)
290         {
291             report.setPrintHtmlResult(true);
292         }
293 
294         report.print(response.getWriter(), id);
295     }
296 }