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