Presences.java

 1package eu.siacs.conversations.entities;
 2
 3import java.util.Hashtable;
 4import java.util.Iterator;
 5import java.util.Map.Entry;
 6
 7import org.json.JSONArray;
 8import org.json.JSONException;
 9import org.json.JSONObject;
10
11public class Presences {
12
13	public static final int CHAT = -1;
14	public static final int ONLINE = 0;
15	public static final int AWAY = 1;
16	public static final int XA = 2;
17	public static final int DND = 3;
18	public static final int OFFLINE = 4;
19	
20	private Hashtable<String, Integer> presences = new Hashtable<String, Integer>();
21
22	public Hashtable<String, Integer> getPresences() {
23		return this.presences;
24	}
25
26	public void updatePresence(String resource, int status) {
27		this.presences.put(resource, status);
28	}
29
30	public void removePresence(String resource) {
31		this.presences.remove(resource);
32	}
33	
34	public int getMostAvailableStatus() {
35		int status = OFFLINE;
36		Iterator<Entry<String, Integer>> it = presences.entrySet().iterator();
37		while (it.hasNext()) {
38			Entry<String, Integer> entry = it.next();
39			if (entry.getValue()<status) status = entry.getValue();
40		}
41		return status;
42	}
43
44	public String toJsonString() {
45		JSONArray json = new JSONArray();
46		Iterator<Entry<String, Integer>> it = presences.entrySet().iterator();
47
48		while (it.hasNext()) {
49			Entry<String, Integer> entry = it.next();
50			JSONObject jObj = new JSONObject();
51			try {
52				jObj.put("resource", entry.getKey());
53				jObj.put("status", entry.getValue());
54			} catch (JSONException e) {
55
56			}
57			json.put(jObj);
58		}
59		return json.toString();
60	}
61
62	public static Presences fromJsonString(String jsonString) {
63		Presences presences = new Presences();
64		try {
65			JSONArray json = new JSONArray(jsonString);
66			for (int i = 0; i < json.length(); ++i) {
67				JSONObject jObj = json.getJSONObject(i);
68				presences.updatePresence(jObj.getString("resource"),
69						jObj.getInt("status"));
70			}
71		} catch (JSONException e1) {
72			
73		}
74		return presences;
75	}
76}