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;
22 import javax.xml.transform.OutputKeys;
23 import javax.xml.transform.Transformer;
24 import javax.xml.transform.TransformerConfigurationException;
25 import javax.xml.transform.TransformerException;
26 import javax.xml.transform.TransformerFactory;
27 import javax.xml.transform.dom.DOMSource;
28 import javax.xml.transform.stream.StreamResult;
30 import org.apache.commons.httpclient.Header;
31 import org.apache.commons.httpclient.HttpClient;
32 import org.apache.commons.httpclient.HttpMethod;
33 import org.apache.commons.httpclient.HttpStatus;
34 import org.apache.commons.httpclient.NameValuePair;
35 import org.apache.commons.httpclient.methods.GetMethod;
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.apache.xml.serialize.OutputFormat;
39 import org.apache.xml.serialize.XMLSerializer;
40 import org.w3c.dom.Document;
41 import org.w3c.tidy.Tidy;
42 import org.wamblee.xml.ClasspathUriResolver;
43 import org.wamblee.xml.DOMUtility;
44 import org.wamblee.xml.XslTransformer;
47 * General support claas for all kinds of requests.
49 public abstract class AbstractPageRequest implements PageRequest {
51 private static final Log LOG = LogFactory.getLog(AbstractPageRequest.class);
53 private static final String REDIRECT_HEADER = "Location";
55 private int _maxTries;
57 private int _maxDelay;
59 private NameValuePair[] _params;
64 * Constructs the request.
67 * Maximum retries to perform.
69 * Maximum delay before executing a request.
71 * Request parameters to use.
73 * XSLT used to convert the response.
75 protected AbstractPageRequest(int aMaxTries, int aMaxDelay,
76 NameValuePair[] aParams, String aXslt) {
77 if (aParams == null) {
78 throw new IllegalArgumentException("aParams is null");
81 throw new IllegalArgumentException("aXslt is null");
83 _maxTries = aMaxTries;
84 _maxDelay = aMaxDelay;
92 * @see org.wamblee.crawler.PageRequest#overrideXslt(java.lang.String)
94 public void overrideXslt(String aXslt) {
99 * Gets the parameters for the request.
101 * @return Request parameters.
103 protected NameValuePair[] getParameters() {
108 * Executes the request with a random delay and with a maximum number of
112 * HTTP client to use.
114 * Method representing the request.
115 * @return XML document describing the response.
116 * @throws IOException
117 * In case of IO problems.
118 * @throws TransformerException
119 * In case transformation of the HTML to XML fails.
121 protected Document executeMethod(HttpClient aClient, HttpMethod aMethod)
122 throws IOException, TransformerException {
123 int triesLeft = _maxTries;
124 while (triesLeft > 0) {
127 return executeMethodWithoutRetries(aClient, aMethod);
128 } catch (TransformerException e) {
129 if (triesLeft == 0) {
134 throw new RuntimeException("Code should never reach this point");
138 * Executes the request without doing any retries in case XSLT
139 * transformation fails.
142 * HTTP client to use.
145 * @return XML document containing the result.
146 * @throws IOException
147 * In case of IO problems.
148 * @throws TransformerException
149 * In case transformation of the result to XML fails.
151 protected Document executeMethodWithoutRetries(HttpClient aClient,
152 HttpMethod aMethod) throws IOException, TransformerException {
154 aMethod = executeWithRedirects(aClient, aMethod);
155 byte[] xhtmlData = getXhtml(aMethod);
157 XslTransformer xsltProcessor = new XslTransformer(new ClasspathUriResolver());
158 Document transformed = xsltProcessor.transform(xhtmlData,
159 xsltProcessor.resolve(_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());