001 package de.deepamehta.core.service; 002 003 import de.deepamehta.core.DeepaMehtaObject; 004 import de.deepamehta.core.JSONEnabled; 005 import de.deepamehta.core.util.DeepaMehtaUtils; 006 007 import org.codehaus.jettison.json.JSONObject; 008 009 import java.util.ArrayList; 010 import java.util.Iterator; 011 import java.util.List; 012 013 014 015 public class ResultList<T extends JSONEnabled> implements Iterable<T>, JSONEnabled { 016 017 // ---------------------------------------------------------------------------------------------- Instance Variables 018 019 private int totalCount; 020 private List<T> items; 021 022 // ---------------------------------------------------------------------------------------------------- Constructors 023 024 public ResultList() { 025 this.totalCount = 0; 026 this.items = new ArrayList<T>(); 027 } 028 029 public ResultList(int totalCount, List<T> items) { 030 this.totalCount = totalCount; 031 this.items = items; 032 } 033 034 // -------------------------------------------------------------------------------------------------- Public Methods 035 036 public int getSize() { 037 return items.size(); 038 } 039 040 public int getTotalCount() { 041 return totalCount; 042 } 043 044 public List<T> getItems() { 045 return items; 046 } 047 048 // --- 049 050 public void add(T item) { 051 totalCount++; 052 items.add(item); 053 } 054 055 public void addAll(ResultList<T> result) { 056 totalCount += result.getTotalCount(); 057 items.addAll(result.getItems()); 058 } 059 060 // --- 061 062 public ResultList<T> loadChildTopics() { 063 for (T item : this) { 064 // Note: we store also models in a result list. So we need a cast here. 065 ((DeepaMehtaObject) item).loadChildTopics(); 066 } 067 return this; 068 } 069 070 // *** Iterable Implementation *** 071 072 @Override 073 public Iterator<T> iterator() { 074 return items.iterator(); 075 } 076 077 // *** JSONEnabled Implementation *** 078 079 @Override 080 public JSONObject toJSON() { 081 try { 082 JSONObject o = new JSONObject(); 083 o.put("total_count", totalCount); 084 o.put("items", DeepaMehtaUtils.objectsToJSON(items)); 085 return o; 086 } catch (Exception e) { 087 throw new RuntimeException("Serialization failed (" + this + ")", e); 088 } 089 } 090 }