Android Open Source - cube-sdk Cache Able Request






From Project

Back to project page cube-sdk.

License

The source code is released under:

Apache License

If you think the Android project cube-sdk listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package in.srain.cube.request;
/*w  w w  .j  a  va2 s  .co m*/
import android.text.TextUtils;
import in.srain.cube.cache.CacheManager;
import in.srain.cube.cache.CacheResultType;
import in.srain.cube.concurrent.SimpleTask;
import in.srain.cube.util.CLog;
import in.srain.cube.util.Debug;

import java.net.URI;
import java.net.URISyntaxException;

public class CacheAbleRequest<T> extends RequestBase<T> implements ICacheAbleRequest<T> {

    public static enum ResultType {
        USE_CACHE_NOT_EXPIRED,
        USE_CACHE_ANYWAY,
        USE_CACHE_ON_TIMEOUT,
        USE_DATA_FROM_SERVER,
        USE_CACHE_ON_FAIL,
    }

    protected static final boolean DEBUG = Debug.DEBUG_CACHE;
    protected static final String LOG_TAG = "cube_cache_request";

    private CacheAbleRequestHandler<T> mHandler;

    private T mCacheData;
    private boolean mOutOfDate;
    private String mCacheKey = null;

    private int mTimeout = 0;
    private boolean mHasTimeout = false;
    private boolean mUseCacheAnyway = false;
    private boolean mHasNotified = false;
    protected boolean mForceQueryFromServer = false;

    private String mInitDataPath;
    private boolean mDisableCache = false;
    private long mCacheTime;

    public CacheAbleRequest() {
    }

    public CacheAbleRequest(final CacheAbleRequestHandler<T> handler) {
        setCacheAbleRequestHandler(handler);
    }

    public void setCacheAbleRequestHandler(CacheAbleRequestHandler<T> handler) {
        mHandler = handler;
    }

    public void forceQueryFromServer(boolean force) {
        mForceQueryFromServer = force;
    }

    // ===========================================================
    // Override parent
    // ===========================================================
    @Override
    public void doSendRequest() {
        RequestCacheManager.getInstance().requestCache(this);
    }

    /**
     * prepare request
     */
    @Override
    protected void prepareRequest() {

    }

    // ===========================================================
    // Override Interface
    // ===========================================================
    @Override
    public void setTimeout(int timeOut) {
        mTimeout = timeOut;
    }

    @Override
    public void useCacheAnyway(boolean use) {
        mUseCacheAnyway = use;
    }

