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