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.HttpException;
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.URIException;
39 import org.apache.commons.httpclient.methods.GetMethod;
40 import org.apache.commons.logging.Log;
41 import org.apache.commons.logging.LogFactory;
42 import org.apache.xml.serialize.OutputFormat;
43 import org.apache.xml.serialize.XMLSerializer;
44 import org.w3c.dom.Document;
45 import org.w3c.tidy.Tidy;
46 import org.wamblee.io.FileResource;
47 import org.wamblee.xml.DOMUtility;
48 import org.wamblee.xml.XSLT;
51 * General support claas for all kinds of requests.
53 public abstract class AbstractPageRequest implements PageRequest {
55 private static final Log LOG = LogFactory.getLog(AbstractPageRequest.class);
57 private static final String REDIRECT_HEADER = "Location";
59 private int _maxTries;
61 private int _maxDelay;
63 private NameValuePair[] _params;
67 private PrintStream _os;
70 * Constructs the request.
71 * @param aMaxTries Maximum retries to perform.
72 * @param aMaxDelay Maximum delay before executing a request.
73 * @param aParams Request parameters to use.
74 * @param aXslt XSLT used to convert the response.
75 * @param aOs Output stream for logging (if null then no logging is done).
77 protected AbstractPageRequest(int aMaxTries, int aMaxDelay,
78 NameValuePair[] aParams, String aXslt, PrintStream aOs) {
79 if (aParams == null) {
80 throw new IllegalArgumentException("aParams is null");
83 throw new IllegalArgumentException("aXslt is null");
85 _maxTries = aMaxTries;
86 _maxDelay = aMaxDelay;
95 * @see org.wamblee.crawler.PageRequest#overrideXslt(java.lang.String)
97 public void overrideXslt(String aXslt) {
102 * Gets the parameters for the request.
103 * @return Request parameters.
105 protected NameValuePair[] getParameters() {
110 * Executes the request with a random delay and with a maximum number of
112 * @param aClient HTTP client to use.
113 * @param aMethod Method representing the request.
114 * @return XML document describing the response.
115 * @throws TransformerException In case transformation of the HTML to XML fails.
117 protected Document executeMethod(HttpClient aClient, HttpMethod aMethod)
118 throws 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 TransformerException In case transformation of the result to XML fails.
141 protected Document executeMethodWithoutRetries(HttpClient aClient,
142 HttpMethod aMethod) throws TransformerException {
144 aMethod = executeWithRedirects(aClient, aMethod);
145 byte[] xhtmlData = getXhtml(aMethod);
147 Document transformed = new XSLT().transform(xhtmlData,
148 new FileResource(new File(_xslt)));
149 _os.println("Transformed result is: ");
150 Transformer transformer = TransformerFactory.newInstance()
152 transformer.setParameter(OutputKeys.INDENT, "yes");
153 transformer.setParameter(OutputKeys.METHOD, "xml");
154 transformer.transform(new DOMSource(transformed), new StreamResult(
158 } catch (HttpException e) {
159 throw new RuntimeException(e.getMessage(), e);
160 } catch (IOException e) {
161 throw new RuntimeException(e.getMessage(), e);
162 } catch (TransformerConfigurationException e) {
163 throw new RuntimeException(e.getMessage(), e);
165 // Release the connection.
166 aMethod.releaseConnection();
171 * Gets the result of the HTTP method as an XHTML document.
172 * @param aMethod Method to invoke.
173 * @return XHTML as a byte array.
174 * @throws URIException In case of poblems with the URI
175 * @throws IOException In case of problems obtaining the XHTML.
177 private byte[] getXhtml(HttpMethod aMethod) throws URIException, IOException {
178 // Transform the HTML into wellformed XML.
179 Tidy tidy = new Tidy();
182 tidy.setShowWarnings(false);
184 _os.println("Content of '" + aMethod.getURI() + "'");
187 // We write the jtidy output to XML since the DOM tree it produces is
188 // not namespace aware and namespace awareness is required by XSLT.
189 // An alternative is to configure namespace awareness of the XML parser
190 // in a system wide way.
191 Document w3cDoc = tidy.parseDOM(aMethod.getResponseBodyAsStream(),
193 DOMUtility.removeDuplicateAttributes(w3cDoc);
195 ByteArrayOutputStream xhtml = new ByteArrayOutputStream();
196 XMLSerializer serializer = new XMLSerializer(xhtml, new OutputFormat());
197 serializer.serialize(w3cDoc);
202 return xhtml.toByteArray();
206 * Sleeps for a random time but no more than the maximum delay.
209 private void delay() {
211 Thread.sleep((long) ((float) _maxDelay * Math.random()));
212 } catch (InterruptedException e) {
213 return; // to satisfy checkstyle
218 * Executes the request and follows redirects if needed.
219 * @param aClient HTTP client to use.
220 * @param aMethod Method to use.
221 * @return Final HTTP method used (differs from the parameter passed in in case
223 * @throws IOException In case of network problems.
225 private HttpMethod executeWithRedirects(HttpClient aClient,
226 HttpMethod aMethod) throws IOException {
228 int statusCode = aClient.executeMethod(aMethod);
230 switch (statusCode) {
231 case HttpStatus.SC_OK: {
234 case HttpStatus.SC_MOVED_PERMANENTLY:
235 case HttpStatus.SC_MOVED_TEMPORARILY:
236 case HttpStatus.SC_SEE_OTHER: {
237 aMethod.releaseConnection();
238 Header header = aMethod.getResponseHeader(REDIRECT_HEADER);
239 aMethod = new GetMethod(header.getValue());
240 return executeWithRedirects(aClient, aMethod); // TODO protect
245 throw new RuntimeException("Method failed: "
246 + aMethod.getStatusLine());