package com.shin1ogawa.util;

import java.util.Collections;

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

/**
 * キャッシュ用のユーティリティクラス
 * @author shin1ogawa
 */
public class CacheUtil {

	private CacheUtil() {
	}

	@SuppressWarnings("unchecked")
	public static <T>T getCache(String key) {
		T object = null;
		try {
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			Cache cache = cacheFactory.createCache(Collections.emptyMap());
			object = (T) cache.get(key);
		} catch (CacheException e) {
			e.printStackTrace();
		}
		return object;
	}

	@SuppressWarnings("unchecked")
	public static void putCache(String key, Object object) {
		try {
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			Cache cache = cacheFactory.createCache(Collections.emptyMap());
			cache.put(key, object);
		} catch (CacheException e) {
			e.printStackTrace();
		}
	}

	public static void removeCache(String key) {
		try {
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			Cache cache = cacheFactory.createCache(Collections.emptyMap());
			cache.remove(key);
		} catch (CacheException e) {
			e.printStackTrace();
		}
	}

	public static boolean isCached(String key) {
		try {
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			Cache cache = cacheFactory.createCache(Collections.emptyMap());
			return cache.containsKey(key);
		} catch (CacheException e) {
			return false;
		}
	}
}
