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.methods.GetMethod;
38 import org.apache.commons.logging.Log;
39 import org.apache.commons.logging.LogFactory;
40 import org.apache.xml.serialize.OutputFormat;
41 import org.apache.xml.serialize.XMLSerializer;
42 import org.w3c.dom.Document;
43 import org.w3c.tidy.Tidy;
44 import org.wamblee.io.FileResource;
45 import org.wamblee.xml.DOMUtility;
46 import org.wamblee.xml.XSLT;
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;
65 private PrintStream _os;
68 * Constructs the request.
71 * Maximum retries to perform.
73 * Maximum delay before executing a request.
75 * Request parameters to use.
77 * XSLT used to convert the response.
79 * Output stream for logging (if null then no logging is done).
81 protected AbstractPageRequest(int aMaxTries, int aMaxDelay,
82 NameValuePair[] aParams, String aXslt, PrintStream aOs) {
83 if (aParams == null) {
84 throw new IllegalArgumentException("aParams is null");
87 throw new IllegalArgumentException("aXslt is null");
89 _maxTries = aMaxTries;
90 _maxDelay = aMaxDelay;
99 * @see org.wamblee.crawler.PageRequest#overrideXslt(java.lang.String)
101 public void overrideXslt(String aXslt) {
106 * Gets the parameters for the request.
108 * @return Request parameters.
110 protected NameValuePair[] getParameters() {
115 * Executes the request with a random delay and with a maximum number of
119 * HTTP client to use.
121 * Method representing the request.
122 * @return XML document describing the response.
123 * @throws IOException
124 * In case of IO problems.
125 * @throws TransformerException
126 * In case transformation of the HTML to XML fails.
128 protected Document executeMethod(HttpClient aClient, HttpMethod aMethod)
129 throws IOException, TransformerException {
130 int triesLeft = _maxTries;
131 while (triesLeft > 0) {
134 return executeMethodWithoutRetries(aClient, aMethod);
135 } catch (TransformerException e) {
136 if (triesLeft == 0) {
141 throw new RuntimeException("Code should never reach this point");
145 * Executes the request without doing any retries in case XSLT
146 * transformation fails.
149 * HTTP client to use.
152 * @return XML document containing the result.
153 * @throws IOException
154 * In case of IO problems.
155 * @throws TransformerException
156 * In case transformation of the result to XML fails.
158 protected Document executeMethodWithoutRetries(HttpClient aClient,
159 HttpMethod aMethod) throws IOException, TransformerException {
161 aMethod = executeWithRedirects(aClient, aMethod);
162 byte[] xhtmlData = getXhtml(aMethod);
164 Document transformed = new XSLT().transform(xhtmlData,
165 new FileResource(new File(_xslt)));
166 _os.println("Transformed result is: ");
167 Transformer transformer = TransformerFactory.newInstance()
169 transformer.setParameter(OutputKeys.INDENT, "yes");
170 transformer.setParameter(OutputKeys.METHOD, "xml");
171 transformer.transform(new DOMSource(transformed), new StreamResult(
175 } catch (TransformerConfigurationException e) {
176 throw new RuntimeException(e.getMessage(), e);
178 // Release the connection.
179 aMethod.releaseConnection();
184 * Gets the result of the HTTP method as an XHTML document.
188 * @return XHTML as a byte array.
189 * @throws IOException
190 * In case of problems obtaining the XHTML.
192 private byte[] getXhtml(HttpMethod aMethod) throws IOException {
193 // Transform the HTML into wellformed XML.
194 Tidy tidy = new Tidy();
197 tidy.setShowWarnings(false);
199 _os.println("Content of '" + aMethod.getURI() + "'");
202 // We write the jtidy output to XML since the DOM tree it produces is
203 // not namespace aware and namespace awareness is required by XSLT.
204 // An alternative is to configure namespace awareness of the XML parser
205 // in a system wide way.
206 Document w3cDoc = tidy.parseDOM(aMethod.getResponseBodyAsStream(), _os);
207 DOMUtility.removeDuplicateAttributes(w3cDoc);
209 ByteArrayOutputStream xhtml = new ByteArrayOutputStream();
210 XMLSerializer serializer = new XMLSerializer(xhtml, new OutputFormat());
211 serializer.serialize(w3cDoc);
216 return xhtml.toByteArray();
220 * Sleeps for a random time but no more than the maximum delay.
223 private void delay() {
225 Thread.sleep((long) ((float) _maxDelay * Math.random()));
226 } catch (InterruptedException e) {
227 return; // to satisfy checkstyle
232 * Executes the request and follows redirects if needed.
235 * HTTP client to use.
238 * @return Final HTTP method used (differs from the parameter passed in in
239 * case of redirection).
240 * @throws IOException
241 * In case of network problems.
243 private HttpMethod executeWithRedirects(HttpClient aClient,
244 HttpMethod aMethod) throws IOException {
246 int statusCode = aClient.executeMethod(aMethod);
248 switch (statusCode) {
249 case HttpStatus.SC_OK: {
252 case HttpStatus.SC_MOVED_PERMANENTLY:
253 case HttpStatus.SC_MOVED_TEMPORARILY:
254 case HttpStatus.SC_SEE_OTHER: {
255 aMethod.releaseConnection();
256 Header header = aMethod.getResponseHeader(REDIRECT_HEADER);
257 aMethod = new GetMethod(header.getValue());
258 return executeWithRedirects(aClient, aMethod); // TODO protect
263 throw new RuntimeException("Method failed: "
264 + aMethod.getStatusLine());