Search in sources :

Example 1 with NoNetworkException

use of com.octo.android.robospice.exception.NoNetworkException in project robospice by stephanenicolas.

the class DefaultRequestRunner method processRequest.

protected <T> void processRequest(final CachedSpiceRequest<T> request) {
    final long startTime = System.currentTimeMillis();
    Ln.d("Processing request : " + request);
    T result = null;
    // add a progress listener to the request to be notified of
    // progress during load data from network
    final RequestProgressListener requestProgressListener = requestProgressManager.createProgressListener(request);
    request.setRequestProgressListener(requestProgressListener);
    if (request.getRequestCacheKey() != null && request.getCacheDuration() != DurationInMillis.ALWAYS_EXPIRED) {
        // First, search data in cache
        try {
            Ln.d("Loading request from cache : " + request);
            request.setStatus(RequestStatus.READING_FROM_CACHE);
            result = loadDataFromCache(request.getResultType(), request.getRequestCacheKey(), request.getCacheDuration());
            // request
            if (result != null) {
                Ln.d("Request loaded from cache : " + request + " result=" + result);
                requestProgressManager.notifyListenersOfRequestSuccess(request, result);
                printRequestProcessingDuration(startTime, request);
                return;
            } else if (request.isAcceptingDirtyCache()) {
                // as a fallback, some request may accept whatever is in the
                // cache but still
                // want an update from network.
                result = loadDataFromCache(request.getResultType(), request.getRequestCacheKey(), DurationInMillis.ALWAYS_RETURNED);
                if (result != null) {
                    requestProgressManager.notifyListenersOfRequestSuccessButDontCompleteRequest(request, result);
                }
            }
        } catch (final SpiceException e) {
            Ln.d(e, "Cache file could not be read.");
            if (failOnCacheError) {
                handleRetry(request, e);
                printRequestProcessingDuration(startTime, request);
                return;
            }
            cacheManager.removeDataFromCache(request.getResultType(), request.getRequestCacheKey());
            Ln.d(e, "Cache file deleted.");
        }
    }
    // if result is not in cache, load data from network
    Ln.d("Cache content not available or expired or disabled");
    if (!networkStateChecker.isNetworkAvailable(applicationContext) && !request.isOffline()) {
        Ln.e("Network is down.");
        if (!request.isCancelled()) {
            // don't retry when there is no network
            requestProgressManager.notifyListenersOfRequestFailure(request, new NoNetworkException());
        }
        printRequestProcessingDuration(startTime, request);
        return;
    }
    // network is ok, load data from network
    try {
        if (request.isCancelled()) {
            printRequestProcessingDuration(startTime, request);
            return;
        }
        Ln.d("Calling netwok request.");
        request.setStatus(RequestStatus.LOADING_FROM_NETWORK);
        result = request.loadDataFromNetwork();
        Ln.d("Network request call ended.");
    } catch (final Exception e) {
        if (!request.isCancelled()) {
            Ln.e(e, "An exception occurred during request network execution :" + e.getMessage());
            handleRetry(request, new NetworkException("Exception occurred during invocation of web service.", e));
        } else {
            Ln.e("An exception occurred during request network execution but request was cancelled, so listeners are not called.");
        }
        printRequestProcessingDuration(startTime, request);
        return;
    }
    if (result != null && request.getRequestCacheKey() != null) {
        // it to cache
        try {
            if (request.isCancelled()) {
                printRequestProcessingDuration(startTime, request);
                return;
            }
            Ln.d("Start caching content...");
            request.setStatus(RequestStatus.WRITING_TO_CACHE);
            result = saveDataToCacheAndReturnData(result, request.getRequestCacheKey());
            if (request.isCancelled()) {
                printRequestProcessingDuration(startTime, request);
                return;
            }
            requestProgressManager.notifyListenersOfRequestSuccess(request, result);
            printRequestProcessingDuration(startTime, request);
            return;
        } catch (final SpiceException e) {
            Ln.d(e, "An exception occurred during service execution :" + e.getMessage());
            if (failOnCacheError) {
                handleRetry(request, e);
                printRequestProcessingDuration(startTime, request);
                return;
            } else {
                if (request.isCancelled()) {
                    printRequestProcessingDuration(startTime, request);
                    return;
                }
                // result can't be saved to
                // cache but we reached that
                // point after a success of load
                // data from
                // network
                requestProgressManager.notifyListenersOfRequestSuccess(request, result);
            }
            cacheManager.removeDataFromCache(request.getResultType(), request.getRequestCacheKey());
            Ln.d(e, "Cache file deleted.");
        }
    } else {
        // result can't be saved to cache but we reached
        // that point after a success of load data from
        // network
        requestProgressManager.notifyListenersOfRequestSuccess(request, result);
        printRequestProcessingDuration(startTime, request);
        return;
    }
}
Also used : RequestProgressListener(com.octo.android.robospice.request.listener.RequestProgressListener) NoNetworkException(com.octo.android.robospice.exception.NoNetworkException) SpiceException(com.octo.android.robospice.persistence.exception.SpiceException) NetworkException(com.octo.android.robospice.exception.NetworkException) NoNetworkException(com.octo.android.robospice.exception.NoNetworkException) CacheSavingException(com.octo.android.robospice.persistence.exception.CacheSavingException) CacheCreationException(com.octo.android.robospice.persistence.exception.CacheCreationException) SpiceException(com.octo.android.robospice.persistence.exception.SpiceException) NetworkException(com.octo.android.robospice.exception.NetworkException) NoNetworkException(com.octo.android.robospice.exception.NoNetworkException) CacheLoadingException(com.octo.android.robospice.persistence.exception.CacheLoadingException)

