Renames Pz2Bean to Pz2Service
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / mkjsf / pazpar2 / state / StateManager.java
1 package com.indexdata.mkjsf.pazpar2.state;\r
2 \r
3 import java.io.Serializable;\r
4 import java.util.ArrayList;\r
5 import java.util.Arrays;\r
6 import java.util.HashMap;\r
7 import java.util.List;\r
8 import java.util.Map;\r
9 \r
10 import org.apache.log4j.Logger;\r
11 \r
12 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;\r
13 import com.indexdata.mkjsf.utils.Utils;\r
14 \r
15 public class StateManager implements Serializable {\r
16   \r
17   private static final long serialVersionUID = 8152558351351730035L;\r
18 \r
19   Map<String, Pazpar2State> states = new HashMap<String, Pazpar2State>();\r
20   String currentKey = "";\r
21   private static List<String> allCommands = new ArrayList<String>(Arrays.asList("init","ping","settings","search","stat","show","record","termlist","bytarget",\r
22                                                                 /* SP extras */ "auth","categories"));\r
23   Map<String,Boolean> pendingStateChanges = new HashMap<String,Boolean>();\r
24   private static Logger logger = Logger.getLogger(StateManager.class);\r
25   private List<StateListener> listeners = new ArrayList<StateListener>();  \r
26   \r
27   public StateManager () {\r
28     logger.info("Initializing a Pazpar2 state manager [" + Utils.objectId(this) + "]");\r
29     Pazpar2State initialState = new Pazpar2State();\r
30     states.put(initialState.getKey(), initialState);\r
31     currentKey = initialState.getKey();\r
32     for (String command : allCommands) {\r
33       pendingStateChanges.put(command, new Boolean(false));\r
34     }    \r
35   }\r
36   \r
37   public void addStateListener(StateListener listener) {\r
38     listeners.add(listener);\r
39   }\r
40   \r
41   public void removeStateListener (StateListener listener) {\r
42     listeners.remove(listener);\r
43   }\r
44   \r
45   private void updateListeners (String command) {\r
46     for (StateListener lsnr : listeners) {\r
47       lsnr.stateUpdated(command);\r
48     }\r
49   }\r
50   \r
51   /**\r
52    * Registers a Pazpar2 command for execution.\r
53    * \r
54    * The state manager will update current state and flag that\r
55    * a request change was made but that it was not yet carried \r
56    * out against Pazpar2.\r
57    * \r
58    * Any command that is created or modified must be checked in\r
59    * like this to come into effect.\r
60    * \r
61    * @param command\r
62    */\r
63   public void checkIn(Pazpar2Command command) {\r
64     if (getCurrentState().stateMutating(command)) {\r
65       logger.info("State changed by: " + command.getCommandName());\r
66       Pazpar2State state = new Pazpar2State(getCurrentState(),command);\r
67       states.put(state.getKey(), state);\r
68       currentKey = state.getKey();\r
69       hasPendingStateChange(command.getCommandName(),new Boolean(true));      \r
70       logger.info("Updating " + listeners.size() + " listener(s) with state change from " + command);\r
71       updateListeners(command.getCommandName());      \r
72     } else {\r
73       logger.debug("Command " + command.getCommandName() + " not found to change the state [" + command.getEncodedQueryString() + "]");\r
74     }\r
75   }\r
76       \r
77   public Pazpar2Command getCommand (String commandName) {\r
78     return getCurrentState().getCommand(commandName);\r
79   }\r
80   \r
81   public Pazpar2State getCurrentState () {\r
82     return states.get(currentKey);\r
83   }\r
84     \r
85   /**\r
86    * Changes the current state key. Invoked from the UI to have the state \r
87    * manager switch to another state than the current one. \r
88    * \r
89    * @See  The state field in pz2watch.xhtml<br/> \r
90    *       The state listeners windowlocationhashListener() and StateListener()\r
91    *       in listeners.js<br/>\r
92    *       The method {@link com.indexdata.mkjsf.pazpar2.Pz2Service#handleQueryStateChanges}<br/>\r
93    *       The class {@link com.indexdata.mkjsf.pazpar2.state.Pazpar2State}<br/> \r
94    * ... for a complete picture of browser history handling.\r
95    * \r
96    * @param key\r
97    */\r
98   public void setCurrentStateKey(String key) {    \r
99     if (currentKey.equals(key)) {\r
100       logger.info("Ignoring request from UI to set state key, already has that key [" + key + "]");\r
101     } else {\r
102       logger.info("Request from UI to change state key from: [" + currentKey + "] to ["+key+"]");\r
103       if (states.get(key)==null) {\r
104         logger.error("Have no state registered for the key ["+ key +"].");\r
105         if (key == null || key.length()==0) {\r
106           logger.debug("Recived an empty key, retaining currentKey [" + currentKey + "]");\r
107           key = currentKey;\r
108         } else {\r
109           if (states.get(currentKey) != null) {\r
110             if (key.equals("#1")) {\r
111               logger.debug("Initial key created [" + key + "], but already got a state registered for the current key [" + currentKey + "]. Retaining current key.");\r
112               key = currentKey;\r
113             } else {\r
114               logger.info("Current search state cached under both new key [" + key + "] and current key [" + currentKey + "]");\r
115               states.put(key,states.get(currentKey));\r
116             }\r
117           }\r
118         }\r
119       }\r
120       \r
121       if (states.get(key).getCommand("search").equals(states.get(currentKey).getCommand("search"))) {\r
122         logger.debug("No search change detected as a consequence of processing the key ["+key+"]");\r
123       } else {\r
124         hasPendingStateChange("search",true);\r
125       }\r
126       if (states.get(key).getCommand("record").equals(states.get(currentKey).getCommand("record"))) {\r
127         logger.debug("No record change detected as a consequence of processing the key ["+key+"]");\r
128       } else {\r
129         hasPendingStateChange("record",true);\r
130       }\r
131       currentKey = key;            \r
132     }\r
133   }\r
134 \r
135   /**\r
136    * Sets a pending-state-change flag for the given command and notifies\r
137    * registered listeners. \r
138    * \r
139    * It is up to the listener to reset the flag as needed.\r
140    * \r
141    * @param command\r
142    * @param bool\r
143    */\r
144   public void hasPendingStateChange(String command, boolean bool) {\r
145     pendingStateChanges.put(command, new Boolean(bool));\r
146   }\r
147   \r
148   /**\r
149    * \r
150    * @param command\r
151    * @return true if there is a non-executed command change in this state\r
152    */\r
153   public boolean hasPendingStateChange (String command) {\r
154     return pendingStateChanges.get(command).booleanValue();\r
155   }\r
156 \r
157 }\r