    @Override
    public void onRequestSuccess(T data) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, onRequestSuccess", getCacheKey());
        }
        if (hasBeenCanceled()) {
            return;
        }
        mCacheData = data;
        if (null != mHandler) {
            mHandler.onRequestFinish(data);
            if (!mHasTimeout && !mUseCacheAnyway) {
                notifyRequestFinish(ResultType.USE_DATA_FROM_SERVER, false);
            } else {
                if (DEBUG) {
                    CLog.d(LOG_TAG, "%s, will not notifyRequestFinish", getCacheKey());
                }
            }
        }
    }

    @Override
    public void onRequestFail(FailData failData) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, onRequestFail", getCacheKey());
        }
        if (hasBeenCanceled()) {
            return;
        }
        if (null != mHandler) {
            mHandler.onRequestFail(failData);
            if (mCacheData != null && !cacheIsDisabled() && !mUseCacheAnyway) {
                notifyRequestFinish(ResultType.USE_CACHE_ON_FAIL, true);
            } else {
                mHandler.onRequestFail(null);
            }
        }
    }

    @Override
    public void createDataForCache(CacheManager cacheManager) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, createDataForCache", getCacheKey());
        }
        if (hasBeenCanceled()) {
            return;
        }
        doQueryFromServer();
        beginTimeout();
    }

    protected void doQueryFromServer() {
        SimpleRequestManager.sendRequest(this);
    }

    protected boolean cacheRequestResult() {
        return mForceQueryFromServer || !cacheIsDisabled();
    }

    @Override
    public boolean cacheIsDisabled() {
        if (mForceQueryFromServer) {
            return true;
        }
        return mDisableCache;
    }

    // ===========================================================
    // Implements Interface {@link ICacheAble}
    // ===========================================================
    @Override
    public void onCacheData(CacheResultType cacheResultType, T data, boolean outOfDate) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, onQueryFinish, out of date: %s", getCacheKey(), outOfDate);
        }
        if (hasBeenCanceled()) {
            return;
        }
        mCacheData = data;
        mOutOfDate = outOfDate;
        if (null != mHandler) {
            mHandler.onCacheData(data, outOfDate);

            if (mUseCacheAnyway) {
                notifyRequestFinish(ResultType.USE_CACHE_ANYWAY, mOutOfDate);
            } else {
                if (!outOfDate) {
                    notifyRequestFinish(ResultType.USE_CACHE_NOT_EXPIRED, false);
                }
            }
        }
    }

    @Override
    public long getCacheTime() {
        return mCacheTime;
    }

    @Override
    public String getCacheKey() {
        if (mCacheKey == null) {
            String cacheKey = null;
            String url = getRequestData().getRequestUrl();
            try {
                URI uri = null;
                uri = new URI(url);
                cacheKey = uri.getPath();
                if (cacheKey.startsWith("/")) {
                    cacheKey = cacheKey.substring(1);
                }
                cacheKey = cacheKey.replace("/", "-");
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            if (TextUtils.isEmpty(cacheKey)) {
                throw new RuntimeException("Cache key is null");
            }
            mCacheKey = cacheKey;
        }
        return mCacheKey;
    }

    @Override
    public String getAssertInitDataPath() {
        return mInitDataPath;
    }

    @Override
    public T onDataFromServer(String data) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, onDataFromServer", getCacheKey());
        }
        // cache the data
        if (!TextUtils.isEmpty(data) && cacheRequestResult()) {
            RequestCacheManager.getInstance().setCacheData(this.getCacheKey(), data);
        }
        return super.onDataFromServer(data);
    }

    @Override
    public T processOriginDataFromServer(JsonData rawData) {
        return mHandler.processOriginData(rawData);
    }

    @Override
    public T processRawDataFromCache(JsonData rawData) {
        return mHandler.processOriginData(rawData);
    }

    /**
     * will only notify once
     *
     * @param type
     * @param outOfDate
     */
    private void notifyRequestFinish(ResultType type, boolean outOfDate) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, notifyRequestFinish: %s, %s", getCacheKey(), type, outOfDate);
        }
        if (mHasNotified) {
            return;
        }
        mHasNotified = true;
        mHandler.onCacheAbleRequestFinish(mCacheData, type, outOfDate);
    }

    private void timeout() {
        mHasTimeout = true;
        if (mCacheData != null && mHandler != null) {
            notifyRequestFinish(ResultType.USE_CACHE_ON_TIMEOUT, true);
        }
    }

    private void beginTimeout() {
        if (mTimeout > 0 && mCacheData != null) {
            SimpleTask.postDelay(new Runnable() {
                @Override
                public void run() {
                    timeout();
                }
            }, mTimeout);
        }
    }

    public CacheAbleRequest setCacheKey(String cacheKey) {
        mCacheKey = cacheKey;
        return this;
    }

    public CacheAbleRequest setDisableCache(boolean disable) {
        mDisableCache = disable;
        return this;
    }

    public CacheAbleRequest setInitDataPath(String path) {
        mInitDataPath = path;
        return this;
    }

    public CacheAbleRequest setCacheTime(long cacheTime) {
        mCacheTime = cacheTime;
        return this;
    }
}




Java Source Code List