Example 2 with NoNetworkException

use of com.octo.android.robospice.exception.NoNetworkException in project robospice by stephanenicolas.

the class RequestProcessorTest method testAddRequestWhenNetworkIsDown_and_request_has_retry_policy.

public void testAddRequestWhenNetworkIsDown_and_request_has_retry_policy() throws CacheLoadingException, SpiceException, InterruptedException, Exception {
    // given
    CachedSpiceRequestStub<String> stubRequest = createSuccessfulRequest(TEST_CLASS, TEST_CACHE_KEY, TEST_DURATION, TEST_RETURNED_DATA);
    DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(TEST_RETRY_COUNT, TEST_DELAY_BEFORE_RETRY, TEST_RETRY_BACKOFF_MULTIPLIER);
    stubRequest.setRetryPolicy(retryPolicy);
    RequestListenerStub<String> mockRequestListener = new RequestListenerStub<String>();
    Set<RequestListener<?>> requestListenerSet = new HashSet<RequestListener<?>>();
    requestListenerSet.add(mockRequestListener);
    EasyMock.expect(mockCacheManager.loadDataFromCache(EasyMock.eq(TEST_CLASS), EasyMock.eq(TEST_CACHE_KEY), EasyMock.eq(TEST_DURATION))).andReturn(null);
    EasyMock.expectLastCall().times(1);
    EasyMock.replay(mockCacheManager);
    // when
    requestProcessorUnderTest.setFailOnCacheError(true);
    networkStateChecker.setNetworkAvailable(false);
    requestProcessorUnderTest.addRequest(stubRequest, requestListenerSet);
    mockRequestListener.await(REQUEST_COMPLETION_TIME_OUT);
    // then
    assertNotNull(stubRequest.getRetryPolicy());
    assertEquals(TEST_RETRY_COUNT, stubRequest.getRetryPolicy().getRetryCount());
    EasyMock.verify(mockCacheManager);
    assertFalse(stubRequest.isLoadDataFromNetworkCalled());
    assertTrue(mockRequestListener.isExecutedInUIThread());
    assertFalse(mockRequestListener.isSuccessful());
    assertTrue(mockRequestListener.getReceivedException() instanceof NoNetworkException);
}
Also used : RequestListener(com.octo.android.robospice.request.listener.RequestListener) NoNetworkException(com.octo.android.robospice.exception.NoNetworkException) DefaultRetryPolicy(com.octo.android.robospice.retry.DefaultRetryPolicy) RequestListenerStub(com.octo.android.robospice.stub.RequestListenerStub) HashSet(java.util.HashSet)

Example 3 with NoNetworkException

use of com.octo.android.robospice.exception.NoNetworkException in project robospice by stephanenicolas.

the class RequestProcessorTest method testAddRequestWhenNetworkIsDown.

