FileDocCategorySizeDatePackage
TestEventHandler.javaAPI DocAndroid 1.5 API24125Wed May 06 22:42:02 BST 2009android.core

TestEventHandler

public class TestEventHandler extends Object implements EventHandler
Implements EventHandler and provides test functionality to validate responses to requests from the test server

Fields Summary
private int
majorVersion
Status variables
private int
minorVersion
private int
responseCode
private String
reasonPhrase
private Map
headerMap
public static final Object
syncObj
private boolean
useLowLevel
private boolean
delayResponse
public static final int
TEST_REQUEST_SENT
public static final int
TEST_STATUS
public static final int
TEST_HEADERS
public static final int
TEST_LOCATION_CHANGED
public static final int
TEST_DATA
public static final int
TEST_ENDDATA
public static final int
TEST_ERROR
public static final int
TEST_SSL_CERTIFICATE_ERROR
public static final int
TEST_NUM_EXPECTS
private int
expectMajor
private int
expectMinor
private int
expectCode
private boolean[]
expects
private boolean[]
notExpecting
private boolean[]
eventsReceived
private String
expectLocation
private int
expectPermanent
private byte[]
expectData
private int
expectDataLength
private int
expectErrorId
private int
expectSslErrors
private SslCertificate
expectCertificate
private ArrayList
expectHeaders
private StringBuffer
expectDetails
private RequestHandle
mRequestHandle
private LowLevelNetRunner
netRunner
protected static final String
LOGTAG
Constructors Summary
public TestEventHandler()


      
        for (int i = 0; i < TEST_NUM_EXPECTS; i++) {
            expects[i] = false;
            notExpecting[i] = false;
            eventsReceived[i] = false;
        }
    
Methods Summary
public voidattachRequestHandle(RequestHandle requestHandle)
Attach the RequestHandle to this handler

param
requestHandle The RequestHandle

        if (Config.LOGV) {
            Log.v(LOGTAG, "TestEventHandler.attachRequestHandle(): " +
                    "requestHandle: " +  requestHandle);
        }
        mRequestHandle = requestHandle;
    
public voidcertificate(SslCertificate certificate)
Implements the EventHandler certificate method called every time a resource is loaded via a secure connection

public voiddata(byte[] data, int len)
Implements the EventHandler data method called when a server sends content data

param
data The byte array content
param
len The length of the data

      boolean mismatch = false;

      if (Config.LOGV) {
        Log.v(LOGTAG, "TestEventHandler: data() " + len + " bytes");
      }

      eventsReceived[TEST_DATA] = true;
      if (notExpecting[TEST_DATA]) {
        expectDetails.append("Data event received but not expected");
        expectDetails.append("\r\n");
      }

      Log.v(LOGTAG, new String(data, 0, len));

      if (expectDataLength != -1) {
        if (expectDataLength == len) {
          expectDataLength = -1;
        } else {
          expectDetails.append("expect data length mismatch expected:"+
              expectDataLength+" got:"+len);
          expectDetails.append("\r\n");
        }

        /* Check data only if length is the same */
        if ((expectDataLength == -1) && expectData != null) {
          for (int i = 0; i < len; i++) {
            if (expectData[i] != data[i]) {
              mismatch = true;
              expectDetails.append("Expect data mismatch at byte "+
                  i+" expected:"+expectData[i]+" got:"+data[i]);
              expectDetails.append("\r\n");
              break;
            }
          }
        }
      }

      if ((expectDataLength == -1) || !mismatch)
        expects[TEST_DATA] = false;
    
public voiddetachRequestHandle()
Detach the RequestHandle

        if (Config.LOGV) {
            Log.v(LOGTAG, "TestEventHandler.detachRequestHandle(): " +
                    "requestHandle: " + mRequestHandle);
        }
        mRequestHandle = null;
    
