mstover1 2002/08/09 06:39:55
Modified: . build.xml
src_1/org/apache/jmeter/protocol/http/sampler
HTTPSamplerFull.java
Log:
refactoring of HTTPSamplerFull.java (Martin Ramshaw)
Revision Changes Path
1.66 +1 -1 jakarta-jmeter/build.xml
Index: build.xml
===================================================================
RCS file: /home/cvs/jakarta-jmeter/build.xml,v
retrieving revision 1.65
retrieving revision 1.66
diff -u -r1.65 -r1.66
--- build.xml 6 Aug 2002 15:24:52 -0000 1.65
+++ build.xml 9 Aug 2002 13:39:55 -0000 1.66
@@ -6,7 +6,7 @@
<property name="sources.src.dir" value="src_1"/>
<!-- Where the API documentation lives -->
<property name="docs.api.dest.dir" value="docs/api"/>
- <property name="version" value="1.7.2"/>
+ <property name="version" value="1.7.3"/>
<property name="docs.src" value="./xdocs"/>
<property name="docs.dest" value="./docs"/>
<property name="printable_docs.dest" value="./printable_docs"/>
1.14 +502 -519
jakarta-jmeter/src_1/org/apache/jmeter/protocol/http/sampler/HTTPSamplerFull.java
Index: HTTPSamplerFull.java
===================================================================
RCS file:
/home/cvs/jakarta-jmeter/src_1/org/apache/jmeter/protocol/http/sampler/HTTPSamplerFull.java,v
retrieving revision 1.13
retrieving revision 1.14
diff -u -r1.13 -r1.14
--- HTTPSamplerFull.java 5 Aug 2002 19:08:59 -0000 1.13
+++ HTTPSamplerFull.java 9 Aug 2002 13:39:55 -0000 1.14
@@ -69,555 +69,537 @@
import junit.framework.TestSuite;
import junit.framework.TestResult;
-// required to use to tidy parser
import java.io.*;
import org.w3c.dom.*;
import org.w3c.tidy.Tidy;
import org.xml.sax.SAXException;
-// required for TestCase
/**
- * A sampler that downloads all downloadable components e.g. images,
- * applets etc.
+ * A sampler that downloads downloadable components such as images, applets, etc.
+ * <p>
+ * For HTML files, this class will download binary files specified in the
+ * following ways (where <b>url</b> represents the binary file to be downloaded):
+ * <ul>
+ * <li><img src=<b>url</b> ... >
+ * <li><applet code=<b>url</b> ... >
+ * <li><input type=image src=<b>url</b> ... >
+ * <li><body background=<b>url</b> ... >
+ * </ul>
*
- * @author Khor Soon Hin
- * @version 1.0
+ * Note that files that are duplicated within the enclosing document will
+ * only be downloaded once. Also, the processing does not take account of the
+ * following parameters:
+ * <ul>
+ * <li><base href=<b>url</b>>
+ * <li>< ... codebase=<b>url</b> ... >
+ * </ul>
+ *
+ * The following parameters are not accounted for either (as the textbooks
+ * say, they are left as an exercise for the interested reader):
+ * <ul>
+ * <li><applet ... codebase=<b>url</b> ... >
+ * <li><area href=<b>url</b> ... >
+ * <li><embed src=<b>url</b> ... >
+ * <li><embed codebase=<b>url</b> ... >
+ * <li><object codebase=<b>url</b> ... >
+ * <li><table background=<b>url</b> ... >
+ * <li><td background=<b>url</b> ... >
+ * <li><tr background=<b>url</b> ... >
+ * </ul>
+ *
+ * Due to the recent refactoring of this class, these might not be as difficult
+ * as they once might have been.
+ * <p>
+ * Finally, this class does not process <b>Style Sheets</b> either.
+ *
+ * @author Khor Soon Hin,
+ * <a href="mailto:[EMAIL PROTECTED]">Martin Ramshaw</a>
+ * @version 1.1
* @created $Date$
*/
public class HTTPSamplerFull extends HTTPSampler
{
- public final static String IMAGE = "httpSamplerFull.IMAGE";
-
- protected static Category catClass =
- Category.getInstance(HTTPSamplerFull.class.getName());
-
- protected static String utfEncodingName;
-
- protected static String HTTP = "http://";
-
- protected URL baseUrl;
-
- public HTTPSamplerFull()
- {
- super();
- catClass.debug("Start : HTTPSamplerFull1");
- catClass.debug("End : HTTPSamplerFull1");
- }
-
- /**
- * Gets the UrlConfig attribute of the HTTPSampler object
- *
- * @param e Description of Parameter
- * @return The UrlConfig value
- */
- /*public UrlConfig getUrlConfig(Entry e)
- {
- UrlConfig urlConfig = (UrlConfig)
- e.getConfigElement(UrlConfigFull.class);
- if(catClass.isDebugEnabled())
- {
- catClass.debug("getUrlConfig1 : Returning urlConfig - " +
urlConfig.toString());
- }
- return urlConfig;
- }*/
+ /** Used to store the Logger (used for debug and error messages). */
+ protected static Category catClass =
+ Category.getInstance(HTTPSamplerFull.class.getName());
+
+ /**
+ * Used to store the UTF encoding name (which is version dependent).
+ * @see #getUTFEncodingName
+ */
+ protected static String utfEncodingName;
+
+ /**
+ * Used to store the base URL. It should probably be updated to
+ * respect the following parameter:
+ * <pre>
+ * <base href=<b>url</b>>
+ * </pre>
+ */
+ protected URL baseUrl;
+
+ /**
+ * This is the only Constructor.
+ */
+ public HTTPSamplerFull()
+ {
+ super();
+ catClass.debug("Start : HTTPSamplerFull");
+ catClass.debug("End : HTTPSamplerFull");
+ }
- /**
- * Samples the <code>Entry</code> passed in and stores the result in
- * <code>SampleResult</code>
- *
- * @param entry an entry to be sampled
- * @return resuls of the sampling
- */
- public SampleResult sample(Entry e)
- {
- catClass.debug("Start : sample2");
- long totalTime = (long)0;
- SampleResult res = super.sample(e);
- String displayName = res.getSampleLabel();
- Set uniqueBinaries = new HashSet();
- if(catClass.isDebugEnabled())
- {
- catClass.debug("sample2 : main page loading time - " + res.getTime());
- }
- totalTime += res.getTime();
- Document html = null;
- try
- {
- baseUrl = getUrl();
+ /**
+ * Samples the <code>Entry</code> passed in and stores the result in
+ * <code>SampleResult</code>. The original file (which is assumed to be
+ * an HTML file) is parsed into a DOM tree and examined for embedded binary
+ * files.
+ * <p>
+ * Note that files that are duplicated within the enclosing document will
+ * only be downloaded once.
+ *
+ * @param entry an entry to be sampled
+ * @return results of the sampling
+ */
+ public SampleResult sample(Entry e)
+ {
+ // Sample the container page.
+ catClass.debug("Start : HTTPSamplerFull sample");
+ SampleResult res = super.sample(e);
if(catClass.isDebugEnabled())
{
- catClass.debug("sample2 : baseUrl - " + baseUrl.toString());
+ catClass.debug("Main page loading time - " + res.getTime());
}
- // now use parser to look for image tags
- html = (Document)getDOM(new String(res.getResponseData()));
- }
- catch(SAXException exception)
- {
- catClass.error("sample2 : Error parsing document - " + exception);
- catClass.error("sample2 : Setting SampleResult SUCCESS value to
false");
- res.setResponseData(exception.toString().getBytes());
- res.setResponseCode(NON_HTTP_RESPONSE_CODE);
- res.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
- res.setSuccessful(false);
- }
- catch(MalformedURLException exception)
- {
- catClass.error("sample2 : Error creating URL - " + exception);
- catClass.error("sample2 : Setting SampleResult SUCCESS value to
false");
- res.setResponseData(exception.toString().getBytes());
- res.setResponseCode(NON_HTTP_RESPONSE_CODE);
- res.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
- res.setSuccessful(false);
- }
- // sample result to store image from <img...> tags
- SampleResult imgRes = null;
- NodeList nodeList = html.getElementsByTagName("img");
- for(int i = 0; i < nodeList.getLength(); i++)
- {
- imgRes = new SampleResult();
- boolean uniqueImage = true;
+
+ // Now parse the HTML page
+ String displayName = res.getSampleLabel();
+ Document html = null;
try
{
- Node tempNode = nodeList.item(i);
- if(catClass.isDebugEnabled())
- {
- catClass.debug("sample2 : Image tags - " + tempNode);
- }
- // get the url of those images
- NamedNodeMap nnm = tempNode.getAttributes();
- Node namedItem = nnm.getNamedItem("src");
- String imgUrlStr = namedItem.getNodeValue();
- // set the baseUrl and imgUrl so that if error occurs
- // due to MalformedException then at least the values will be
- // visible to the user to aid correction
- imgRes.setSampleLabel(baseUrl + "," + imgUrlStr);
- // download those images
- URL imgUrl = new URL(baseUrl, imgUrlStr);
- if(catClass.isDebugEnabled())
- {
- catClass.debug("sample2 : Image url without baseUrl - " +
imgUrlStr);
- catClass.debug("sample2 : Image url with baseUrl - " +
imgUrl);
- }
- imgRes.setSampleLabel(imgUrl.toString());
- uniqueImage = uniqueBinaries.add(imgUrl.toString());
- if (uniqueImage)
- {
- // a browser should be smart enough to *not* download
- // a binary file that it already has in its cache.
- loadBinary(imgUrl, imgRes);
- totalTime += imgRes.getTime();
- }
- else
- {
- if(catClass.isDebugEnabled())
- {
- catClass.debug("sample2 : skipping duplicate Image -
" + imgUrl);
- }
- }
- }
- catch(IOException exception)
- {
- catClass.error("sample2 : Error reading from URL - " + exception);
- catClass.error("sample2 : Setting SampleResult SUCCESS value to
false");
- imgRes.setResponseData(exception.toString().getBytes());
- imgRes.setResponseCode(NON_HTTP_RESPONSE_CODE);
- imgRes.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
- imgRes.setSuccessful(false);
+ baseUrl = getUrl();
+ if(catClass.isDebugEnabled())
+ {
+ catClass.debug("baseUrl - " + baseUrl.toString());
+ }
+ html = (Document)getDOM(new String(res.getResponseData()));
}
- if (uniqueImage)
+ catch(SAXException se)
{
- res.addSubResult(imgRes);
+ catClass.error("Error parsing document - " + se);
+ res.setResponseData(se.toString().getBytes());
+ res.setResponseCode(NON_HTTP_RESPONSE_CODE);
+ res.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
+ res.setSuccessful(false);
+ return res;
}
- }
- SampleResult appRes = null;
- // use parser to look for applet tags
- nodeList = html.getElementsByTagName("applet");
- for(int i = 0; i < nodeList.getLength(); i++)
- {
- appRes = new SampleResult();
- boolean uniqueApplet = true;
- try
+ catch(MalformedURLException mfue)
{
- Node tempNode = nodeList.item(i);
- if(catClass.isDebugEnabled())
- {
- catClass.debug("sample2 : Applet tags - " + tempNode);
- }
- // get the url of those applets
- NamedNodeMap nnm = tempNode.getAttributes();
- Node namedItem = nnm.getNamedItem("code");
- // This will only work with an Applet .class file.
- // Ideally, this should be upgraded to work with Objects (IE)
- // as well as archive (.jar and .zip) files as well.
- String appletUrlStr = namedItem.getNodeValue();
- // set the baseUrl and imgUrl so that if error occurs
- // due to MalformedException then at least the values will be
- // visible to the user to aid correction
- appRes.setSampleLabel(baseUrl + "," + appletUrlStr);
- // download those applet
- URL appletUrl = new URL(baseUrl, appletUrlStr);
- if(catClass.isDebugEnabled())
- {
- catClass.debug("sample2 : Applet url without baseUrl - " +
appletUrlStr);
- catClass.debug("sample2 : Applet url with baseUrl - " +
appletUrl);
- }
- appRes.setSampleLabel(appletUrl.toString());
- uniqueApplet = uniqueBinaries.add(appletUrl.toString());
- if (uniqueApplet)
- {
- // a browser should be smart enough to *not* download
- // a binary file that it already has in its cache.
- loadBinary(appletUrl, appRes);
- totalTime += appRes.getTime();
- }
- else
- {
- if(catClass.isDebugEnabled())
- {
- catClass.debug("sample2 : skipping duplicate Applet -
" + appletUrl);
- }
- }
- }
- catch(IOException exception)
- {
- catClass.error("sample2 : Error reading from URL - " + exception);
- catClass.error("sample2 : Setting SampleResult SUCCESS value to
false");
- appRes.setResponseData(exception.toString().getBytes());
- appRes.setResponseCode(NON_HTTP_RESPONSE_CODE);
- appRes.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
- appRes.setSuccessful(false);
+ catClass.error("Error creating URL '" + displayName + "'");
+ catClass.error("MalformedURLException - " + mfue);
+ res.setResponseData(mfue.toString().getBytes());
+ res.setResponseCode(NON_HTTP_RESPONSE_CODE);
+ res.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
+ res.setSuccessful(false);
+ return res;
}
- if (uniqueApplet)
+
+ // Now parse the DOM tree
+
+ // This is used to ignore duplicated binary files.
+ Set uniqueURLs = new HashSet();
+
+ // look for images
+ parseNodes(html, "img", false, "src", uniqueURLs, res);
+ // look for applets
+
+ // This will only work with an Applet .class file.
+ // Ideally, this should be upgraded to work with Objects (IE)
+ // and archives (.jar and .zip) files as well.
+
+ parseNodes(html, "applet", false, "code", uniqueURLs, res);
+ // look for input tags with image types
+ parseNodes(html, "input", true, "src", uniqueURLs, res);
+ // look for background images
+ parseNodes(html, "body", false, "background", uniqueURLs, res);
+
+ // Okay, we're all done now
+ if(catClass.isDebugEnabled())
{
- res.addSubResult(appRes);
+ catClass.debug("Total time - " + res.getTime());
}
- }
- // use parser to look for input tags with image types as well
- nodeList = html.getElementsByTagName("input");
- for(int i = 0; i < nodeList.getLength(); i++)
- {
- boolean uniqueImage = true;
- try
- {
- Node tempNode = nodeList.item(i);
- if(catClass.isDebugEnabled())
- {
- catClass.debug("sample2 : Input tags - " + tempNode);
- }
- // get the url of those images
- NamedNodeMap nnm = tempNode.getAttributes();
- Node namedItem = nnm.getNamedItem("type");
- if(namedItem != null)
+ catClass.debug("End : HTTPSamplerFull sample");
+ return res;
+ }
+
+ /**
+ * Parse the DOM tree looking for the specified HTML source tags,
+ * and download the appropriate binary files matching these tags.
+ *
+ * @param html the HTML document to parse
+ * @param htmlTag the HTML tag to parse for
+ * @param type indicates that we require 'type=image'
+ * @param srcTag the HTML tag that indicates the source URL
+ * @param uniques used to ensure that binary files are only downloaded
once
+ * @param res <code>SampleResult</code> to store sampling results
+ */
+ protected void parseNodes(Document html, String htmlTag, boolean type, String
srcTag,
+ Set uniques, SampleResult res)
+ {
+ catClass.debug("Start : HTTPSamplerFull parseNodes");
+ NodeList nodeList = html.getElementsByTagName(htmlTag);
+ boolean uniqueBinary;
+ SampleResult binRes = null;
+ for(int i = 0; i < nodeList.getLength(); i++)
{
- String inputType = namedItem.getNodeValue();
+ uniqueBinary = true;
+ Node tempNode = nodeList.item(i);
if(catClass.isDebugEnabled())
{
- catClass.debug("sample2 : Input type - " + inputType);
+ catClass.debug("'" + htmlTag + "' tag: " + tempNode);
}
- if(inputType != null && inputType.equalsIgnoreCase("image"))
+
+ // get the url of the Binary
+ NamedNodeMap nnm = tempNode.getAttributes();
+ Node namedItem = null;
+
+ if(type)
{
- imgRes = new SampleResult();
- namedItem = nnm.getNamedItem("src");
- String imgUrlStr = namedItem.getNodeValue();
- // set the baseUrl and imgUrl so that if error occurs
- // due to MalformedException then at least the values
will be
- // visible to the user to aid correction
- imgRes.setSampleLabel(baseUrl + "," +
- imgUrlStr);
- // download those images
- URL imgUrl = new URL(baseUrl, imgUrlStr);
+ // if type is set, we need 'type=image'
+ namedItem = nnm.getNamedItem("type");
+ if(namedItem == null)
+ {
+ catClass.debug("namedItem 'null' - ignoring");
+ break;
+ }
+ String inputType = namedItem.getNodeValue();
if(catClass.isDebugEnabled())
{
- catClass.debug("sample2 : Image url without
baseUrl - " +
- imgUrlStr);
- catClass.debug("sample2 : Image url with
baseUrl - " +
- imgUrl);
+ catClass.debug("Input type - " + inputType);
}
- imgRes.setSampleLabel(imgUrl.toString());
- uniqueImage = uniqueBinaries.add(imgUrl.toString());
- if (uniqueImage)
+ if(inputType != null &&
inputType.equalsIgnoreCase("image"))
{
- // a browser should be smart enough to *not*
download
- // a binary file that it already has in its
cache.
- loadBinary(imgUrl, imgRes);
- totalTime += imgRes.getTime();
+ // then we need to download the binary
}
else
{
+ catClass.debug("type != 'image' - ignoring");
+ break;
+ }
+ }
+
+ binRes = new SampleResult();
+ namedItem = nnm.getNamedItem(srcTag);
+ String binUrlStr = namedItem.getNodeValue();
+ // set the baseUrl and binUrl so that if error occurs
+ // due to MalformedException then at least the values will be
+ // visible to the user to aid correction
+ binRes.setSampleLabel(baseUrl + "," + binUrlStr);
+ // download the binary
+ URL binUrl = null;
+ try
+ {
+ binUrl = new URL(baseUrl, binUrlStr);
+ }
+ catch(MalformedURLException mfue)
+ {
+ catClass.error("Error creating URL '" + baseUrl +
+ " , " + binUrlStr + "'");
+ catClass.error("MalformedURLException - " + mfue);
+ binRes.setResponseData(mfue.toString().getBytes());
+ binRes.setResponseCode(NON_HTTP_RESPONSE_CODE);
+ binRes.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
+ binRes.setSuccessful(false);
+ res.addSubResult(binRes);
+ break;
+ }
+ if(catClass.isDebugEnabled())
+ {
+ catClass.debug("Binary url - " + binUrlStr);
+ catClass.debug("Full Binary url - " + binUrl);
+ }
+ binRes.setSampleLabel(binUrl.toString());
+ uniqueBinary = uniques.add(binUrl.toString());
+ if (uniqueBinary)
+ {
+ // a browser should be smart enough to *not* download
+ // a binary file that it already has in its cache.
+ try
+ {
+ loadBinary(binUrl, binRes);
+ }
+ catch(IOException ioe)
+ {
+ catClass.error("Error reading from URL - " +
ioe);
+
binRes.setResponseData(ioe.toString().getBytes());
+ binRes.setResponseCode(NON_HTTP_RESPONSE_CODE);
+
binRes.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
+ binRes.setSuccessful(false);
+ }
+ }
+ else
+ {
if(catClass.isDebugEnabled())
{
- catClass.debug("sample2 : skipping duplicate
Image - " + imgUrl);
+ catClass.debug("Skipping duplicate - " +
binUrl);
}
- }
+ break;
}
+ catClass.debug("Adding result");
+ // Note that this only happens for unique binaries
+ res.addSubResult(binRes);
+ res.setTime(res.getTime() + binRes.getTime());
}
- }
- catch(IOException exception)
+ catClass.debug("End : HTTPSamplerFull parseNodes");
+ }
+
+ /**
+ * Download the binary file from the given <code>URL</code>.
+ *
+ * @param url <code>URL</code> from where binary is to be downloaded
+ * @param res <code>SampleResult</code> to store sampling results
+ * @return binary downloaded
+ *
+ * @throws IOException indicates a problem reading from the URL
+ */
+ protected byte[] loadBinary(URL url, SampleResult res) throws IOException
+ {
+ catClass.debug("Start : loadBinary");
+ byte[] ret = new byte[0];
+ res.setSamplerData(new HTTPSampler(url));
+ HttpURLConnection conn = null;
+ try
{
- catClass.error("sample2 : Error reading from URL - " + exception);
- catClass.error("sample2 : Setting SampleResult SUCCESS value to
false");
- imgRes.setResponseData(exception.toString().getBytes());
- imgRes.setResponseCode(NON_HTTP_RESPONSE_CODE);
- imgRes.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
- imgRes.setSuccessful(false);
+ conn = setupConnection(url, GET);
+ conn.connect();
}
- if (uniqueImage)
+ catch(IOException ioe)
{
- res.addSubResult(imgRes);
- }
- }
- if(catClass.isDebugEnabled())
- {
- catClass.debug("sample2 : total time - " + totalTime);
- }
- res.setTime(totalTime);
- catClass.debug("End : sample2");
- return res;
- }
-
- /**
- * Download the binaries from given <code>URL</code>
- *
- * @param url <code>URL</code> from where binary is to be downloaded
- * @param res <code>SampleResult</code> to store sampling results
- * @return binary downloaded
- */
- protected byte[] loadBinary(URL url, SampleResult res)
- throws IOException
- {
- catClass.debug("Start : loadBinary1");
- byte[] ret = new byte[0];
- res.setSamplerData(new HTTPSampler(url));
- HttpURLConnection conn = null;
- try
- {
- conn = setupConnection(url, GET);
- conn.connect();
- }
- catch(IOException exception)
- {
- // don't do anything 'cos persumably the connection will return the
- // correct http response codes
- if(catClass.isDebugEnabled())
- {
- catClass.debug("loadBinary1 : error in setupConnection " +
exception);
- }
- }
- try
- {
- long time = System.currentTimeMillis();
- if(catClass.isDebugEnabled())
- {
- catClass.debug("loadBinary1 : start sampling time - " + time);
- }
- int errorLevel = getErrorLevel(conn, res);
- if (errorLevel == 2)
- {
- ret = readResponse(conn);
- res.setSuccessful(true);
- long endTime = System.currentTimeMillis();
+ // don't do anything 'cos presumably the connection will
return the
+ // correct http response codes
if(catClass.isDebugEnabled())
{
- catClass.debug("loadBinary1 : end sampling time - " +
endTime);
+ catClass.debug("loadBinary : error in setupConnection
" + ioe);
}
- res.setTime(endTime - time);
+ throw ioe;
}
- else
- {
- res.setSuccessful(false);
- int responseCode = ((HttpURLConnection)conn).getResponseCode();
- String responseMessage =
((HttpURLConnection)conn).getResponseMessage();
- catClass.error("loadBinary1 : failed response code - " +
- responseCode);
- catClass.error("loadBinary1 : failed response message - " +
- responseMessage);
- }
- if(catClass.isDebugEnabled())
+
+ try
{
- catClass.debug("loadBinary1 : binary - " + ret[0]+ret[1]);
- catClass.debug("loadBinary1 : loadTime - " + res.getTime());
- }
- catClass.debug("End : loadBinary1");
- res.setResponseData(ret);
- res.setDataType(SampleResult.BINARY);
- return ret;
- }
- finally
- {
- try
- {
- // the server can request that the connection be closed,
- // but if we requested that the server close the connection
- // the server should echo back our 'close' request.
- // Otherwise, let the server disconnect the connection
- // when its timeout period is reached.
- String connection = conn.getHeaderField("Connection");
- if (connection == null || connection.equalsIgnoreCase("close"))
- conn.disconnect();
- }
- catch(Exception e){}
- }
- }
-
- /**
- * Get the response code of the URL connection and divide it by 100 thus
- * returning 2(for 2xx response codes), 3(for 3xx reponse codes), etc
- *
- * @param conn <code>HttpURLConnection</code> of URL request
- * @param res where all results of sampling will be stored
- * @return HTTP response code divided by 100
- */
- protected int getErrorLevel(HttpURLConnection conn, SampleResult res)
- {
- catClass.debug("Start : getErrorLevel1");
- int errorLevel = 2;
- try
- {
- int responseCode = ((HttpURLConnection) conn).getResponseCode();
- String responseMessage = ((HttpURLConnection)
conn).getResponseMessage();
- errorLevel = responseCode/100;
- res.setResponseCode(String.valueOf(responseCode));
- res.setResponseMessage(responseMessage);
- if(catClass.isDebugEnabled())
+ long time = System.currentTimeMillis();
+ if(catClass.isDebugEnabled())
+ {
+ catClass.debug("loadBinary : start time - " + time);
+ }
+ int errorLevel = getErrorLevel(conn, res);
+ if (errorLevel == 2)
+ {
+ ret = readResponse(conn);
+ res.setSuccessful(true);
+ long endTime = System.currentTimeMillis();
+ if(catClass.isDebugEnabled())
+ {
+ catClass.debug("loadBinary : end time - " +
endTime);
+ }
+ res.setTime(endTime - time);
+ }
+ else
+ {
+ res.setSuccessful(false);
+ int responseCode =
+ ((HttpURLConnection)conn).getResponseCode();
+ String responseMsg =
+ ((HttpURLConnection)conn).getResponseMessage();
+ catClass.error("loadBinary : failed code - " +
responseCode);
+ catClass.error("loadBinary : failed message - " +
responseMsg);
+ }
+ if(catClass.isDebugEnabled())
+ {
+ catClass.debug("loadBinary : binary - " +
ret[0]+ret[1]);
+ catClass.debug("loadBinary : loadTime - " +
res.getTime());
+ }
+ catClass.debug("End : loadBinary");
+ res.setResponseData(ret);
+ res.setDataType(SampleResult.BINARY);
+ return ret;
+ }
+ finally
+ {
+ try
+ {
+ // the server can request that the connection be
closed,
+ // but if we requested that the server close the
connection
+ // the server should echo back our 'close' request.
+ // Otherwise, let the server disconnect the connection
+ // when its timeout period is reached.
+ String connection = conn.getHeaderField("Connection");
+ if (connection == null ||
connection.equalsIgnoreCase("close"))
+ conn.disconnect();
+ }
+ catch(Exception e){}
+ }
+ }
+
+ /**
+ * Get the response code of the URL connection and divide it by 100 thus
+ * returning 2 (for 2xx response codes), 3 (for 3xx reponse codes), etc.
+ *
+ * @param conn <code>HttpURLConnection</code> of URL request
+ * @param res where all results of sampling will be stored
+ * @return HTTP response code divided by 100
+ */
+ protected int getErrorLevel(HttpURLConnection conn, SampleResult res)
+ {
+ catClass.debug("Start : getErrorLevel");
+ int errorLevel = 2;
+ try
{
- catClass.debug("getErrorLevel1 : responseCode - " + responseCode);
- catClass.debug("getErrorLevel1 : responseMessage - " +
- responseMessage);
+ int responseCode =
+ ((HttpURLConnection) conn).getResponseCode();
+ String responseMessage =
+ ((HttpURLConnection) conn).getResponseMessage();
+ errorLevel = responseCode/100;
+ res.setResponseCode(String.valueOf(responseCode));
+ res.setResponseMessage(responseMessage);
+ if(catClass.isDebugEnabled())
+ {
+ catClass.debug("getErrorLevel : responseCode - " +
+ responseCode);
+ catClass.debug("getErrorLevel : responseMessage - " +
+ responseMessage);
+ }
}
- }
- catch (Exception e2)
- {
-System.out.println("getErrorLevel1 : " + conn.getHeaderField(0));
-System.out.println("getErrorLevel1 : " + conn.getHeaderFieldKey(0));
- catClass.error("getErrorLevel1 : " +
- "Error getting response code for HttpUrlConnection - " + e2);
- catClass.error("getErrorLevel1 : " +
- "Setting SampleResult SUCCESS value to false");
- res.setResponseData(e2.toString().getBytes());
- res.setResponseCode(NON_HTTP_RESPONSE_CODE);
- res.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
- res.setSuccessful(false);
- }
- catClass.debug("End : getErrorLevel1");
- return errorLevel;
- }
+ catch (Exception e2)
+ {
+ System.out.println("getErrorLevel : " +
conn.getHeaderField(0));
+ System.out.println("getErrorLevel : " +
conn.getHeaderFieldKey(0));
+ catClass.error("getErrorLevel : " +
+ "Error getting response code for HttpUrlConnection - "
+ e2);
+ res.setResponseData(e2.toString().getBytes());
+ res.setResponseCode(NON_HTTP_RESPONSE_CODE);
+ res.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
+ res.setSuccessful(false);
+ }
+ catClass.debug("End : getErrorLevel");
+ return errorLevel;
+ }
- public Object clone()
+ public Object clone()
{
HTTPSamplerFull newSampler = new HTTPSamplerFull();
this.configureClone(newSampler);
return newSampler;
}
- /**
- * Returns <code>tidy</code> as HTML parser
- *
- * @return a <code>tidy</code> HTML parser
- */
- protected static Tidy getParser()
- {
- catClass.debug("Start : getParser1");
- Tidy tidy = new Tidy();
- tidy.setCharEncoding(org.w3c.tidy.Configuration.UTF8);
- tidy.setQuiet(true);
- tidy.setShowWarnings(false);
- if(catClass.isDebugEnabled())
- {
- catClass.debug("getParser1 : tidy parser created - " + tidy);
- }
- catClass.debug("End : getParser1");
- return tidy;
- }
-
- /**
- * Returns a node representing a whole xml given an xml document
- *
- * @param text an xml document
- * @return a node representing a whole xml
- */
- protected static Node getDOM(String text) throws SAXException
- {
- catClass.debug("Start : getDOM1");
- try
- {
- Node node = getParser().parseDOM(new
- ByteArrayInputStream(text.getBytes(getUTFEncodingName())), null);
+ /**
+ * Returns <code>tidy</code> as HTML parser.
+ *
+ * @return a <code>tidy</code> HTML parser
+ */
+ protected static Tidy getParser()
+ {
+ catClass.debug("Start : getParser");
+ Tidy tidy = new Tidy();
+ tidy.setCharEncoding(org.w3c.tidy.Configuration.UTF8);
+ tidy.setQuiet(true);
+ tidy.setShowWarnings(false);
if(catClass.isDebugEnabled())
{
- catClass.debug("node : " + node);
+ catClass.debug("getParser : tidy parser created - " + tidy);
}
- catClass.debug("End : getDOM1");
- return node;
- }
- catch(UnsupportedEncodingException e)
- {
- catClass.error("getDOM1 : Unsupported encoding exception - " + e);
- catClass.debug("End : getDOM1");
- throw new RuntimeException("UTF-8 encoding failed");
- }
- }
+ catClass.debug("End : getParser");
+ return tidy;
+ }
- /**
- * Returns the encoding type which is different for different jdks
- * even though the mean the same thing i.e. UTF8 or UTF-8
- *
- * @return either UTF8 or UTF-8 depending on the jdk version
- */
- protected static String getUTFEncodingName()
- {
- catClass.debug("Start : getUTFEncodingName1");
- if (utfEncodingName == null)
- {
- String versionNum = System.getProperty( "java.version" );
- if(catClass.isDebugEnabled())
+ /**
+ * Returns a node representing a whole xml given an xml document.
+ *
+ * @param text an xml document
+ * @return a node representing a whole xml
+ *
+ * @throws SAXException indicates an error parsing the xml document
+ */
+ protected static Node getDOM(String text) throws SAXException
+ {
+ catClass.debug("Start : getDOM");
+ try
{
- catClass.debug("getUTFEncodingName1 : versionNum - " + versionNum);
+ Node node = getParser().parseDOM(new
+ ByteArrayInputStream(text.getBytes(getUTFEncodingName())),
null);
+ if(catClass.isDebugEnabled())
+ {
+ catClass.debug("node : " + node);
+ }
+ catClass.debug("End : getDOM");
+ return node;
+ }
+ catch(UnsupportedEncodingException e)
+ {
+ catClass.error("getDOM1 : Unsupported encoding exception - " +
e);
+ catClass.debug("End : getDOM");
+ throw new RuntimeException("UTF-8 encoding failed - " + e);
}
- if (versionNum.startsWith( "1.1" ))
+ }
+
+ /**
+ * Returns the encoding type which is different for different jdks
+ * even though they mean the same thing (for example, UTF8 or UTF-8).
+ *
+ * @return either UTF8 or UTF-8 depending on the jdk version
+ * @see #utfEncodingName
+ */
+ protected static String getUTFEncodingName()
+ {
+ catClass.debug("Start : getUTFEncodingName");
+ if (utfEncodingName == null)
{
- utfEncodingName = "UTF8";
+ String versionNum = System.getProperty( "java.version" );
+ if(catClass.isDebugEnabled())
+ {
+ catClass.debug("getUTFEncodingName : version = " +
versionNum);
+ }
+ if (versionNum.startsWith( "1.1" ))
+ {
+ utfEncodingName = "UTF8";
+ }
+ else
+ {
+ utfEncodingName = "UTF-8";
+ }
}
- else
+ if(catClass.isDebugEnabled())
{
- utfEncodingName = "UTF-8";
+ catClass.debug("getUTFEncodingName : Encoding = " +
utfEncodingName);
}
- }
- if(catClass.isDebugEnabled())
- {
- catClass.debug("getUTFEncodingName1 : Returning utfEncodingName - " +
- utfEncodingName);
- }
- catClass.debug("End : getUTFEncodingName1");
- return utfEncodingName;
- }
-
- public static class Test extends TestCase
- {
- private HTTPSamplerFull hsf;
+ catClass.debug("End : getUTFEncodingName");
+ return utfEncodingName;
+ }
+
+public static class Test extends TestCase
+{
+ private HTTPSamplerFull hsf;
- private static Category catClass =
+ private static Category catClass =
Category.getInstance(Test.class.getName());
- public Test(String name)
- {
+ public Test(String name)
+ {
super(name);
- }
+ }
- protected void setUp()
- {
+ protected void setUp()
+ {
catClass.debug("Start : setUp1");
hsf = new HTTPSamplerFull();
hsf.setMethod(HTTPSampler.GET);
hsf.setProtocol("file");
-// urlConfigFull.setPort(8080);
-// urlConfigFull.setDomain("jakarta.apache.org");
+ // urlConfigFull.setPort(8080);
+ // urlConfigFull.setDomain("jakarta.apache.org");
hsf.setPath("HTTPSamplerFullTestFile.txt");
- catClass.debug("End : setUp1");
+ catClass.debug("End : setUp1");
}
public void testGetUTFEncodingName()
{
- catClass.debug("Start : testGetUTFEncodingName1");
+ catClass.debug("Start : testGetUTFEncodingName");
String javaVersion = System.getProperty("java.version");
System.setProperty("java.version", "1.1");
assertEquals("UTF8", HTTPSamplerFull.getUTFEncodingName());
@@ -627,89 +609,90 @@
System.setProperty("java.version", "1.2");
assertEquals("UTF-8", HTTPSamplerFull.getUTFEncodingName());
System.setProperty("java.version", javaVersion);
- catClass.debug("End : testGetUTFEncodingName1");
+ catClass.debug("End : testGetUTFEncodingName");
}
public void testGetUrlConfig()
{
- catClass.debug("Start : testGetUrlConfig1");
+ catClass.debug("Start : testGetUrlConfig");
assertEquals(HTTPSampler.GET, hsf.getMethod());
assertEquals("file", hsf.getProtocol());
-// assertEquals(8080, urlConfig.getPort());
-// assertEquals("jakarta.apache.org", urlConfig.getDomain());
+ // assertEquals(8080, urlConfig.getPort());
+ // assertEquals("jakarta.apache.org", urlConfig.getDomain());
assertEquals("HTTPSamplerFullTestFile.txt", hsf.getPath());
- catClass.debug("End : testGetUrlConfig1");
+ catClass.debug("End : testGetUrlConfig");
}
+
// Can't think of a self-contained way to test this 'cos it requires
// http server. Tried to use file:// but HTTPSampler's sample
// specifically requires http.
public void testSampleMain()
{
- catClass.debug("Start : testSampleMain1");
+ catClass.debug("Start : testSampleMain");
// !ToDo : Have to wait till the day SampleResult is extended to
// store results of all downloaded stuff e.g. images, applets etc
String fileInput = "<html>\n\n" +
- "<title>\n" +
- " A simple applet\n" +
- "</title>\n" +
- "<body background=\"back.jpg\" vlink=\"#dd0000\"
link=\"#0000ff\">\n" +
- "<center>\n" +
- "<h2> A simple applet\n" +
- "</h2>\n" +
- "<br>\n" +
- "<br>\n" +
- "<table>\n" +
- "<td width = 20>\n" +
- "<td width = 500 align = left>\n" +
- "<img src=\"/tomcat.gif\">\n" +
- "<img src=\"/tomcat.gif\">\n" +
- "<a href=\"Time.java\"> Read my code <a>\n" +
- "<p><applet code=Time.class width = 400 height = 200>\n" +
- "</applet>\n" +
- "<p><applet code=Time.class width = 400 height = 200>\n" +
- "</applet>\n" +
- "</table>\n" +
- "<form>\n" +
- " <input type=\"image\" src=\"/tomcat-power.gif\">\n" +
- "</form>\n" +
- "<form>\n" +
- " <input type=\"image\" src=\"/tomcat-power.gif\">\n" +
- "</form>\n" +
- "</body>\n" +
- "</html>\n";
+ "<title>\n" +
+ " A simple applet\n" +
+ "</title>\n" +
+ "<body background=\"back.jpg\" vlink=\"#dd0000\"
link=\"#0000ff\">\n" +
+ "<center>\n" +
+ "<h2> A simple applet\n" +
+ "</h2>\n" +
+ "<br>\n" +
+ "<br>\n" +
+ "<table>\n" +
+ "<td width = 20>\n" +
+ "<td width = 500 align = left>\n" +
+ "<img src=\"/tomcat.gif\">\n" +
+ "<img src=\"/tomcat.gif\">\n" +
+ "<a href=\"NervousText.java\"> Read my code <a>\n" +
+ "<p><applet code=NervousText.class width=400 height=200>\n" +
+ "</applet>\n" +
+ "<p><applet code=NervousText.class width=400 height=200>\n" +
+ "</applet>\n" +
+ "</table>\n" +
+ "<form>\n" +
+ " <input type=\"image\" src=\"/tomcat-power.gif\">\n" +
+ "</form>\n" +
+ "<form>\n" +
+ " <input type=\"image\" src=\"/tomcat-power.gif\">\n" +
+ "</form>\n" +
+ "</body>\n" +
+ "</html>\n";
byte[] bytes = fileInput.getBytes();
try
{
- FileOutputStream fos =
- new FileOutputStream("HTTPSamplerFullTestFile.txt");
- fos.write(bytes);
- fos.close();
+ FileOutputStream fos =
+ new FileOutputStream("HTTPSamplerFullTestFile.txt");
+ fos.write(bytes);
+ fos.close();
}
- catch(IOException e)
+ catch(IOException ioe)
{
- fail("Cannot create HTTPSamplerFullTestFile.txt in current directory
" +
- "for testing - " + e);
+ fail("Cannot create HTTPSamplerFullTestFile.txt in current
directory " +
+ "for testing - " + ioe);
}
// !ToDo
// hsf.sample(entry);
assertNull("Cannot think of way to test sample", null);
- catClass.debug("End : testSampleMain1");
- }
+ catClass.debug("End : testSampleMain");
+ }
- protected void tearDown()
- {
- catClass.debug("Start : tearDown1");
+ protected void tearDown()
+ {
+ catClass.debug("Start : tearDown");
hsf = null;
- catClass.debug("End : tearDown1");
- }
+ catClass.debug("End : tearDown");
+ }
- public static void main(String[] args)
- {
+ public static void main(String[] args)
+ {
BasicConfigurator.configure();
TestSuite suite = new TestSuite(Test.class);
junit.textui.TestRunner runner = new junit.textui.TestRunner();
runner.run(suite);
- }
- }
+ }
+}
}
--
To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>