001package de.deepamehta.core.service;
002
003import de.deepamehta.core.JSONEnabled;
004import de.deepamehta.core.util.DeepaMehtaUtils;
005
006import org.codehaus.jettison.json.JSONArray;
007import org.codehaus.jettison.json.JSONObject;
008
009import java.util.ArrayList;
010import java.util.Iterator;
011import java.util.List;
012import java.util.logging.Logger;
013
014
015
016public class Directives implements Iterable<Directives.Entry> {
017
018    // ---------------------------------------------------------------------------------------------- Instance Variables
019
020    private List<Entry> directives = new ArrayList();
021
022    // ------------------------------------------------------------------------------------------------- Class Variables
023
024    private static Logger logger = Logger.getLogger("de.deepamehta.core.service.Directives");
025
026    private static final ThreadLocal<Directives> threadLocalDirectives = new ThreadLocal() {
027        @Override
028        protected Directives initialValue() {
029            logger.fine("### Creating tread-local directives");
030            return new Directives();
031        }
032    };
033
034    // -------------------------------------------------------------------------------------------------- Public Methods
035
036    public void add(Directive dir, JSONEnabled arg) {
037        directives.add(new Entry(dir, arg));
038    }
039
040    public JSONArray toJSONArray() {
041        return DeepaMehtaUtils.toJSONArray(directives);
042    }
043
044    // ---
045
046    public static Directives get() {
047        return threadLocalDirectives.get();
048    }
049
050    public static void remove() {
051        logger.fine("### Removing tread-local directives");
052        threadLocalDirectives.remove();
053    }
054
055    // *** Iterable Implementation ***
056
057    @Override
058    public Iterator<Entry> iterator() {
059        return directives.iterator();
060    }
061
062    // -------------------------------------------------------------------------------------------------- Nested Classes
063
064    public class Entry implements JSONEnabled {
065
066        public Directive dir;
067        public JSONEnabled arg;
068
069        private Entry(Directive dir, JSONEnabled arg) {
070            this.dir = dir;
071            this.arg = arg;
072        }
073
074        @Override
075        public JSONObject toJSON() {
076            try {
077                JSONObject obj = new JSONObject();
078                obj.put("type", dir);
079                obj.put("arg", arg.toJSON());
080                return obj;
081            } catch (Exception e) {
082                throw new RuntimeException("Serialization failed (" + this + ")", e);
083            }
084        }
085
086        @Override
087        public String toString() {
088            return dir + ": " + arg;
089        }
090    }
091}