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