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
11import eu.siacs.conversations.xml.Element;
12
13public class Presences {
14
15	public static final int CHAT = -1;
16	public static final int ONLINE = 0;
17	public static final int AWAY = 1;
18	public static final int XA = 2;
19	public static final int DND = 3;
20	public static final int OFFLINE = 4;
21	
22	private Hashtable<String, Integer> presences = new Hashtable<String, Integer>();
23
24	public Hashtable<String, Integer> getPresences() {
25		return this.presences;
26	}
27
28	public void updatePresence(String resource, int status) {
29		this.presences.put(resource, status);
30	}
31
32	public void removePresence(String resource) {
33		this.presences.remove(resource);
34	}
35	
36	public int getMostAvailableStatus() {
37		int status = OFFLINE;
38		Iterator<Entry<String, Integer>> it = presences.entrySet().iterator();
39		while (it.hasNext()) {
40			Entry<String, Integer> entry = it.next();
41			if (entry.getValue()<status) status = entry.getValue();
42		}
43		return status;
44	}
45
46	public String toJsonString() {
47		JSONArray json = new JSONArray();
48		Iterator<Entry<String, Integer>> it = presences.entrySet().iterator();
49
50		while (it.hasNext()) {
51			Entry<String, Integer> entry = it.next();
52			JSONObject jObj = new JSONObject();
53			try {
54				jObj.put("resource", entry.getKey());
55				jObj.put("status", entry.getValue());
56			} catch (JSONException e) {
57
58			}
59			json.put(jObj);
60		}
61		return json.toString();
62	}
63
64	public static Presences fromJsonString(String jsonString) {
65		Presences presences = new Presences();
66		try {
67			JSONArray json = new JSONArray(jsonString);
68			for (int i = 0; i < json.length(); ++i) {
69				JSONObject jObj = json.getJSONObject(i);
70				presences.updatePresence(jObj.getString("resource"),
71						jObj.getInt("status"));
72			}
73		} catch (JSONException e1) {
74			
75		}
76		return presences;
77	}
78
79	public static int parseShow(Element show) {
80		if (show == null) {
81			return Presences.ONLINE;
82		} else if (show.getContent().equals("away")) {
83			return Presences.AWAY;
84		} else if (show.getContent().equals("xa")) {
85			return Presences.XA;
86		} else if (show.getContent().equals("chat")) {
87			return Presences.CHAT;
88		} else if (show.getContent().equals("dnd")) {
89			return 	Presences.DND;
90		} else {
91			return Presences.OFFLINE;
92		}
93	}
94	
95	public int size() {
96		return presences.size();
97	}
98}