package org.aplikator.client.local;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.storage.client.Storage;
/**
*
*/
public abstract class SettingsStorage {
public static final String ACTIVE_SORT = "_activeSort";
public static final String ACTIVE_FILTER = "_activeFilter";
public static final String TABLE_MODE = "_tableMode";
private static final int FOREVER = 2000000000;
private static final String COOKIE_NAME = "AplikatorViewSettings-" + GWT.getModuleName();
;
private static Logger LOG = Logger.getLogger(SettingsStorage.class.getName());
private static Storage storage = Storage.getLocalStorageIfSupported();
private static Map<String, String> map = toMap(storage != null ? storage.getItem(COOKIE_NAME) : null);
public static void storeSetting(String key, String value) {
map.put(key, value);
try {
String cookie = toJson(map);
if (storage != null) {
storage.setItem(COOKIE_NAME, cookie);
}
} catch (Throwable t) {
LOG.warning("Error storing settings:" + t);
}
}
public static String getSetting(String key) {
return map.get(key);
}
private static String toJson(Map<String, String> map) {
String json = "";
if (map != null && !map.isEmpty()) {
JSONObject jsonObj = new JSONObject();
for (Map.Entry<String, String> entry : map.entrySet()) {
jsonObj.put(entry.getKey(), new JSONString(entry.getValue()));
}
json = jsonObj.toString();
}
return json;
}
private static Map<String, String> toMap(String jsonStr) {
Map<String, String> map = new HashMap<String, String>();
try {
JSONValue parsed = JSONParser.parseStrict(jsonStr);
JSONObject jsonObj = parsed.isObject();
if (jsonObj != null) {
for (String key : jsonObj.keySet()) {
map.put(key, jsonObj.get(key).isString().stringValue());
}
}
} catch (Throwable t) {
LOG.warning("Error loading settings:" + t);
}
return map;
}
}