7a3755febaa6fbe8d86259500317079358567b63
[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.IOException;
21
22 import javax.xml.transform.OutputKeys;
23 import javax.xml.transform.Transformer;
24 import javax.xml.transform.TransformerConfigurationException;
25 import javax.xml.transform.TransformerException;
26 import javax.xml.transform.TransformerFactory;
27 import javax.xml.transform.dom.DOMSource;
28 import javax.xml.transform.stream.StreamResult;
29
30 import org.apache.commons.httpclient.Header;
31 import org.apache.commons.httpclient.HttpClient;
32 import org.apache.commons.httpclient.HttpMethod;
33 import org.apache.commons.httpclient.HttpStatus;
34 import org.apache.commons.httpclient.NameValuePair;
35 import org.apache.commons.httpclient.methods.GetMethod;
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.apache.xml.serialize.OutputFormat;
39 import org.apache.xml.serialize.XMLSerializer;
40 import org.w3c.dom.Document;
41 import org.w3c.tidy.Tidy;
42 import org.wamblee.xml.ClasspathUriResolver;
43 import org.wamblee.xml.DOMUtility;
44 import org.wamblee.xml.XslTransformer;
45
46 /**
47  * General support claas for all kinds of requests.
48  */
49 public abstract class AbstractPageRequest implements PageRequest {
50
51     private static final Log LOG = LogFactory.getLog(AbstractPageRequest.class);
52
53     private static final String REDIRECT_HEADER = "Location";
54
55     private int _maxTries;
56
57     private int _maxDelay;
58
59     private NameValuePair[] _params;
60
61     private String _xslt;
62
63     /**
64      * Constructs the request.
65      * 
66      * @param aMaxTries
67      *            Maximum retries to perform.
68      * @param aMaxDelay
69      *            Maximum delay before executing a request.
70      * @param aParams
71      *            Request parameters to use.
72      * @param aXslt
73      *            XSLT used to convert the response.
74      */
75     protected AbstractPageRequest(int aMaxTries, int aMaxDelay,
76             NameValuePair[] aParams, String aXslt) {
77         if (aParams == null) {
78             throw new IllegalArgumentException("aParams is null");
79         }
80         if (aXslt == null) {
81             throw new IllegalArgumentException("aXslt is null");
82         }
83         _maxTries = aMaxTries;
84         _maxDelay = aMaxDelay;
85         _params = aParams;
86         _xslt = aXslt;
87     }
88
89     /*
90      * (non-Javadoc)
91      * 
92      * @see org.wamblee.crawler.PageRequest#overrideXslt(java.lang.String)
93      */
94     public void overrideXslt(String aXslt) {
95         _xslt = aXslt;
96     }
97
98     /**
99      * Gets the parameters for the request.
100      * 
101      * @return Request parameters.
102      */
103     protected NameValuePair[] getParameters() {
104         return _params;
105     }
106
107     /**
108      * Executes the request with a random delay and with a maximum number of
109      * retries.
110      * 
111      * @param aClient
112      *            HTTP client to use.
113      * @param aMethod
114      *            Method representing the request.
115      * @return XML document describing the response.
116      * @throws IOException
117      *             In case of IO problems.
118      * @throws TransformerException
119      *             In case transformation of the HTML to XML fails.
120      */
121     protected Document executeMethod(HttpClient aClient, HttpMethod aMethod)
122             throws IOException, TransformerException {
123         int triesLeft = _maxTries;
124         while (triesLeft > 0) {
125             triesLeft--;
126             try {
127                 return executeMethodWithoutRetries(aClient, aMethod);
128             } catch (TransformerException e) {
129                 if (triesLeft == 0) {
130                     throw e;
131                 }
132             }
133         }
134         throw new RuntimeException("Code should never reach this point");
135     }
136
137     /**
138      * Executes the request without doing any retries in case XSLT
139      * transformation fails.
140      * 
141      * @param aClient
142      *            HTTP client to use.
143      * @param aMethod
144      *            Method to execute.
145      * @return XML document containing the result.
146      * @throws IOException
147      *             In case of IO problems.
148      * @throws TransformerException
149      *             In case transformation of the result to XML fails.
150      */
151     protected Document executeMethodWithoutRetries(HttpClient aClient,
152             HttpMethod aMethod) throws IOException, TransformerException {
153         try {
154             aMethod = executeWithRedirects(aClient, aMethod);
155             byte[] xhtmlData = getXhtml(aMethod);
156
157             XslTransformer xsltProcessor = new XslTransformer(new ClasspathUriResolver());
158             Document transformed = xsltProcessor.transform(xhtmlData,
159                     xsltProcessor.resolve(_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 }