package com.multysite.model.admin;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import com.google.appengine.api.NamespaceManager;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.multysite.entity.admin.ApplicationMapping;
import com.multysite.util.Setting;
public class ApplicationMappingModel {
private static final Logger log = Logger
.getLogger(ApplicationMappingModel.class.getName());
private static Objectify ofy;
private static Cache cache = null;
private static boolean isRegisted = false;
private static ObjectifyOpts opts = null;
private static String cachePrefix = "siteMappingModel_";
private List<ApplicationMapping> listResult = new ArrayList<ApplicationMapping>();
public List<ApplicationMapping> getListResult() {
return listResult;
}
public void setListResult(List<ApplicationMapping> listResult) {
this.listResult = listResult;
}
public static void init() {
if (!isRegisted) {
isRegisted = true;
try {
ObjectifyService.register(ApplicationMapping.class);
} catch (Exception e) {
isRegisted = false;
}
try {
cache = CacheManager.getInstance().getCacheFactory()
.createCache(Collections.emptyMap());
} catch (CacheException e) {
isRegisted = false;
}
opts = new ObjectifyOpts().setSessionCache(true);
}
ofy = ObjectifyService.begin(opts);
}
public ApplicationMappingModel() {
init();
}
@SuppressWarnings("unchecked")
public static void insert(String ns, ApplicationMapping obj) {
String currentNs = NamespaceManager.get();
if (!currentNs.equals(ns)) {
NamespaceManager.set(ns);
}
init();
if (cache != null) {
String prefix = cachePrefix + "id_" + obj.getDomain();
cache.put(prefix, obj);
}
ofy.put(obj);
NamespaceManager.set(currentNs);
}
public static void delete(String ns, ApplicationMapping obj) {
String currentNs = NamespaceManager.get();
if (!currentNs.equals(ns)) {
NamespaceManager.set(ns);
}
init();
String prefix = cachePrefix + "id_" + obj.getDomain();
if (cache != null && cache.containsKey(prefix)) {
cache.remove(prefix);
}
ofy.delete(obj);
NamespaceManager.set(currentNs);
}
@SuppressWarnings("unchecked")
public static ApplicationMapping getById(String id) {
NamespaceManager.set(Setting.getGeneralNamespace());
try {
init();
boolean cached = false;
ApplicationMapping obj = new ApplicationMapping();
String prefix = cachePrefix + "id_" + id;
try {
obj = (ApplicationMapping) cache.get(prefix);
if (obj != null) {
cached = true;
}
} catch (Exception e) {
cached = false;
}
if (!cached) {
try {
obj = ofy.get(new Key<ApplicationMapping>(
ApplicationMapping.class, id));
cache.put(prefix, obj);
} catch (Exception e) {
e.printStackTrace();
obj = null;
}
}
return obj;
} catch (Exception e) {
log.warning(e.toString());
e.printStackTrace();
return null;
}
}
}