public voidendData()
Implements the EventHandler endData method called to indicate completion or a request

      if (Config.LOGV) {
        Log.v(LOGTAG, "TestEventHandler: endData() called");
      }

      eventsReceived[TEST_ENDDATA] = true;
      if (notExpecting[TEST_ENDDATA]) {
        expectDetails.append("End data event received but not expected");
        expectDetails.append("\r\n");
      }

      expects[TEST_ENDDATA] = false;

      if (useLowLevel) {
        if (delayResponse) {
          synchronized (syncObj) {
            syncObj.notifyAll();
          }
        } else {
          if (netRunner != null) {
            System.out.println("TestEventHandler: endData() stopping "+
                netRunner);
            netRunner.decrementRunCount();
          }
        }
      }
    
public voiderror(int id, java.lang.String description)
Implements the EventHandler error method called when a server sends header fields

param
id Status code of the error
param
description Brief description of the error

      if (Config.LOGV) {
        Log.v(LOGTAG, "TestEventHandler: error() called Id:" + id +
            " description " + description);
      }

      eventsReceived[TEST_ERROR] = true;
      if (notExpecting[TEST_ERROR]) {
        expectDetails.append("Error event received but not expected");
        expectDetails.append("\r\n");
      }
      if (expectErrorId != -1) {
        if (expectErrorId == id) {
          expectErrorId = -1;
        } else {
          expectDetails.append("Error Id expected:"+expectErrorId+
              " got:"+id);
          expectDetails.append("\r\n");
        }
      }

      if (expectErrorId == -1)
        expects[TEST_ERROR] = false;

      if (useLowLevel) {
        if (delayResponse) {
          synchronized (syncObj) {
            syncObj.notifyAll();
          }
        } else {
          if (netRunner != null) {
            System.out.println("TestEventHandler: endData() stopping "+
                netRunner);
            netRunner.decrementRunCount();
          }
        }
      }
    
public booleanevaluateHeader(android.core.TestEventHandler$TestHeader h, java.lang.String value)

        if (value == null) {
            expects[TEST_HEADERS] = true;
            System.out.print(" Missing!  ");
            expectDetails.append(" missing header " + h.name);
            return false;
        }
        if (h.value == null) {
            System.out.println("Expect value = null");
            return true;
        }
        System.out.println("Expect value = " +
                (h.value.toLowerCase()) + " got " +
                value.toLowerCase());
        
        if (!h.value.equalsIgnoreCase(value)) {
            expectDetails.append("expect header value " + h.value +
                    " got " + value);
            expects[TEST_HEADERS] = true;
            return false;
        }
        return true;
    
public voidexpectData()

        expects[TEST_DATA] = true;
    
public voidexpectData(int len)

        expects[TEST_DATA] = true;
        expectDataLength = len;
    
public voidexpectData(byte[] data, int len)

        expects[TEST_DATA] = true;
        expectData = new byte[len];
        expectDataLength = len;

        for (int i = 0; i < len; i++) {
            expectData[i] = data[i];
        }
    
public voidexpectEndData()

        expects[TEST_ENDDATA] = true;
    
public voidexpectError()

        expects[TEST_ERROR] = true;
    
public voidexpectError(int errorId)

        expects[TEST_ERROR] = true;
        expectErrorId = errorId;
    
public voidexpectHeaderAdd(java.lang.String name)

        expects[TEST_HEADERS] = true;
        TestHeader h = new TestHeader(name.toLowerCase(), null);
        expectHeaders.add(h);
    
public voidexpectHeaderAdd(java.lang.String name, java.lang.String value)

        expects[TEST_HEADERS] = true;
        TestHeader h = new TestHeader(name.toLowerCase(), value);
        expectHeaders.add(h);
    
public voidexpectHeaders()

        expects[TEST_HEADERS] = true;
    
public voidexpectLocationChanged()

        expects[TEST_LOCATION_CHANGED] = true;
    
public voidexpectLocationChanged(java.lang.String newLocation)

        expects[TEST_LOCATION_CHANGED] = true;
        expectLocation = newLocation;
    
