checkstyleZZ
[utils] / crawler / basic / src / org / wamblee / crawler / AbstractPageRequest.java
1 /*
2  * Copyright 2005 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.wamblee.crawler;
18
19 import java.io.ByteArrayOutputStream;
20 import java.io.File;
21 import java.io.IOException;
22 import java.io.PrintStream;
23
24 import javax.xml.transform.OutputKeys;
25 import javax.xml.transform.Transformer;
26 import javax.xml.transform.TransformerConfigurationException;
27 import javax.xml.transform.TransformerException;
28 import javax.xml.transform.TransformerFactory;
29 import javax.xml.transform.dom.DOMSource;
30 import javax.xml.transform.stream.StreamResult;
31
32 import org.apache.commons.httpclient.Header;
33 import org.apache.commons.httpclient.HttpClient;
34 import org.apache.commons.httpclient.HttpMethod;
35 import org.apache.commons.httpclient.HttpStatus;
36 import org.apache.commons.httpclient.NameValuePair;
37 import org.apache.commons.httpclient.methods.GetMethod;
38 import org.apache.commons.logging.Log;
39 import org.apache.commons.logging.LogFactory;
40 import org.apache.xml.serialize.OutputFormat;
41 import org.apache.xml.serialize.XMLSerializer;
42 import org.w3c.dom.Document;
43 import org.w3c.tidy.Tidy;
44 import org.wamblee.io.FileResource;
45 import org.wamblee.xml.DOMUtility;
46 import org.wamblee.xml.XSLT;
47
48 /**
49  * General support claas for all kinds of requests.
50  */
51 public abstract class AbstractPageRequest implements PageRequest {
52
53     private static final Log LOG = LogFactory.getLog(AbstractPageRequest.class);
54
55     private static final String REDIRECT_HEADER = "Location";
56
57     private int _maxTries;
58
59     private int _maxDelay;
60
61     private NameValuePair[] _params;
62
63     private String _xslt;
64
65     private PrintStream _os;
66
67     /**
68      * Constructs the request.
69      * 
70      * @param aMaxTries
71      *            Maximum retries to perform.
72      * @param aMaxDelay
73      *            Maximum delay before executing a request.
74      * @param aParams
75      *            Request parameters to use.
76      * @param aXslt
77      *            XSLT used to convert the response.
78      * @param aOs
79      *            Output stream for logging (if null then no logging is done).
80      */
81     protected AbstractPageRequest(int aMaxTries, int aMaxDelay,
82             NameValuePair[] aParams, String aXslt, PrintStream aOs) {
83         if (aParams == null) {
84             throw new IllegalArgumentException("aParams is null");
85         }
86         if (aXslt == null) {
87             throw new IllegalArgumentException("aXslt is null");
88         }
89         _maxTries = aMaxTries;
90         _maxDelay = aMaxDelay;
91         _params = aParams;
92         _xslt = aXslt;
93         _os = aOs;
94     }
95
96     /*
97      * (non-Javadoc)
98      * 
99      * @see org.wamblee.crawler.PageRequest#overrideXslt(java.lang.String)
100      */
101     public void overrideXslt(String aXslt) {
102         _xslt = aXslt;
103     }
104
105     /**
106      * Gets the parameters for the request.
107      * 
108      * @return Request parameters.
109      */
110     protected NameValuePair[] getParameters() {
111         return _params;
112     }
113
114     /**
115      * Executes the request with a random delay and with a maximum number of
116      * retries.
117      * 
118      * @param aClient
119      *            HTTP client to use.
120      * @param aMethod
121      *            Method representing the request.
122      * @return XML document describing the response.
123      * @throws IOException
124      *             In case of IO problems.
125      * @throws TransformerException
126      *             In case transformation of the HTML to XML fails.
127      */
128     protected Document executeMethod(HttpClient aClient, HttpMethod aMethod)
129             throws IOException, TransformerException {
130         int triesLeft = _maxTries;
131         while (triesLeft > 0) {
132             triesLeft--;
133             try {
134                 return executeMethodWithoutRetries(aClient, aMethod);
135             } catch (TransformerException e) {
136                 if (triesLeft == 0) {
137                     throw e;
138                 }
139             }
140         }
141         throw new RuntimeException("Code should never reach this point");
142     }
143
144     /**
145      * Executes the request without doing any retries in case XSLT
146      * transformation fails.
147      * 
148      * @param aClient
149      *            HTTP client to use.
150      * @param aMethod
151      *            Method to execute.
152      * @return XML document containing the result.
153      * @throws IOException
154      *             In case of IO problems.
155      * @throws TransformerException
156      *             In case transformation of the result to XML fails.
157      */
158     protected Document executeMethodWithoutRetries(HttpClient aClient,
159             HttpMethod aMethod) throws IOException, TransformerException {
160         try {
161             aMethod = executeWithRedirects(aClient, aMethod);
162             byte[] xhtmlData = getXhtml(aMethod);
163
164             Document transformed = new XSLT().transform(xhtmlData,
165                     new FileResource(new File(_xslt)));
166             _os.println("Transformed result is: ");
167             Transformer transformer = TransformerFactory.newInstance()
168                     .newTransformer();
169             transformer.setParameter(OutputKeys.INDENT, "yes");
170             transformer.setParameter(OutputKeys.METHOD, "xml");
171             transformer.transform(new DOMSource(transformed), new StreamResult(
172                     _os));
173
174             return transformed;
175         } catch (TransformerConfigurationException e) {
176             throw new RuntimeException(e.getMessage(), e);
177         } finally {
178             // Release the connection.
179             aMethod.releaseConnection();
180         }
181     }
182
183     /**
184      * Gets the result of the HTTP method as an XHTML document.
185      * 
186      * @param aMethod
187      *            Method to invoke.
188      * @return XHTML as a byte array.
189      * @throws IOException
190      *             In case of problems obtaining the XHTML.
191      */
192     private byte[] getXhtml(HttpMethod aMethod) throws IOException {
193         // Transform the HTML into wellformed XML.
194         Tidy tidy = new Tidy();
195         tidy.setXHTML(true);
196         tidy.setQuiet(true);
197         tidy.setShowWarnings(false);
198         if (_os != null) {
199             _os.println("Content of '" + aMethod.getURI() + "'");
200             _os.println();
201         }
202         // We write the jtidy output to XML since the DOM tree it produces is
203         // not namespace aware and namespace awareness is required by XSLT.
204         // An alternative is to configure namespace awareness of the XML parser
205         // in a system wide way.
206         Document w3cDoc = tidy.parseDOM(aMethod.getResponseBodyAsStream(), _os);
207         DOMUtility.removeDuplicateAttributes(w3cDoc);
208
209         ByteArrayOutputStream xhtml = new ByteArrayOutputStream();
210         XMLSerializer serializer = new XMLSerializer(xhtml, new OutputFormat());
211         serializer.serialize(w3cDoc);
212         xhtml.flush();
213         if (_os != null) {
214             _os.println();
215         }
216         return xhtml.toByteArray();
217     }
218
219     /**
220      * Sleeps for a random time but no more than the maximum delay.
221      * 
222      */
223     private void delay() {
224         try {
225             Thread.sleep((long) ((float) _maxDelay * Math.random()));
226         } catch (InterruptedException e) {
227             return; // to satisfy checkstyle
228         }
229     }
230
231     /**
232      * Executes the request and follows redirects if needed.
233      * 
234      * @param aClient
235      *            HTTP client to use.
236      * @param aMethod
237      *            Method to use.
238      * @return Final HTTP method used (differs from the parameter passed in in
239      *         case of redirection).
240      * @throws IOException
241      *             In case of network problems.
242      */
243     private HttpMethod executeWithRedirects(HttpClient aClient,
244             HttpMethod aMethod) throws IOException {
245         delay();
246         int statusCode = aClient.executeMethod(aMethod);
247
248         switch (statusCode) {
249         case HttpStatus.SC_OK: {
250             return aMethod;
251         }
252         case HttpStatus.SC_MOVED_PERMANENTLY:
253         case HttpStatus.SC_MOVED_TEMPORARILY:
254         case HttpStatus.SC_SEE_OTHER: {
255             aMethod.releaseConnection();
256             Header header = aMethod.getResponseHeader(REDIRECT_HEADER);
257             aMethod = new GetMethod(header.getValue());
258             return executeWithRedirects(aClient, aMethod); // TODO protect
259             // against infinite
260             // recursion.
261         }
262         default: {
263             throw new RuntimeException("Method failed: "
264                     + aMethod.getStatusLine());
265         }
266         }
267     }
268 }