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 void clearPresences() {
 37		this.presences.clear();
 38	}
 39	
 40	public int getMostAvailableStatus() {
 41		int status = OFFLINE;
 42		Iterator<Entry<String, Integer>> it = presences.entrySet().iterator();
 43		while (it.hasNext()) {
 44			Entry<String, Integer> entry = it.next();
 45			if (entry.getValue()<status) status = entry.getValue();
 46		}
 47		return status;
 48	}
 49
 50	public String toJsonString() {
 51		JSONArray json = new JSONArray();
 52		Iterator<Entry<String, Integer>> it = presences.entrySet().iterator();
 53
 54		while (it.hasNext()) {
 55			Entry<String, Integer> entry = it.next();
 56			JSONObject jObj = new JSONObject();
 57			try {
 58				jObj.put("resource", entry.getKey());
 59				jObj.put("status", entry.getValue());
 60			} catch (JSONException e) {
 61				
 62			}
 63			json.put(jObj);
 64		}
 65		return json.toString();
 66	}
 67
 68	public static Presences fromJsonString(String jsonString) {
 69		Presences presences = new Presences();
 70		try {
 71			JSONArray json = new JSONArray(jsonString);
 72			for (int i = 0; i < json.length(); ++i) {
 73				JSONObject jObj = json.getJSONObject(i);
 74				presences.updatePresence(jObj.getString("resource"),
 75						jObj.getInt("status"));
 76			}
 77		} catch (JSONException e1) {
 78
 79		}
 80		return presences;
 81	}
 82
 83	public static int parseShow(Element show) {
 84		if (show == null) {
 85			return Presences.ONLINE;
 86		} else if (show.getContent().equals("away")) {
 87			return Presences.AWAY;
 88		} else if (show.getContent().equals("xa")) {
 89			return Presences.XA;
 90		} else if (show.getContent().equals("chat")) {
 91			return Presences.CHAT;
 92		} else if (show.getContent().equals("dnd")) {
 93			return 	Presences.DND;
 94		} else {
 95			return Presences.OFFLINE;
 96		}
 97	}
 98	
 99	public int size() {
100		return presences.size();
101	}
102}