public voidexpectLocationChanged(java.lang.String newLocation, boolean permanent)

        expects[TEST_LOCATION_CHANGED] = true;
        expectLocation = newLocation;
        expectPermanent = permanent ? 1 : 0;
    
public voidexpectNoData()

        notExpecting[TEST_DATA] = true;
    
public voidexpectNoEndData()

            notExpecting[TEST_ENDDATA] = true;
    
public voidexpectNoError()

        notExpecting[TEST_ERROR] = true;
    
public voidexpectNoHeaders()

        notExpecting[TEST_HEADERS] = true;
    
public voidexpectNoLocationChanged()

            notExpecting[TEST_LOCATION_CHANGED] = true;
    
public voidexpectNoRequestSent()

        notExpecting[TEST_REQUEST_SENT] = true;
    
public voidexpectNoSSLCertificateError()

            notExpecting[TEST_SSL_CERTIFICATE_ERROR] = true;
    
public voidexpectNoStatus()

        notExpecting[TEST_STATUS] = true;
    
public booleanexpectPassed()
Test to see if current expectations match recieved information

return
True is all expected results have been matched

        for (int i = 0; i < TEST_NUM_EXPECTS; i++) {
            if (expects[i] == true) {
                return false;
            }
        }

        for (int i = 0; i < TEST_NUM_EXPECTS; i++) {
            if (eventsReceived[i] && notExpecting[i]) {
                return false;
            }
        }
        return true;
    
public voidexpectRequestSent()

        expects[TEST_REQUEST_SENT] = true;
    
public voidexpectSSLCertificateError()

        expects[TEST_SSL_CERTIFICATE_ERROR] = true;
    
public voidexpectSSLCertificateError(int errors)

        expects[TEST_SSL_CERTIFICATE_ERROR] = true;
        expectSslErrors = errors;
    
public voidexpectSSLCertificateError(SslCertificate certificate)

        expects[TEST_SSL_CERTIFICATE_ERROR] = true;
        expectCertificate = certificate;
    
public voidexpectStatus()

        expects[TEST_STATUS] = true;
    
public voidexpectStatus(int major, int minor, int code)

        expects[TEST_STATUS] = true;
        expectMajor = major;
        expectMinor = minor;
        expectCode = code;
    
public voidexpectStatus(int code)

        expects[TEST_STATUS] = true;
        expectCode = code;
    
public java.lang.StringgetFailureMessage()
Return message indicating expectation failures

        return expectDetails.toString();
    
public voidhandleSslErrorRequest(SslError error)
SSL certificate error callback. Handles SSL error(s) on the way up to the user.

      int primaryError = error.getPrimaryError();

      if (Config.LOGV) {
        Log.v(LOGTAG, "TestEventHandler: handleSslErrorRequest(): "+
              " primary error:" + primaryError +
              " certificate: " + error.getCertificate());
      }

      eventsReceived[TEST_SSL_CERTIFICATE_ERROR] = true;
      if (notExpecting[TEST_SSL_CERTIFICATE_ERROR]) {
        expectDetails.append("SSL Certificate error event received "+
            "but not expected");
        expectDetails.append("\r\n");
      }

      if (expectSslErrors != -1) {
        if (expectSslErrors == primaryError) {
            expectSslErrors = -1;
        } else {
            expectDetails.append("SslCertificateError id expected:"+
                expectSslErrors+" got: " + primaryError);
            expectDetails.append("\r\n");
        }
      }

      // SslCertificate match here?

      if (expectSslErrors == -1) // && expectSslCertificate == certificate?
        expects[TEST_SSL_CERTIFICATE_ERROR] = false;
    
