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;
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;
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;
48 * General support claas for all kinds of requests.
50 public abstract class AbstractPageRequest implements PageRequest {
52 private static final Log LOG = LogFactory.getLog(AbstractPageRequest.class);
54 private static final String REDIRECT_HEADER = "Location";
56 private int _maxTries;
58 private int _maxDelay;
60 private NameValuePair[] _params;
65 * Constructs the request.
68 * Maximum retries to perform.
70 * Maximum delay before executing a request.
72 * Request parameters to use.
74 * XSLT used to convert the response.
76 protected AbstractPageRequest(int aMaxTries, int aMaxDelay,
77 NameValuePair[] aParams, String aXslt) {
78 if (aParams == null) {
79 throw new IllegalArgumentException("aParams is null");
82 throw new IllegalArgumentException("aXslt is null");
84 _maxTries = aMaxTries;
85 _maxDelay = aMaxDelay;
93 * @see org.wamblee.crawler.PageRequest#overrideXslt(java.lang.String)
95 public void overrideXslt(String aXslt) {
100 * 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
113 * HTTP client to use.
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.
122 protected Document executeMethod(HttpClient aClient, HttpMethod aMethod)
123 throws IOException, TransformerException {
124 int triesLeft = _maxTries;
125 while (triesLeft > 0) {
128 return executeMethodWithoutRetries(aClient, aMethod);
129 } catch (TransformerException e) {
130 if (triesLeft == 0) {
135 throw new RuntimeException("Code should never reach this point");
139 * Executes the request without doing any retries in case XSLT
140 * transformation fails.
143 * HTTP client to use.
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.
152 protected Document executeMethodWithoutRetries(HttpClient aClient,
153 HttpMethod aMethod) throws IOException, TransformerException {
155 aMethod = executeWithRedirects(aClient, aMethod);
156 byte[] xhtmlData = getXhtml(aMethod);
158 Document transformed = new XSLT().transform(xhtmlData,
159 new FileResource(new File(_xslt)));
160 ByteArrayOutputStream os = new ByteArrayOutputStream();
161 Transformer transformer = TransformerFactory.newInstance()
163 transformer.setParameter(OutputKeys.INDENT, "yes");
164 transformer.setParameter(OutputKeys.METHOD, "xml");
165 transformer.transform(new DOMSource(transformed), new StreamResult(
167 LOG.debug("Transformed result is \n" + os.toString());
169 } catch (TransformerConfigurationException e) {
170 throw new RuntimeException(e.getMessage(), e);
172 // Release the connection.
173 aMethod.releaseConnection();
178 * Gets the result of the HTTP method as an XHTML document.
182 * @return XHTML as a byte array.
183 * @throws IOException
184 * In case of problems obtaining the XHTML.
186 private byte[] getXhtml(HttpMethod aMethod) throws IOException {
187 // Transform the HTML into wellformed XML.
188 Tidy tidy = new Tidy();
191 tidy.setShowWarnings(false);
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());
202 ByteArrayOutputStream xhtml = new ByteArrayOutputStream();
203 XMLSerializer serializer = new XMLSerializer(xhtml, new OutputFormat());
204 serializer.serialize(w3cDoc);
207 return xhtml.toByteArray();
211 * Sleeps for a random time but no more than the maximum delay.
214 private void delay() {
216 Thread.sleep((long) ((float) _maxDelay * Math.random()));
217 } catch (InterruptedException e) {
218 return; // to satisfy checkstyle
223 * Executes the request and follows redirects if needed.
226 * HTTP client 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.
234 private HttpMethod executeWithRedirects(HttpClient aClient,
235 HttpMethod aMethod) throws IOException {
237 int statusCode = aClient.executeMethod(aMethod);
239 switch (statusCode) {
240 case HttpStatus.SC_OK: {
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
254 throw new RuntimeException("Method failed: "
255 + aMethod.getStatusLine());