(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 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      * @param aMaxTries Maximum retries to perform. 
71      * @param aMaxDelay Maximum delay before executing a request. 
72      * @param aParams Request parameters to use. 
73      * @param aXslt XSLT used to convert the response. 
74      * @param aOs Output stream for logging (if null then no logging is done).
75      */
76     protected AbstractPageRequest(int aMaxTries, int aMaxDelay,
77             NameValuePair[] aParams, String aXslt, PrintStream aOs) {
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         _os = aOs;
89     }
90
91     /*
92      * (non-Javadoc)
93      * 
94      * @see org.wamblee.crawler.PageRequest#overrideXslt(java.lang.String)
95      */
96     public void overrideXslt(String aXslt) {
97         _xslt = aXslt;
98     }
99
100     /**
101      * Gets the parameters for the request. 
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      * @param aClient HTTP client to use. 
112      * @param aMethod Method representing the request. 
113      * @return XML document describing the response.
114      * @throws IOException In case of IO problems.  
115      * @throws TransformerException In case transformation of the HTML to XML fails.
116      */
117     protected Document executeMethod(HttpClient aClient, HttpMethod aMethod)
118             throws IOException, TransformerException {
119         int triesLeft = _maxTries;
120         while (triesLeft > 0) {
121             triesLeft--;
122             try {
123                 return executeMethodWithoutRetries(aClient, aMethod);
124             } catch (TransformerException e) {
125                 if (triesLeft == 0) {
126                     throw e;
127                 }
128             }
129         }
130         throw new RuntimeException("Code should never reach this point");
131     }
132
133     /**
134      * Executes the request without doing any retries in case XSLT transformation
135      * fails. 
136      * @param aClient HTTP client to use. 
137      * @param aMethod Method to execute. 
138      * @return XML document containing the result. 
139      * @throws IOException In case of IO problems. 
140      * @throws TransformerException In case transformation of the result to XML fails.
141      */
142     protected Document executeMethodWithoutRetries(HttpClient aClient,
143             HttpMethod aMethod) throws IOException, TransformerException {
144         try {
145             aMethod = executeWithRedirects(aClient, aMethod);
146             byte[] xhtmlData = getXhtml(aMethod);
147         
148             Document transformed = new XSLT().transform(xhtmlData,
149                     new FileResource(new File(_xslt)));
150             _os.println("Transformed result is: ");
151             Transformer transformer = TransformerFactory.newInstance()
152                     .newTransformer();
153             transformer.setParameter(OutputKeys.INDENT, "yes");
154             transformer.setParameter(OutputKeys.METHOD, "xml");
155             transformer.transform(new DOMSource(transformed), new StreamResult(
156                     _os));
157
158             return transformed;
159         } catch (TransformerConfigurationException e) {
160             throw new RuntimeException(e.getMessage(), e);
161         } finally {
162             // Release the connection.
163             aMethod.releaseConnection();
164         }
165     }
166
167     /**
168      * Gets the result of the HTTP method as an XHTML document. 
169      * @param aMethod Method to invoke.
170      * @return XHTML as a byte array.  
171      * @throws URIException In case of poblems with the URI
172      * @throws IOException In case of problems obtaining the XHTML.
173      */
174         private byte[] getXhtml(HttpMethod aMethod) throws URIException, IOException {
175                 // Transform the HTML into wellformed XML.
176                 Tidy tidy = new Tidy();
177                 tidy.setXHTML(true);
178                 tidy.setQuiet(true);
179                 tidy.setShowWarnings(false);
180                 if (_os != null) {
181                     _os.println("Content of '" + aMethod.getURI() + "'");
182                     _os.println();
183                 }
184                 // We write the jtidy output to XML since the DOM tree it produces is
185                 // not namespace aware and namespace awareness is required by XSLT.
186                 // An alternative is to configure namespace awareness of the XML parser 
187                 // in a system wide way. 
188                 Document w3cDoc = tidy.parseDOM(aMethod.getResponseBodyAsStream(),
189                    _os);
190                 DOMUtility.removeDuplicateAttributes(w3cDoc);
191                 
192                 ByteArrayOutputStream xhtml = new ByteArrayOutputStream(); 
193                 XMLSerializer serializer = new XMLSerializer(xhtml, new OutputFormat());
194                 serializer.serialize(w3cDoc);
195                 xhtml.flush();
196                 if (_os != null) {
197            _os.println();
198         }
199                 return xhtml.toByteArray();
200         }
201
202     /**
203      * Sleeps for a random time but no more than the maximum delay.
204      *
205      */
206     private void delay() {
207         try {
208             Thread.sleep((long) ((float) _maxDelay * Math.random()));
209         } catch (InterruptedException e) {
210             return; // to satisfy checkstyle
211         }
212     }
213
214     /**
215      * Executes the request and follows redirects if needed. 
216      * @param aClient HTTP client to use. 
217      * @param aMethod Method to use.
218      * @return Final HTTP method used (differs from the parameter passed in in case 
219      *   of redirection).
220      * @throws IOException In case of network problems.
221      */
222     private HttpMethod executeWithRedirects(HttpClient aClient,
223             HttpMethod aMethod) throws IOException {
224         delay();
225         int statusCode = aClient.executeMethod(aMethod);
226
227         switch (statusCode) {
228         case HttpStatus.SC_OK: {
229             return aMethod;
230         }
231         case HttpStatus.SC_MOVED_PERMANENTLY:
232         case HttpStatus.SC_MOVED_TEMPORARILY:
233         case HttpStatus.SC_SEE_OTHER: {
234             aMethod.releaseConnection();
235             Header header = aMethod.getResponseHeader(REDIRECT_HEADER);
236             aMethod = new GetMethod(header.getValue());
237             return executeWithRedirects(aClient, aMethod); // TODO protect
238                                                             // against infinite
239                                                             // recursion.
240         }
241         default: {
242             throw new RuntimeException("Method failed: "
243                     + aMethod.getStatusLine());
244         }
245         }
246     }
247 }