Package com.tubeonfire.util

Source Code of com.tubeonfire.util.RecentViewHelper

package com.tubeonfire.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.tubeonfire.entity.Tube;
import com.tubeonfire.search.TubeSearchModel;

public class RecentViewHelper {

  private static String cachePrefix = "recentViewCache_";
  private static boolean isRegisted = false;
  private static Cache cache = null;

  public static void initCache() {
    if (!isRegisted) {
      isRegisted = true;
      try {
        cache = CacheManager.getInstance().getCacheFactory()
            .createCache(Collections.emptyMap());
      } catch (CacheException e) {
        isRegisted = false;
      }
    }
  }

  @SuppressWarnings("unchecked")
  public static List<Tube> getRecentView() {
    initCache();
    String prefix = cachePrefix;
    boolean cached = false;
    List<Tube> result = new ArrayList<Tube>();
    if (cache != null) {
      try {
        result = (ArrayList<Tube>) cache.get(prefix);
        if (result.size() > 0) {
          cached = true;
        }
      } catch (Exception e) {
        cached = false;
      }
      if (cached) {
        if (result.size() >= 11) {
          TubeSearchModel model = new TubeSearchModel();
          model.setLimit(10);
          model.setPage(1);
          model.prepareRecentView();
          if (model.getListResult().size() > 0) {
            result = model.getListResult();
          }
          cache.put(prefix, result);
        }
      }
    }
    if (!cached) {
      TubeSearchModel model = new TubeSearchModel();
      model.setLimit(10);
      model.setPage(1);
      model.prepareRecentView();
      if (model.getListResult().size() > 0) {
        result = model.getListResult();
      }
      cache.put(prefix, result);
    }
    return result;
  }

  @SuppressWarnings("unchecked")
  public static void addRecentView(Tube tub) {
    List<Tube> recentView = getRecentView();
    for (int i = 0; i < recentView.size(); i++) {
      if (recentView.get(i).getId().equals(tub.getId())) {
        recentView.remove(i);
      }
    }
    if (recentView.size() >= 10) {
      recentView.remove(0);
    }
    recentView.add(tub);
    initCache();
    cache.put(cachePrefix, recentView);
  }
}
TOP

Related Classes of com.tubeonfire.util.RecentViewHelper

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.