summaryrefslogtreecommitdiff
path: root/java/src/org/singinst/uf/presenter/Store.java
blob: 3cb3f41ef59af1bb56a988d2dccb9806bb2ae498 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package org.singinst.uf.presenter;

import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import org.singinst.uf.model.ScalarValueHolder;

public abstract class Store {
	private static Store instance = null;
	
	public abstract Double get(String key);
	public abstract void put(String key, double value);
	
	/**
	 * Load data (expert claim). This is called from the browser.
	 * @param jsonSubset
	 */
	public void loadData(String jsonSubset) {
		try {
			attemptLoad(jsonSubset);
		} catch (Exception e) {
			Status.singleton.setValue("<html>" + HtmlUtil.red("Load failed!"));
			e.printStackTrace();
		}
	}
	
	/**
	 * example: {"caption": "loaded foo", "Q2-3.value": "1.35"}
	 */
	private void attemptLoad(String jsonSubset) {
		Map<String, String> map = new TreeMap<String, String>();
		
		String[] properties = jsonSubset.replaceFirst("\\{(.+)\\}", "$1").split("\\,");
		for (String property : properties) {
			String[] keyValue = property.split("\\:");
			String key = scrub(keyValue[0]);
			String value = scrub(keyValue[1]);
			map.put(key, value);
		}
		String caption = map.remove("caption");
		if (caption == null) {
			caption = "loaded: " + map.toString();
		}
		for (Entry<String, String> e: map.entrySet()) {
			
			ScalarValueHolder.findById(e.getKey()).setValue(Double.valueOf(e.getValue()));
		}
		Status.singleton.setValue(caption);
	}
	
	private String scrub(String string) {
		return string.trim().replaceFirst("\\\"(.+)\\\"", "$1").replaceFirst("\\'(.+)\\'", "$1");
	}
	
	public static void setInstance(Store instance) {
		Store.instance = instance;
	}
	public static Store getInstance() {
		return instance;
	}
}