in.srain.cube.Cube.java
in.srain.cube.app.CubeFragmentActivity.java
in.srain.cube.app.CubeFragment.java
in.srain.cube.app.FragmentParam.java
in.srain.cube.app.ICubeFragment.java
in.srain.cube.app.XActivity.java
in.srain.cube.app.lifecycle.IComponentContainer.java
in.srain.cube.app.lifecycle.LifeCycleComponentManager.java
in.srain.cube.app.lifecycle.LifeCycleComponent.java
in.srain.cube.cache.CacheInfo.java
in.srain.cube.cache.CacheManager.java
in.srain.cube.cache.CacheResultType.java
in.srain.cube.cache.ICacheAble.java
in.srain.cube.cache.IFileCache.java
in.srain.cube.cache.QueryHandler.java
in.srain.cube.cache.Query.java
in.srain.cube.concurrent.BlockingDeque.java
in.srain.cube.concurrent.Deque.java
in.srain.cube.concurrent.LinkedBlockingDeque.java
in.srain.cube.concurrent.SimpleExecutor.java
in.srain.cube.concurrent.SimpleTask.java
in.srain.cube.file.DiskLruCache.java
in.srain.cube.file.FileUtil.java
in.srain.cube.file.LruFileCache.java
in.srain.cube.image.CubeImageView.java
in.srain.cube.image.ImageLoaderFactory.java
in.srain.cube.image.ImageLoader.java
in.srain.cube.image.ImagePerformanceStatistics.java
in.srain.cube.image.ImageProvider.java
in.srain.cube.image.ImageReuseInfoManger.java
in.srain.cube.image.ImageReuseInfo.java
in.srain.cube.image.ImageTaskStatistics.java
in.srain.cube.image.ImageTask.java
in.srain.cube.image.drawable.RecyclingBitmapDrawable.java
in.srain.cube.image.drawable.RoundedDrawable.java
in.srain.cube.image.iface.ImageFileProvider.java
in.srain.cube.image.iface.ImageLoadHandler.java
in.srain.cube.image.iface.ImageLoadProgressHandler.java
in.srain.cube.image.iface.ImageMemoryCache.java
in.srain.cube.image.iface.ImageResizer.java
in.srain.cube.image.iface.ImageTaskExecutor.java
in.srain.cube.image.impl.DefaultImageLoadHandler.java
in.srain.cube.image.impl.DefaultImageResizer.java
in.srain.cube.image.impl.DefaultImageTaskExecutor.java
in.srain.cube.image.impl.DefaultMemoryCache.java
in.srain.cube.image.impl.LruImageFileProvider.java
in.srain.cube.image.impl.SimpleDownloader.java
in.srain.cube.mints.base.BlockMenuFragment.java
in.srain.cube.mints.base.DemoBaseActivity.java
in.srain.cube.mints.base.TitleBaseActivity.java
in.srain.cube.mints.base.TitleBaseFragment.java
in.srain.cube.mints.base.TitleHeaderBar.java
in.srain.cube.request.CacheAbleRequestDefaultHandler.java
in.srain.cube.request.CacheAbleRequestHandler.java
in.srain.cube.request.CacheAbleRequestJsonHandler.java
in.srain.cube.request.CacheAbleRequest.java
in.srain.cube.request.FailData.java
in.srain.cube.request.ICacheAbleRequest.java
in.srain.cube.request.IRequest.java
in.srain.cube.request.JsonData.java
in.srain.cube.request.RequestBase.java
in.srain.cube.request.RequestCacheManager.java
in.srain.cube.request.RequestData.java
in.srain.cube.request.RequestDefaultHandler.java
in.srain.cube.request.RequestFinishHandler.java
in.srain.cube.request.RequestHandler.java
in.srain.cube.request.RequestJsonHandler.java
in.srain.cube.request.SimpleJsonRequest.java
in.srain.cube.request.SimpleRequestManager.java
in.srain.cube.request.SimpleRequest.java
in.srain.cube.uri.CustomizedUri.java
in.srain.cube.util.Debug.java
in.srain.cube.util.Encrypt.java
in.srain.cube.util.Env.java
in.srain.cube.util.LocalDisplay.java
in.srain.cube.util.NetworkStatusManager.java
in.srain.cube.util.ResourceMan.java
in.srain.cube.util.SystemWatcher.java
in.srain.cube.util.Version.java
in.srain.cube.views.DotView.java
in.srain.cube.views.IScrollHeaderFrameHandler.java
in.srain.cube.views.MoreActionView.java
in.srain.cube.views.ScrollHeaderFrame.java
in.srain.cube.views.banner.BannerAdapter.java
in.srain.cube.views.banner.PagerIndicator.java
in.srain.cube.views.banner.SliderBanner.java
in.srain.cube.views.block.BlockListAdapter.java
in.srain.cube.views.block.BlockListView.java
in.srain.cube.views.list.ListPageInfo.java
in.srain.cube.views.list.ListViewDataAdapterBase.java
in.srain.cube.views.list.ListViewDataAdapter.java
in.srain.cube.views.list.PagedListDataModel.java
in.srain.cube.views.list.PagedListViewDataAdapter.java
in.srain.cube.views.list.ViewHolderBase.java
in.srain.cube.views.list.ViewHolderCreator.java
in.srain.cube.views.mix.AutoPlayer.java
in.srain.cube.views.pager.PageIndicator.java
in.srain.cube.views.pager.TabPageIndicator.java