public voidheaders(Headers headers)
Implements the EventHandler headers method called when a server sends header fields

        if (Config.LOGV) {
            Log.v(LOGTAG, "TestEventHandler:headers()");
        }
        expects[TEST_HEADERS] = false;

        if (notExpecting[TEST_HEADERS]) {
            expectDetails.append("Header event received but not expected");
            expectDetails.append("\r\n");
        }

        /* Check through headers received for matches with expected
         * headers */
        if (expectHeaders.isEmpty()) {
            return;
        }      
        
        for (int i = expectHeaders.size() - 1; i >= 0; i--) {
            TestHeader h =  expectHeaders.get(i);
            System.out.println("Expected header name: " + h.name);
            String s = null;
            switch (h.name.hashCode()) {
            case -1132779846:
                s = Long.toString(headers.getContentLength());
                break;
            case 785670158:
                s = headers.getContentType();
                break;
            case 2095084583:
                s = headers.getContentEncoding();
                break;
            case 1901043637:
                s = headers.getLocation();
                break;
            case -243037365:
                s = headers.getWwwAuthenticate();
                break;
            case -301767724:
                s = headers.getProxyAuthenticate();
                break;
            case -1267267485:
                s = headers.getContentDisposition();
                break;
            case 1397189435:
                s = headers.getAcceptRanges();
                break;
            case -1309235404:
                s = headers.getExpires();
                break;
            case -208775662:
                s = headers.getCacheControl();
                break;
            case 150043680:
                s = headers.getLastModified();
                break;
            case 3123477:
                s = headers.getEtag();
                break;
            case -775651618:
                int ct = headers.getConnectionType();
                if (ct == Headers.CONN_CLOSE) {
                    s = HTTP.CONN_CLOSE;
                } else if (ct == Headers.CONN_KEEP_ALIVE) {
                    s = HTTP.CONN_KEEP_ALIVE;
                }
                break;
            default:
                s = null;
                
            }
            if (evaluateHeader(h, s)) {
                expectHeaders.remove(i);
            }
        }
            
    
public voidlocationChanged(java.lang.String newLocation, boolean permanent)
Implements the EventHandler locationChanged method called when a server sends a redirect message

param
newLocation The URL to the new server
param
permanent Indicator of whether this is a permanent change

      if (Config.LOGV) {
        Log.v(LOGTAG, "TestEventHandler: locationChanged() " +
            newLocation + " permanent " + permanent);
      }

      eventsReceived[TEST_LOCATION_CHANGED] = true;
      if (notExpecting[TEST_LOCATION_CHANGED]) {
        expectDetails.append("Location changed event received but "+
            "not expected");
        expectDetails.append("\r\n");
      }

      if (expectLocation != null) {
        if (expectLocation.equals(newLocation)) {
          expectLocation = null;
        } else {
          expectDetails.append("Location expected:"+expectLocation+
              " got:"+newLocation);
          expectDetails.append("\r\n");
        }
      }

      if (expectPermanent != -1) {
        if (((expectPermanent == 0) && !permanent) ||
            ((expectPermanent == 1) && permanent)){
          expectPermanent = -1;
        } else {
          expectDetails.append("Location permanent expected:"+
              expectPermanent+" got"+permanent);
          expectDetails.append("\r\n");
        }
      }

      if ((expectLocation == null) && (expectPermanent == -1))
        expects[TEST_LOCATION_CHANGED] = false;
    
public voidrequestSent()
Implementation of EventHandler method called when a request has been sent. If the test is waiting for this call, it will be signalled, otherwise this method will trigger the response to be read automatically.

      Log.v(LOGTAG, "TestEventHandler:requestSent()");
      expects[TEST_REQUEST_SENT] = false;
      eventsReceived[TEST_REQUEST_SENT] = true;
      if (notExpecting[TEST_REQUEST_SENT]) {
          expectDetails.append("Request sent event received but not expected");
          expectDetails.append("\r\n");
      }

      if (useLowLevel) {
        if (delayResponse) {
          synchronized (syncObj) {
            syncObj.notifyAll();
          }
        } else {
            // mRequest.startReadingResponse();
        }
      }
    
