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;
20 import java.io.IOException;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.List;
25 import javax.xml.transform.OutputKeys;
26 import javax.xml.transform.Transformer;
27 import javax.xml.transform.TransformerConfigurationException;
28 import javax.xml.transform.TransformerException;
29 import javax.xml.transform.TransformerFactory;
30 import javax.xml.transform.dom.DOMSource;
31 import javax.xml.transform.stream.StreamResult;
33 import org.apache.commons.httpclient.Header;
34 import org.apache.commons.httpclient.HttpClient;
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.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.xml.DomUtils;
46 import org.wamblee.xml.XslTransformer;
49 * General support claas for all kinds of requests.
51 public abstract class AbstractPageRequest implements PageRequest {
53 private static final Log LOG = LogFactory.getLog(AbstractPageRequest.class);
55 private static final String REDIRECT_HEADER = "Location";
57 private int _maxTries;
59 private int _maxDelay;
61 private NameValuePair[] _params;
63 private NameValuePair[] _headers;
67 private XslTransformer _transformer;
70 * Constructs the request.
73 * Maximum retries to perform.
75 * Maximum delay before executing a request.
77 * Request parameters to use.
79 * Request headers to use.
81 * XSLT used to convert the response.
83 protected AbstractPageRequest(int aMaxTries, int aMaxDelay,
84 NameValuePair[] aParams, NameValuePair[] aHeaders, String aXslt, XslTransformer aTransformer) {
85 if (aParams == null) {
86 throw new IllegalArgumentException("aParams is null");
88 if (aHeaders == null) {
89 throw new IllegalArgumentException("aHeaders is null");
92 throw new IllegalArgumentException("aXslt is null");
94 _maxTries = aMaxTries;
95 _maxDelay = aMaxDelay;
99 _transformer = aTransformer;
105 * @see org.wamblee.crawler.PageRequest#overrideXslt(java.lang.String)
107 public void overrideXslt(String aXslt) {
112 * Gets the parameters for the request.
114 * @param aParams Additional parameters to use, obtained from another page, most likely as
115 * hidden form fields.
116 * @return Request parameters.
118 protected NameValuePair[] getParameters(NameValuePair[] aParams) {
119 List<NameValuePair> params = new ArrayList<NameValuePair>();
120 params.addAll(Arrays.asList(_params));
121 params.addAll(Arrays.asList(aParams));
122 return params.toArray(new NameValuePair[0]);
126 * Gets the headers for the request.
127 * @return Request headers.
129 protected NameValuePair[] getHeaders() {
134 * Executes the request with a random delay and with a maximum number of
138 * HTTP client to use.
140 * Method representing the request.
141 * @return XML document describing the response.
142 * @throws IOException
143 * In case of IO problems.
144 * @throws TransformerException
145 * In case transformation of the HTML to XML fails.
147 protected Document executeMethod(HttpClient aClient, HttpMethod aMethod)
148 throws IOException, TransformerException {
150 for (NameValuePair header: getHeaders()) {
151 aMethod.setRequestHeader(header.getName(), header.getValue());
154 int triesLeft = _maxTries;
155 while (triesLeft > 0) {
158 return executeMethodWithoutRetries(aClient, aMethod);
159 } catch (TransformerException e) {
160 if (triesLeft == 0) {
165 throw new RuntimeException("Code should never reach this point");
169 * Executes the request without doing any retries in case XSLT
170 * transformation fails.
173 * HTTP client to use.
176 * @return XML document containing the result.
177 * @throws IOException
178 * In case of IO problems.
179 * @throws TransformerException
180 * In case transformation of the result to XML fails.
182 protected Document executeMethodWithoutRetries(HttpClient aClient,
183 HttpMethod aMethod) throws IOException, TransformerException {
185 aMethod = executeWithRedirects(aClient, aMethod);
186 byte[] xhtmlData = getXhtml(aMethod);
189 Document transformed = _transformer.transform(xhtmlData,
190 _transformer.resolve(_xslt));
191 ByteArrayOutputStream os = new ByteArrayOutputStream();
192 Transformer transformer = TransformerFactory.newInstance()
194 transformer.setParameter(OutputKeys.INDENT, "yes");
195 transformer.setParameter(OutputKeys.METHOD, "xml");
196 transformer.transform(new DOMSource(transformed), new StreamResult(
198 LOG.debug("Transformed result is \n" + os.toString());
200 } catch (TransformerConfigurationException e) {
201 throw new TransformerException("Transformer configuration problem", e);
203 // Release the connection.
204 aMethod.releaseConnection();
209 * Gets the result of the HTTP method as an XHTML document.
213 * @return XHTML as a byte array.
214 * @throws IOException
215 * In case of problems obtaining the XHTML.
217 private byte[] getXhtml(HttpMethod aMethod) throws IOException {
218 // Transform the HTML into wellformed XML.
219 Tidy tidy = new Tidy();
222 tidy.setShowWarnings(false);
224 // We write the jtidy output to XML since the DOM tree it produces is
225 // not namespace aware and namespace awareness is required by XSLT.
226 // An alternative is to configure namespace awareness of the XML parser
227 // in a system wide way.
228 ByteArrayOutputStream os = new ByteArrayOutputStream();
229 Document w3cDoc = tidy.parseDOM(aMethod.getResponseBodyAsStream(), os);
230 DomUtils.removeDuplicateAttributes(w3cDoc);
231 LOG.debug("Content of response is \n" + os.toString());
233 ByteArrayOutputStream xhtml = new ByteArrayOutputStream();
234 XMLSerializer serializer = new XMLSerializer(xhtml, new OutputFormat());
235 serializer.serialize(w3cDoc);
238 return xhtml.toByteArray();
242 * Sleeps for a random time but no more than the maximum delay.
245 private void delay() {
247 Thread.sleep((long) ((float) _maxDelay * Math.random()));
248 } catch (InterruptedException e) {
249 return; // to satisfy checkstyle
254 * Executes the request and follows redirects if needed.
257 * HTTP client to use.
260 * @return Final HTTP method used (differs from the parameter passed in in
261 * case of redirection).
262 * @throws IOException
263 * In case of network problems.
265 private HttpMethod executeWithRedirects(HttpClient aClient,
266 HttpMethod aMethod) throws IOException {
268 int statusCode = aClient.executeMethod(aMethod);
270 switch (statusCode) {
271 case HttpStatus.SC_OK: {
274 case HttpStatus.SC_MOVED_PERMANENTLY:
275 case HttpStatus.SC_MOVED_TEMPORARILY:
276 case HttpStatus.SC_SEE_OTHER: {
277 aMethod.releaseConnection();
278 Header header = aMethod.getResponseHeader(REDIRECT_HEADER);
279 aMethod = new GetMethod(header.getValue());
280 return executeWithRedirects(aClient, aMethod); // TODO protect
285 throw new IOException("Method failed: "
286 + aMethod.getStatusLine());