package ${package}.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;
import javax.servlet.http.*;

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

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

@SuppressWarnings("serial")
public class PostServlet extends HttpServlet {
	static final Logger logger = Logger.getLogger(PostServlet.class.getName());

	SampleEntityLogic logic = new SampleEntityLogic();

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		User user = UserServiceFactory.getUserService().getCurrentUser();
		String content = req.getParameter("content");
		if (content != null && content.length() > 0) {
			SampleEntity entity = SampleEntityLogic.create(user, content);
			entity = logic.save(entity);
			logger.log(Level.FINER, "new SampleEntity:" + entity);
			removeCache(entity);
		}
		resp.sendRedirect("/");
	}

	private void removeCache() {
		try {
			CacheFactory cacheFactory = CacheManager.getInstance()
					.getCacheFactory();
			Cache cache = cacheFactory.createCache(Collections.emptyMap());
			String key = SampleEntity.class.getName();
			if (cache.containsKey(key)) {
				cache.remove(key);
			}
		} catch (CacheException e) {
			//
		}
	}
}