public voidresetExpects()
Reset all expectation values for re-use

        expectMajor = -1;
        expectMinor = -1;
        expectCode = -1;
        expectLocation = null;
        expectPermanent = -1;
        expectErrorId = -1;
        expectSslErrors = -1;
        expectCertificate = null;
        expectDetails.setLength(0);
        expectHeaders.clear();

        for (int i = 0; i < TEST_NUM_EXPECTS; i++) {
            expects[i] = false;
            notExpecting[i] = false;
            eventsReceived[i] = false;
        }

        for (int i = 0; i < expectDataLength; i++) {
            expectData[i] = 0;
        }

        expectDataLength = -1;
    
public voidsetNetRunner(LowLevelNetRunner runner)
Use the low level net runner with no delayed response

param
runner The LowLevelNetRunner object

      setNetRunner(runner, false);
    
public voidsetNetRunner(LowLevelNetRunner runner, boolean delayedResponse)
Use the low level net runner and specify if the response should be delayed

param
runner The LowLevelNetRunner object
param
delayedResponse Set to true is you will use the waitForRequestSent/waitForRequestResponse routines

      netRunner = runner;
      useLowLevel = true;
      delayResponse = delayedResponse;

      if (!delayResponse)
        netRunner.incrementRunCount();
    
public voidstatus(int major_version, int minor_version, int code, java.lang.String reason_phrase)
Implements the EventHandler status method called when a server status response is received.

param
major_version The HTTP major version
param
minor_version The HTTP minor version
param
code The status code
param
reason_phrase A reason phrase passed to us by the server

      if (Config.LOGV) {
        Log.v(LOGTAG, "TestEventHandler:status() major: " + major_version +
            " minor: " + minor_version +
            " code: " + code +
            " reason: " + reason_phrase);
      }

      eventsReceived[TEST_STATUS] = true;
      if (notExpecting[TEST_STATUS]) {
        expectDetails.append("Status event received but not expected");
        expectDetails.append("\r\n");
      }

      majorVersion = major_version;
      minorVersion = minor_version;
      responseCode = code;
      reasonPhrase = reason_phrase;

      if (expectMajor != -1) {
        if (expectMajor == major_version) {
          expectMajor = -1;
        } else {
          expectDetails.append("Major version expected:"+expectMajor+
              " got:"+major_version);
          expectDetails.append("\r\n");
        }
      }

      if (expectMinor != -1) {
        if (expectMinor == minor_version) {
          expectMinor = -1;
        } else {
          expectDetails.append("Minor version expected:"+expectMinor+
              " got:"+minor_version);
          expectDetails.append("\r\n");
        }
      }

      if (expectCode != -1) {
        if (expectCode == code) {
          expectCode = -1;
        } else {
          expectDetails.append("Status code expected:"+expectCode+
              " got:"+code);
          expectDetails.append("\r\n");
        }
      }


      if ((expectMajor == -1) && (expectMinor == -1) && (expectCode == -1)) {
        expects[TEST_STATUS] = false;
      } else {
        System.out.println("MAJOR = "+expectMajor+" MINOR = "+expectMinor+
            " CODE = "+expectCode);
      }
    
public voidwaitForRequestResponse()
Enable this listeners Request object to read server responses. This should only be used in conjunction with setDelayResponse(true)

      if (!delayResponse || !useLowLevel) {
        Log.d(LOGTAG, " Cant do this without delayReponse set ");
        return;
      }

      //if (mRequest != null) {
          // mRequest.startReadingResponse();
      // }
      /* Now wait for the response to be completed either through endData
       * or an error
       */
      synchronized (syncObj) {
        try {
          syncObj.wait();
        } catch (InterruptedException e) {
        }
      }
    
public voidwaitForRequestSent()
Enable this listeners Request object to read server responses. This should only be used in conjunction with setDelayResponse(true)

      if (!delayResponse || !useLowLevel) {
        Log.d(LOGTAG, " Cant do this without delayReponse set ");
        return;
      }

      /* Now wait for the response to be completed either through endData
       * or an error
       */
      synchronized (syncObj) {
        try {
          syncObj.wait();
        } catch (InterruptedException e) {
        }
      }