// ============================================================================================
// TESTING NETWORK MANAGER DEPENDENCY & SPICE LISTENER
// ============================================================================================
public void testAddRequestWhenNetworkIsDown() throws CacheLoadingException, CacheSavingException, InterruptedException, CacheCreationException {
    // given
    CachedSpiceRequestStub<String> stubRequest = createSuccessfulRequest(TEST_CLASS, TEST_CACHE_KEY, TEST_DURATION, TEST_RETURNED_DATA);
    stubRequest.setRetryPolicy(null);
    RequestListenerStub<String> mockRequestListener = new RequestListenerStub<String>();
    Set<RequestListener<?>> requestListenerSet = new HashSet<RequestListener<?>>();
    requestListenerSet.add(mockRequestListener);
    EasyMock.expect(mockCacheManager.loadDataFromCache(EasyMock.eq(TEST_CLASS), EasyMock.eq(TEST_CACHE_KEY), EasyMock.eq(TEST_DURATION))).andReturn(null);
    EasyMock.replay(mockCacheManager);
    SpiceServiceListener mockSpiceServiceListener = EasyMock.createMock(SpiceServiceListener.class);
    mockSpiceServiceListener.onRequestAdded((CachedSpiceRequest<?>) EasyMock.anyObject(), (RequestProcessingContext) EasyMock.anyObject());
    mockSpiceServiceListener.onRequestProgressUpdated((CachedSpiceRequest<?>) EasyMock.anyObject(), (RequestProcessingContext) EasyMock.anyObject());
    EasyMock.expectLastCall().anyTimes();
    mockSpiceServiceListener.onRequestFailed((CachedSpiceRequest<?>) EasyMock.anyObject(), (RequestProcessingContext) EasyMock.anyObject());
    mockSpiceServiceListener.onRequestProcessed((CachedSpiceRequest<?>) EasyMock.anyObject(), (RequestProcessingContext) EasyMock.anyObject());
    EasyMock.expectLastCall().anyTimes();
    EasyMock.replay(mockSpiceServiceListener);
    requestProcessorUnderTest.addSpiceServiceListener(mockSpiceServiceListener);
    // when
    requestProcessorUnderTest.setFailOnCacheError(true);
    networkStateChecker.setNetworkAvailable(false);
    requestProcessorUnderTest.addRequest(stubRequest, requestListenerSet);
    mockRequestListener.await(REQUEST_COMPLETION_TIME_OUT);
    // then
    EasyMock.verify(mockCacheManager);
    assertFalse(stubRequest.isLoadDataFromNetworkCalled());
    assertTrue(mockRequestListener.isExecutedInUIThread());
    assertFalse(mockRequestListener.isSuccessful());
    assertTrue(mockRequestListener.getReceivedException() instanceof NoNetworkException);
    EasyMock.verify(mockSpiceServiceListener);
}
Also used : RequestListener(com.octo.android.robospice.request.listener.RequestListener) NoNetworkException(com.octo.android.robospice.exception.NoNetworkException) SpiceServiceListener(com.octo.android.robospice.request.listener.SpiceServiceListener) RequestListenerStub(com.octo.android.robospice.stub.RequestListenerStub) HashSet(java.util.HashSet)

Aggregations

NoNetworkException (com.octo.android.robospice.exception.NoNetworkException)3 RequestListener (com.octo.android.robospice.request.listener.RequestListener)2 RequestListenerStub (com.octo.android.robospice.stub.RequestListenerStub)2 HashSet (java.util.HashSet)2 NetworkException (com.octo.android.robospice.exception.NetworkException)1 CacheCreationException (com.octo.android.robospice.persistence.exception.CacheCreationException)1 CacheLoadingException (com.octo.android.robospice.persistence.exception.CacheLoadingException)1 CacheSavingException (com.octo.android.robospice.persistence.exception.CacheSavingException)1 SpiceException (com.octo.android.robospice.persistence.exception.SpiceException)1 RequestProgressListener (com.octo.android.robospice.request.listener.RequestProgressListener)1 SpiceServiceListener (com.octo.android.robospice.request.listener.SpiceServiceListener)1 DefaultRetryPolicy (com.octo.android.robospice.retry.DefaultRetryPolicy)1