Attempts to fix state handling accross XHTML pages.
[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    * @param key\r
93    */\r
94   public void setCurrentStateKey(String key) {    \r
95     if (currentKey.equals(key)) {\r
96       logger.debug("setCurrentStateKey: no key change detected");\r
97     } else {\r
98       logger.debug("State key change. Was: [" + currentKey + "]. Will be ["+key+"]");\r
99       if (states.get(key)==null) {\r
100         logger.error("The back-end received an unknow state key, probably UI generated: ["+ key +"].");\r
101         if (key == null || key.length()==0) {\r
102           logger.info("Empty key received, treating it as identical to current key going forward.");\r
103           key = currentKey;\r
104         } else {\r
105           if (states.get(currentKey) != null) {\r
106             logger.info("Current search state cached under both of [" + key + "] and [" + currentKey + "]");\r
107             states.put(key,states.get(currentKey));\r
108           }\r
109         }\r
110       }\r
111       \r
112       if (states.get(key).getCommand("search").equals(states.get(currentKey).getCommand("search"))) {\r
113         logger.debug("No search change detected");\r
114       } else {\r
115         hasPendingStateChange("search",true);\r
116       }\r
117       if (states.get(key).getCommand("record").equals(states.get(currentKey).getCommand("record"))) {\r
118         logger.debug("No record change detected");\r
119       } else {\r
120         hasPendingStateChange("record",true);\r
121       }\r
122       currentKey = key;            \r
123     }\r
124   }\r
125 \r
126   /**\r
127    * Sets a pending-state-change flag for the given command and notifies\r
128    * registered listeners. \r
129    * \r
130    * It is up to the listener to reset the flag as needed.\r
131    * \r
132    * @param command\r
133    * @param bool\r
134    */\r
135   public void hasPendingStateChange(String command, boolean bool) {\r
136     pendingStateChanges.put(command, new Boolean(bool));\r
137   }\r
138   \r
139   /**\r
140    * \r
141    * @param command\r
142    * @return true if there is a non-executed command change in this state\r
143    */\r
144   public boolean hasPendingStateChange (String command) {\r
145     return pendingStateChanges.get(command).booleanValue();\r
146   }\r
147 \r
148 }\r