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