001 package de.kiezatlas;
002
003 import de.deepamehta.core.JSONEnabled;
004 import de.deepamehta.core.Topic;
005 import de.deepamehta.core.RelatedTopic;
006 import de.deepamehta.core.util.DeepaMehtaUtils;
007
008 import org.codehaus.jettison.json.JSONArray;
009 import org.codehaus.jettison.json.JSONObject;
010
011 import java.util.List;
012
013
014
015 /**
016 * A collection of Geo Objects as returned by the Kiezatlas service (a data transfer object).
017 * The Geo Objects are grouped by category, then grouped by criteria.
018 */
019 public class GroupedGeoObjects implements JSONEnabled {
020
021 // ---------------------------------------------------------------------------------------------- Instance Variables
022
023 private JSONObject json = new JSONObject();
024 private JSONArray criteriaResult = new JSONArray();
025 private JSONArray categoriesResult;
026 private long currentCriteriaId;
027
028 // ---------------------------------------------------------------------------------------------------- Constructors
029
030 GroupedGeoObjects(long clock) {
031 try {
032 json.put("items", criteriaResult);
033 json.put("clock", clock);
034 } catch (Exception e) {
035 throw new RuntimeException("Constructing a GroupedGeoObjects failed", e);
036 }
037 }
038
039 // -------------------------------------------------------------------------------------------------- Public Methods
040
041 void add(Topic criteria, Topic category, List<RelatedTopic> geoObjects) {
042 try {
043 // start new criteria
044 if (criteria.getId() != currentCriteriaId) {
045 categoriesResult = new JSONArray();
046 criteriaResult.put(new JSONObject()
047 .put("criteria", criteria.toJSON())
048 .put("categories", categoriesResult)
049 );
050 currentCriteriaId = criteria.getId();
051 }
052 //
053 categoriesResult.put(new JSONObject()
054 .put("category", category.toJSON())
055 .put("geo_objects", DeepaMehtaUtils.objectsToJSON(geoObjects))
056 );
057 } catch (Exception e) {
058 throw new RuntimeException("Adding items to a GroupedGeoObjects failed", e);
059 }
060 }
061
062 @Override
063 public JSONObject toJSON() {
064 return json;
065 }
066 }