package ${package}.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ${package}.entity.SampleEntity;
import ${package}.logic.SampleEntityLogic;

import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class IndexServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("user", UserServiceFactory.getUserService()
				.getCurrentUser());
		req.setAttribute("loginUrl", UserServiceFactory.getUserService()
				.createLoginURL(req.getRequestURI()));
		req.setAttribute("logoutUrl", UserServiceFactory.getUserService()
				.createLogoutURL(req.getRequestURI()));
		List<SampleEntity> entities = getEntities();
		req.setAttribute("entities", entities);
		req.getRequestDispatcher("/index.jsp").forward(req, resp);
	}

	SampleEntityLogic logic = new SampleEntityLogic();

	@SuppressWarnings("unchecked")
	private List<SampleEntity> getEntities() {
		String key = SampleEntity.class.getName();
		Cache cache = null;
		try {
			cache = CacheManager.getInstance().getCacheFactory().createCache(
					Collections.emptyMap());
			if (cache.containsKey(key)) {
				return (List<SampleEntity>) cache.get(key);
			}
		} catch (CacheException e) {
			//
		}
		Query query = logic.newQuery();
		query.setOrdering("created desc");
		List<SampleEntity> list = logic.list(query);
		if (cache != null) {
			cache.put(key, list);
		}
		return list;
	}
}
