Android Open Source - mobile2-android File Cache Manager






From Project

Back to project page mobile2-android.

License

The source code is released under:

Apache License

If you think the Android project mobile2-android 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 com.ecollege.android.util;
// w ww .  j  a  v  a 2 s. c o m
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.FileUtils;

import android.content.Context;

import com.ecollege.api.ECollegeHttpResponseCache;
import com.ecollege.api.ECollegeHttpResponseHandler;

public class FileCacheManager implements ECollegeHttpResponseCache {
  
  private final File cacheDir;
  private final long expirationInMillis;  // in ms
  
  /**
   * FileCacheManager implements a cache system with the application cache directory on android.
   * 
   * @param context
   * @param expiration  A single expiration length (in ms) used for each cache file
   */
  public FileCacheManager(Context context, long expirationInMillis) {
    cacheDir = context.getCacheDir();
    this.expirationInMillis = expirationInMillis;
  }

  public CacheEntry getIfNewerThan(String cacheScope, String cacheKey, long maxMillisOld) {
    return getIfNewerThan(cacheScope, cacheKey, maxMillisOld, false);
  }
  
  public CacheEntry get(String cacheScope, String cacheKey) {
    return getIfNewerThan(cacheScope, cacheKey, expirationInMillis, true);
  }
  
  protected CacheEntry getIfNewerThan(String cacheScope, String cacheKey, long maxMillisOld, boolean deleteIfOlderThanMax) {
    File cacheFile = null;
    long lastModified = Calendar.getInstance().getTimeInMillis();
    synchronized (cacheDir) {
      File cacheScopeDirectory = findOrCreateDirectoryForScope(cacheScope);
      cacheFile = new File(cacheScopeDirectory, cacheKey);
      
      synchronized (cacheScopeDirectory) {
        if (cacheFile.exists()) {
          lastModified = cacheFile.lastModified();
          long now = Calendar.getInstance().getTimeInMillis();
          
          if (now - lastModified > maxMillisOld) {
            if (deleteIfOlderThanMax) {
              invalidateCacheEntry(cacheFile);
              deleteCacheSubdirectoryIfEmpty(cacheScopeDirectory);
            }
            cacheFile = null;
          }
        }
      }
    }
    
    if (cacheFile != null && cacheFile.exists()){
      GZIPInputStream fin = null;
      try {
        fin = new GZIPInputStream(new FileInputStream(cacheFile));
        String cacheData = ECollegeHttpResponseHandler.streamToString(fin, null);
        return new CacheEntry(cacheData, lastModified);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (fin != null) {
          try {
            fin.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
    
    return null;
  }

  public void put(String cacheScope, String cacheKey, String responseContent) {
    synchronized (cacheDir) {
      File cacheScopeDirectory = findOrCreateDirectoryForScope(cacheScope);
      synchronized (cacheScopeDirectory) {
        File cacheFile = new File(cacheScopeDirectory, cacheKey);
        GZIPOutputStream out = null;
        try {
          out = new GZIPOutputStream(new FileOutputStream(cacheFile));
          out.write(responseContent.getBytes());
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          try {
            if (out != null) {
              out.finish();
              out.close();
            }
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  public void invalidateCacheScope(String cacheScope) {
    synchronized (cacheDir) {
      File cacheScopeDirectory = new File(cacheDir, cacheScope);
      synchronized (cacheScopeDirectory) {
        if (cacheScopeDirectory.exists()) {
          FileUtils.deleteQuietly(cacheScopeDirectory);
          cacheScopeDirectory = null;
        }
      }
    }
  }
  
  public void invalidateCacheKey(String cacheScope, String cacheKey) {
    synchronized (cacheDir) {
      File cacheScopeDirectory = new File(cacheDir, cacheScope);
      synchronized (cacheScopeDirectory) {
        if (cacheScopeDirectory.exists()) {
          File cacheFile = new File(cacheScopeDirectory, cacheKey);
          invalidateCacheEntry(cacheFile);
        }
      }
    }
  }
  
  public Integer removeInvalidEntries() {
    File entryFile;
    long lastModified;
    long now = Calendar.getInstance().getTimeInMillis();
    int counter = 0;
    synchronized (cacheDir) {
      Iterator<File> cacheFileList = Arrays.asList(cacheDir.listFiles()).iterator();
      while (cacheFileList.hasNext()) {
        entryFile = cacheFileList.next();
        lastModified = entryFile.lastModified();
        
        if (now - lastModified > expirationInMillis) {
          invalidateCacheEntry(entryFile);
          counter++;
        }
      }
      return counter;
    }
  }

  protected void invalidateCacheEntry(File file) {
    synchronized (cacheDir) {
      File parentDirectory = file.getParentFile();
      file.delete();
      file = null;
      // if the cache entry's parent directory is not the cacheDirectory itself (which was the case in an old implementation)
      if (!cacheDir.getAbsolutePath().equals(parentDirectory.getAbsolutePath())) {
        // delete the parent if empty
        deleteCacheSubdirectoryIfEmpty(parentDirectory);
      }
    }
  }

  protected File findOrCreateDirectoryForScope(String cacheScope) {
    synchronized (cacheDir) {
      File cacheScopeDir = new File(cacheDir, cacheScope);
      if (!cacheScopeDir.exists()) {
        try {
          cacheScopeDir.mkdir();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      return cacheScopeDir;
    }
  }

  protected void deleteCacheSubdirectoryIfEmpty(File directory) {
    synchronized (cacheDir) {
      synchronized (directory) {
        if (directory.isDirectory()) {
          String[] paths = directory.list();
          if (paths.length == 0) {
            FileUtils.deleteQuietly(directory);
            directory = null;
          }
        }
      }
    }
  }

  
}




Java Source Code List

com.ecollege.android.AnnouncementActivity.java
com.ecollege.android.CourseActivity.java
com.ecollege.android.CourseAnnouncementsActivity.java
com.ecollege.android.CourseDiscussionsActivity.java
com.ecollege.android.CourseGradebookActivity.java
com.ecollege.android.CoursePeopleActivity.java
com.ecollege.android.CourseThreadActivity.java
com.ecollege.android.CoursesActivity.java
com.ecollege.android.DiscussionsActivity.java
com.ecollege.android.DropboxMessageActivity.java
com.ecollege.android.ECollegeApplication.java
com.ecollege.android.GradeActivity.java
com.ecollege.android.HomeActivity.java
com.ecollege.android.HtmlContentActivity.java
com.ecollege.android.LoginActivity.java
com.ecollege.android.MainActivity.java
com.ecollege.android.PersonActivity.java
com.ecollege.android.ProfileActivity.java
com.ecollege.android.SingleSignonActivity.java
com.ecollege.android.SplashActivity.java
com.ecollege.android.UserDiscussionActivity.java
com.ecollege.android.UserResponseActivity.java
com.ecollege.android.UserTopicActivity.java
com.ecollege.android.activities.ECollegeActivityHelper.java
com.ecollege.android.activities.ECollegeActivity.java
com.ecollege.android.activities.ECollegeDefaultActivity.java
com.ecollege.android.activities.ECollegeListActivity.java
com.ecollege.android.activities.ECollegeTabActivity.java
com.ecollege.android.adapter.ActivityFeedAdapter.java
com.ecollege.android.adapter.GroupedAdapter.java
com.ecollege.android.adapter.LoadMoreAdapter.java
com.ecollege.android.adapter.ParentAdapterObserver.java
com.ecollege.android.adapter.ResponseAdapter.java
com.ecollege.android.adapter.TopicsAdapter.java
com.ecollege.android.adapter.UberAdapter.java
com.ecollege.android.adapter.UberItem.java
com.ecollege.android.adapter.UpcomingEventsAdapter.java
com.ecollege.android.adapter.WaitingForApiAdapter.java
com.ecollege.android.errors.ECollegeAlertException.java
com.ecollege.android.errors.ECollegeException.java
com.ecollege.android.errors.ECollegePromptException.java
com.ecollege.android.errors.ECollegePromptRetryException.java
com.ecollege.android.tasks.ECollegeAsyncTask.java
com.ecollege.android.tasks.ServiceCallTask.java
com.ecollege.android.tasks.TaskPostProcessor.java
com.ecollege.android.util.CacheConfiguration.java
com.ecollege.android.util.DateTimeUtil.java
com.ecollege.android.util.FileCacheManager.java
com.ecollege.android.util.VolatileCacheManager.java
com.ecollege.android.view.HeaderView.java
com.ecollege.android.view.helpers.ResponseCountViewHelper.java