2 * Copyright 2005 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.wamblee.crawler;
19 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22 import java.io.PrintStream;
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;
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;
50 * General support claas for all kinds of requests.
52 public abstract class AbstractPageRequest implements PageRequest {
54 private static final Log LOG = LogFactory.getLog(AbstractPageRequest.class);
56 private static final String REDIRECT_HEADER = "Location";
58 private int _maxTries;
60 private int _maxDelay;
62 private NameValuePair[] _params;
66 private PrintStream _os;
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).
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");
82 throw new IllegalArgumentException("aXslt is null");
84 _maxTries = aMaxTries;
85 _maxDelay = aMaxDelay;
94 * @see org.wamblee.crawler.PageRequest#overrideXslt(java.lang.String)
96 public void overrideXslt(String aXslt) {
101 * Gets the parameters for the request.
102 * @return Request parameters.
104 protected NameValuePair[] getParameters() {
109 * Executes the request with a random delay and with a maximum number of
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.
117 protected Document executeMethod(HttpClient aClient, HttpMethod aMethod)
118 throws IOException, TransformerException {
119 int triesLeft = _maxTries;
120 while (triesLeft > 0) {
123 return executeMethodWithoutRetries(aClient, aMethod);
124 } catch (TransformerException e) {
125 if (triesLeft == 0) {
130 throw new RuntimeException("Code should never reach this point");
134 * Executes the request without doing any retries in case XSLT transformation
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.
142 protected Document executeMethodWithoutRetries(HttpClient aClient,
143 HttpMethod aMethod) throws IOException, TransformerException {
145 aMethod = executeWithRedirects(aClient, aMethod);
146 byte[] xhtmlData = getXhtml(aMethod);
148 Document transformed = new XSLT().transform(xhtmlData,
149 new FileResource(new File(_xslt)));
150 _os.println("Transformed result is: ");
151 Transformer transformer = TransformerFactory.newInstance()
153 transformer.setParameter(OutputKeys.INDENT, "yes");
154 transformer.setParameter(OutputKeys.METHOD, "xml");
155 transformer.transform(new DOMSource(transformed), new StreamResult(
159 } catch (TransformerConfigurationException e) {
160 throw new RuntimeException(e.getMessage(), e);
162 // Release the connection.
163 aMethod.releaseConnection();
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.
174 private byte[] getXhtml(HttpMethod aMethod) throws URIException, IOException {
175 // Transform the HTML into wellformed XML.
176 Tidy tidy = new Tidy();
179 tidy.setShowWarnings(false);
181 _os.println("Content of '" + aMethod.getURI() + "'");
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(),
190 DOMUtility.removeDuplicateAttributes(w3cDoc);
192 ByteArrayOutputStream xhtml = new ByteArrayOutputStream();
193 XMLSerializer serializer = new XMLSerializer(xhtml, new OutputFormat());
194 serializer.serialize(w3cDoc);
199 return xhtml.toByteArray();
203 * Sleeps for a random time but no more than the maximum delay.
206 private void delay() {
208 Thread.sleep((long) ((float) _maxDelay * Math.random()));
209 } catch (InterruptedException e) {
210 return; // to satisfy checkstyle
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
220 * @throws IOException In case of network problems.
222 private HttpMethod executeWithRedirects(HttpClient aClient,
223 HttpMethod aMethod) throws IOException {
225 int statusCode = aClient.executeMethod(aMethod);
227 switch (statusCode) {
228 case HttpStatus.SC_OK: {
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
242 throw new RuntimeException("Method failed: "
243 + aMethod.getStatusLine());