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