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.
72 * Maximum retries to perform.
74 * Maximum delay before executing a request.
76 * Request parameters to use.
78 * XSLT used to convert the response.
80 * Output stream for logging (if null then no logging is done).
82 protected AbstractPageRequest(int aMaxTries, int aMaxDelay,
83 NameValuePair[] aParams, String aXslt, PrintStream aOs) {
84 if (aParams == null) {
85 throw new IllegalArgumentException("aParams is null");
88 throw new IllegalArgumentException("aXslt is null");
90 _maxTries = aMaxTries;
91 _maxDelay = aMaxDelay;
100 * @see org.wamblee.crawler.PageRequest#overrideXslt(java.lang.String)
102 public void overrideXslt(String aXslt) {
107 * Gets the parameters for the request.
109 * @return Request parameters.
111 protected NameValuePair[] getParameters() {
116 * Executes the request with a random delay and with a maximum number of
120 * HTTP client to use.
122 * Method representing the request.
123 * @return XML document describing the response.
124 * @throws IOException
125 * In case of IO problems.
126 * @throws TransformerException
127 * In case transformation of the HTML to XML fails.
129 protected Document executeMethod(HttpClient aClient, HttpMethod aMethod)
130 throws IOException, TransformerException {
131 int triesLeft = _maxTries;
132 while (triesLeft > 0) {
135 return executeMethodWithoutRetries(aClient, aMethod);
136 } catch (TransformerException e) {
137 if (triesLeft == 0) {
142 throw new RuntimeException("Code should never reach this point");
146 * Executes the request without doing any retries in case XSLT
147 * transformation fails.
150 * HTTP client to use.
153 * @return XML document containing the result.
154 * @throws IOException
155 * In case of IO problems.
156 * @throws TransformerException
157 * In case transformation of the result to XML fails.
159 protected Document executeMethodWithoutRetries(HttpClient aClient,
160 HttpMethod aMethod) throws IOException, TransformerException {
162 aMethod = executeWithRedirects(aClient, aMethod);
163 byte[] xhtmlData = getXhtml(aMethod);
165 Document transformed = new XSLT().transform(xhtmlData,
166 new FileResource(new File(_xslt)));
167 _os.println("Transformed result is: ");
168 Transformer transformer = TransformerFactory.newInstance()
170 transformer.setParameter(OutputKeys.INDENT, "yes");
171 transformer.setParameter(OutputKeys.METHOD, "xml");
172 transformer.transform(new DOMSource(transformed), new StreamResult(
176 } catch (TransformerConfigurationException e) {
177 throw new RuntimeException(e.getMessage(), e);
179 // Release the connection.
180 aMethod.releaseConnection();
185 * Gets the result of the HTTP method as an XHTML document.
189 * @return XHTML as a byte array.
190 * @throws IOException
191 * In case of problems obtaining the XHTML.
193 private byte[] getXhtml(HttpMethod aMethod) throws IOException {
194 // Transform the HTML into wellformed XML.
195 Tidy tidy = new Tidy();
198 tidy.setShowWarnings(false);
200 _os.println("Content of '" + aMethod.getURI() + "'");
203 // We write the jtidy output to XML since the DOM tree it produces is
204 // not namespace aware and namespace awareness is required by XSLT.
205 // An alternative is to configure namespace awareness of the XML parser
206 // in a system wide way.
207 Document w3cDoc = tidy.parseDOM(aMethod.getResponseBodyAsStream(), _os);
208 DOMUtility.removeDuplicateAttributes(w3cDoc);
210 ByteArrayOutputStream xhtml = new ByteArrayOutputStream();
211 XMLSerializer serializer = new XMLSerializer(xhtml, new OutputFormat());
212 serializer.serialize(w3cDoc);
217 return xhtml.toByteArray();
221 * Sleeps for a random time but no more than the maximum delay.
224 private void delay() {
226 Thread.sleep((long) ((float) _maxDelay * Math.random()));
227 } catch (InterruptedException e) {
228 return; // to satisfy checkstyle
233 * Executes the request and follows redirects if needed.
236 * HTTP client to use.
239 * @return Final HTTP method used (differs from the parameter passed in in
240 * case of redirection).
241 * @throws IOException
242 * In case of network problems.
244 private HttpMethod executeWithRedirects(HttpClient aClient,
245 HttpMethod aMethod) throws IOException {
247 int statusCode = aClient.executeMethod(aMethod);
249 switch (statusCode) {
250 case HttpStatus.SC_OK: {
253 case HttpStatus.SC_MOVED_PERMANENTLY:
254 case HttpStatus.SC_MOVED_TEMPORARILY:
255 case HttpStatus.SC_SEE_OTHER: {
256 aMethod.releaseConnection();
257 Header header = aMethod.getResponseHeader(REDIRECT_HEADER);
258 aMethod = new GetMethod(header.getValue());
259 return executeWithRedirects(aClient, aMethod); // TODO protect
264 throw new RuntimeException("Method failed: "
265 + aMethod.getStatusLine());