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 Directives implements Iterable<Directives.Entry>, JSONEnabled {
015    
016        // ---------------------------------------------------------------------------------------------- Instance Variables
017    
018        private List<Entry> directives = new ArrayList();
019    
020        // -------------------------------------------------------------------------------------------------- Public Methods
021    
022        public void add(Directive dir, JSONEnabled arg) {
023            directives.add(new Entry(dir, arg));
024        }
025    
026        // *** JSONEnabled Implementation ***
027    
028        public JSONObject toJSON() {
029            try {
030                JSONObject obj = new JSONObject();
031                obj.put("directives", DeepaMehtaUtils.objectsToJSON(directives));
032                return obj;
033            } catch (Exception e) {
034                throw new RuntimeException("Serialization failed (" + this + ")", e);
035            }
036        }
037    
038        // *** Iterable Implementation ***
039    
040        @Override
041        public Iterator<Entry> iterator() {
042            return directives.iterator();
043        }
044    
045        // --------------------------------------------------------------------------------------------------- Inner Classes
046    
047        public class Entry implements JSONEnabled {
048    
049            public Directive dir;
050            public JSONEnabled arg;
051    
052            private Entry(Directive dir, JSONEnabled arg) {
053                this.dir = dir;
054                this.arg = arg;
055            }
056    
057            @Override
058            public JSONObject toJSON() {
059                try {
060                    JSONObject obj = new JSONObject();
061                    obj.put("type", dir);
062                    obj.put("arg", arg.toJSON());
063                    return obj;
064                } catch (Exception e) {
065                    throw new RuntimeException("Serialization failed (" + this + ")", e);
066                }
067            }
068    
069            @Override
070            public String toString() {
071                return dir + ": " + arg;
072            }
073        }
074    }