com.duowan.mobile.netroid
Class Request<T>

java.lang.Object
  extended by com.duowan.mobile.netroid.Request<T>
All Implemented Interfaces:
java.lang.Comparable<Request<T>>
Direct Known Subclasses:
FileDownloadRequest, ImageRequest, JsonRequest, StringRequest

public abstract class Request<T>
extends java.lang.Object
implements java.lang.Comparable<Request<T>>

Base class for all network requests. ` * @param The type of parsed response this request expects.


Nested Class Summary
static interface Request.Method
          Supported request methods.
static class Request.Priority
          Priority values.
 
Constructor Summary
Request(int method, java.lang.String url, Listener<T> listener)
          Creates a new request with the given method (one of the values from Request.Method), URL, and error listener.
Request(java.lang.String url, Listener<T> listener)
          Creates a new request with GET method
 
Method Summary
 void addHeader(java.lang.String field, java.lang.String value)
          Put a Header to RequestHeaders.
 void addMarker(java.lang.String tag)
          Adds an event to this request's event log; for debugging.
 void cancel()
          Mark this request as canceled.
 int compareTo(Request<T> other)
          Our comparator sorts from high to low priority, and secondarily by sequence number to provide FIFO ordering.
 void deliverCancel()
          Delivers request has truly cancelled to the Listener.
 void deliverDownloadProgress(long fileSize, long downloadedSize)
          Delivers when download request progress change to the Listener.
 void deliverError(NetroidError error)
          Delivers error message to the Listener that the Request was initialized with.
 void deliverFinish()
          Delivers when cache used to the Listener.
 void deliverNetworking()
          Delivers when request going to do networking to the Listener.
 void deliverPreExecute()
          Delivers request is handling to the Listener.
 void deliverRetry()
          Delivers when request timeout and retry to the Listener.
 void deliverSuccess(T response)
          Perform delivery of the parsed response.
 void deliverUsedCache()
          Delivers when cache used to the Listener.
 void finish(java.lang.String tag)
          Notifies the request queue that this request has finished (successfully or with error).
 byte[] getBody()
          Returns the raw POST or PUT body to be sent.
 java.lang.String getBodyContentType()
           
 long getCacheExpireTime()
           
 java.lang.String getCacheKey()
          Returns the cache key for this request.
 java.util.Map<java.lang.String,java.lang.String> getHeaders()
          Returns a list of extra HTTP headers to go along with this request.
 int getMethod()
          Return the method for this request.
protected  java.util.Map<java.lang.String,java.lang.String> getParams()
          Returns a Map of parameters to be used for a POST or PUT request.
protected  java.lang.String getParamsEncoding()
          Returns which encoding should be used when converting POST or PUT parameters returned by getParams() into a raw POST or PUT body.
 Request.Priority getPriority()
          Returns the Request.Priority of this request; Request.Priority.NORMAL by default.
 RetryPolicy getRetryPolicy()
          Returns the retry policy that should be used for this request.
 int getSequence()
          Returns the sequence number of this request.
 java.lang.Object getTag()
          Returns this request's tag.
 int getTimeoutMs()
          Returns the socket timeout in milliseconds per retry attempt.
 java.lang.String getUrl()
          Returns the URL of this request.
 byte[] handleResponse(org.apache.http.HttpResponse response, Delivery delivery)
          Handle the response for various request, normally, a request was a short and low memory-usage request, thus we can parse the response-content as byte[] in memory.
 boolean hasHadResponseDelivered()
          Returns true if this request has had a response delivered for it.
 boolean isCanceled()
          Returns true if this request has been canceled.
 boolean isForceUpdate()
          Ask if should force update.
 void markDelivered()
          Mark this request as having a response delivered on it.
protected  NetroidError parseNetworkError(NetroidError netroidError)
          Subclasses can override this method to parse 'networkError' and return a more specific error.
protected abstract  Response<T> parseNetworkResponse(NetworkResponse response)
          Subclasses must implement this to parse the raw network response and return an appropriate response type.
 NetworkResponse perform()
          By default, everyone Request is http-base request, if you wants to load local file or perform others, also wants to use Cache, you can override this method to implement non-http request.
 void prepare()
          Prepare to execute, invoke before HttpStack.performRequest(com.duowan.mobile.netroid.Request).
 void removeHeader(java.lang.String field)
          Remove a header from RequestHeaders
 void setCacheExpireTime(java.util.concurrent.TimeUnit timeUnit, int amount)
          Set how long the cache is expired, DiskCache will determine the cache entry is expired or not.
 void setForceUpdate(boolean forceUpdate)
          tell Network should force update or no.
 void setListener(Listener<T> listener)
          Set the response listener.
 void setRequestQueue(RequestQueue requestQueue)
          Associates this request with the given queue.
 void setRetryPolicy(RetryPolicy retryPolicy)
          Sets the retry policy for this request.
 void setSequence(int sequence)
          Sets the sequence number of this request.
 void setTag(java.lang.Object tag)
          Set a tag on this request.
 boolean shouldCache()
          Returns true if responses to this request should be cached.
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Request

public Request(int method,
               java.lang.String url,
               Listener<T> listener)
Creates a new request with the given method (one of the values from Request.Method), URL, and error listener. Note that the normal response listener is not provided here as delivery of responses is provided by subclasses, who have a better idea of how to deliver an already-parsed response.


Request

public Request(java.lang.String url,
               Listener<T> listener)
Creates a new request with GET method

Method Detail

getMethod

public int getMethod()
Return the method for this request. Can be one of the values in Request.Method.


setListener

public void setListener(Listener<T> listener)
Set the response listener.


setTag

public void setTag(java.lang.Object tag)
Set a tag on this request. Can be used to cancel all requests with this tag by RequestQueue.cancelAll(Object).


getTag

public java.lang.Object getTag()
Returns this request's tag.

See Also:
setTag(Object)

setRetryPolicy

public void setRetryPolicy(RetryPolicy retryPolicy)
Sets the retry policy for this request.


addMarker

public void addMarker(java.lang.String tag)
Adds an event to this request's event log; for debugging.


finish

public void finish(java.lang.String tag)
Notifies the request queue that this request has finished (successfully or with error).

Also dumps all events from this request's event log; for debugging.


setRequestQueue

public void setRequestQueue(RequestQueue requestQueue)
Associates this request with the given queue. The request queue will be notified when this request has finished.


setSequence

public final void setSequence(int sequence)
Sets the sequence number of this request. Used by RequestQueue.


getSequence

public final int getSequence()
Returns the sequence number of this request.


getUrl

public java.lang.String getUrl()
Returns the URL of this request.


getCacheKey

public java.lang.String getCacheKey()
Returns the cache key for this request. By default, this is the URL.


isForceUpdate

public boolean isForceUpdate()
Ask if should force update.


setForceUpdate

public void setForceUpdate(boolean forceUpdate)
tell Network should force update or no.


getCacheExpireTime

public long getCacheExpireTime()

setCacheExpireTime

public void setCacheExpireTime(java.util.concurrent.TimeUnit timeUnit,
                               int amount)
Set how long the cache is expired, DiskCache will determine the cache entry is expired or not. For example : Request.setCacheExpireTime(TimeUnit.MINUTES, 1); // cache stays one minute Request.setCacheExpireTime(TimeUnit.DAYS, 2); // cache stays two days

Parameters:
timeUnit - what unit for the amount value
amount - how much unit should calculate

cancel

public void cancel()
Mark this request as canceled. No callback will be delivered.


isCanceled

public boolean isCanceled()
Returns true if this request has been canceled.


getHeaders

public final java.util.Map<java.lang.String,java.lang.String> getHeaders()
                                                                  throws AuthFailureError
Returns a list of extra HTTP headers to go along with this request. Can throw AuthFailureError as authentication may be required to provide these values.

Throws:
AuthFailureError - In the event of auth failure

addHeader

public final void addHeader(java.lang.String field,
                            java.lang.String value)
Put a Header to RequestHeaders.

Parameters:
field - header key
value - header value

removeHeader

public final void removeHeader(java.lang.String field)
Remove a header from RequestHeaders

Parameters:
field - header key

getParams

protected java.util.Map<java.lang.String,java.lang.String> getParams()
                                                              throws AuthFailureError
Returns a Map of parameters to be used for a POST or PUT request. Can throw AuthFailureError as authentication may be required to provide these values.

Note that you can directly override getBody() for custom data.

Throws:
AuthFailureError - in the event of auth failure

getParamsEncoding

protected java.lang.String getParamsEncoding()
Returns which encoding should be used when converting POST or PUT parameters returned by getParams() into a raw POST or PUT body.

This controls both encodings:

  1. The string encoding used when converting parameter names and values into bytes prior to URL encoding them.
  2. The string encoding used when converting the URL encoded parameters into a raw byte array.


getBodyContentType

public java.lang.String getBodyContentType()

getBody

public byte[] getBody()
               throws AuthFailureError
Returns the raw POST or PUT body to be sent.

Throws:
AuthFailureError - in the event of auth failure

prepare

public void prepare()
Prepare to execute, invoke before HttpStack.performRequest(com.duowan.mobile.netroid.Request). it's original purpose is reset some request parameters after timeout then retry, especially headers, the situation is when you have some headers need to init or reset every perform, for example the "Range" header for download a file, you obviously must retrieve the begin position of file and reset the "Range" for every time you going to retry, so that's why we add this method.


handleResponse

public byte[] handleResponse(org.apache.http.HttpResponse response,
                             Delivery delivery)
                      throws java.io.IOException,
                             ServerError
Handle the response for various request, normally, a request was a short and low memory-usage request, thus we can parse the response-content as byte[] in memory. However the FileDownloadRequest itself was a large memory-usage case, that's inadvisable for parse all response content to memory, so it had self-implement mechanism.

Throws:
java.io.IOException
ServerError

perform

public NetworkResponse perform()
By default, everyone Request is http-base request, if you wants to load local file or perform others, also wants to use Cache, you can override this method to implement non-http request.


shouldCache

public final boolean shouldCache()
Returns true if responses to this request should be cached.


getPriority

public Request.Priority getPriority()
Returns the Request.Priority of this request; Request.Priority.NORMAL by default.


getTimeoutMs

public final int getTimeoutMs()
Returns the socket timeout in milliseconds per retry attempt. (This value can be changed per retry attempt if a backoff is specified via backoffTimeout()). If there are no retry attempts remaining, this will cause delivery of a TimeoutError error.


getRetryPolicy

public RetryPolicy getRetryPolicy()
Returns the retry policy that should be used for this request.


markDelivered

public void markDelivered()
Mark this request as having a response delivered on it. This can be used later in the request's lifetime for suppressing identical responses.


hasHadResponseDelivered

public boolean hasHadResponseDelivered()
Returns true if this request has had a response delivered for it.


parseNetworkResponse

protected abstract Response<T> parseNetworkResponse(NetworkResponse response)
Subclasses must implement this to parse the raw network response and return an appropriate response type. This method will be called from a worker thread. The response will not be delivered if you return null.

Parameters:
response - Response from the network
Returns:
The parsed response, or null in the case of an error

parseNetworkError

protected NetroidError parseNetworkError(NetroidError netroidError)
Subclasses can override this method to parse 'networkError' and return a more specific error.

The default implementation just returns the passed 'networkError'.

Parameters:
netroidError - the error retrieved from the network
Returns:
an NetworkError augmented with additional information

deliverSuccess

public void deliverSuccess(T response)
Perform delivery of the parsed response. The given response is guaranteed to be non-null; responses that fail to parse are not delivered.

Parameters:
response - The parsed response returned by parseNetworkResponse(NetworkResponse)

deliverError

public void deliverError(NetroidError error)
Delivers error message to the Listener that the Request was initialized with.

Parameters:
error - Error details

deliverCancel

public void deliverCancel()
Delivers request has truly cancelled to the Listener.


deliverPreExecute

public void deliverPreExecute()
Delivers request is handling to the Listener.


deliverUsedCache

public void deliverUsedCache()
Delivers when cache used to the Listener.


deliverFinish

public void deliverFinish()
Delivers when cache used to the Listener.


deliverRetry

public void deliverRetry()
Delivers when request timeout and retry to the Listener.


deliverNetworking

public void deliverNetworking()
Delivers when request going to do networking to the Listener.


deliverDownloadProgress

public void deliverDownloadProgress(long fileSize,
                                    long downloadedSize)
Delivers when download request progress change to the Listener.


compareTo

public int compareTo(Request<T> other)
Our comparator sorts from high to low priority, and secondarily by sequence number to provide FIFO ordering.

Specified by:
compareTo in interface java.lang.Comparable<Request<T>>

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object