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