Moves filter settings from pz2 bean to search command
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / pz2utils4jsf / pazpar2 / Pz2Session.java
1 package com.indexdata.pz2utils4jsf.pazpar2;\r
2 \r
3 import java.util.ArrayList;\r
4 import java.util.List;\r
5 import java.util.Map;\r
6 import java.util.StringTokenizer;\r
7 import java.util.concurrent.ConcurrentHashMap;\r
8 \r
9 import javax.annotation.PostConstruct;\r
10 import javax.inject.Inject;\r
11 \r
12 import org.apache.log4j.Logger;\r
13 \r
14 import com.indexdata.pz2utils4jsf.config.ConfigurationReader;\r
15 import com.indexdata.pz2utils4jsf.controls.ResultsPager;\r
16 import com.indexdata.pz2utils4jsf.errors.ConfigurationError;\r
17 import com.indexdata.pz2utils4jsf.errors.ConfigurationException;\r
18 import com.indexdata.pz2utils4jsf.errors.ErrorHelper;\r
19 import com.indexdata.pz2utils4jsf.errors.ErrorInterface;\r
20 import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandParameter;\r
21 import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandReadOnly;\r
22 import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Command;\r
23 import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Commands;\r
24 import com.indexdata.pz2utils4jsf.pazpar2.data.ByTarget;\r
25 import com.indexdata.pz2utils4jsf.pazpar2.data.CommandError;\r
26 import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData;\r
27 import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseParser;\r
28 import com.indexdata.pz2utils4jsf.pazpar2.data.RecordResponse;\r
29 import com.indexdata.pz2utils4jsf.pazpar2.data.SearchResponse;\r
30 import com.indexdata.pz2utils4jsf.pazpar2.data.ShowResponse;\r
31 import com.indexdata.pz2utils4jsf.pazpar2.data.StatResponse;\r
32 import com.indexdata.pz2utils4jsf.pazpar2.data.TermListsResponse;\r
33 import com.indexdata.pz2utils4jsf.pazpar2.data.TermResponse;\r
34 import com.indexdata.pz2utils4jsf.pazpar2.state.StateListener;\r
35 import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager;\r
36 import com.indexdata.pz2utils4jsf.utils.Utils;\r
37 \r
38 @ForStraightPz2\r
39 public class Pz2Session implements Pz2Interface, StateListener {\r
40     \r
41   private static final long serialVersionUID = 3947514708343320514L;\r
42   private static Logger logger = Logger.getLogger(Pz2Session.class);\r
43   \r
44   protected Map<String,Pazpar2ResponseData> dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();\r
45   \r
46   @Inject StateManager stateMgr;\r
47   @Inject Pazpar2Commands req;\r
48   \r
49   protected ErrorHelper errorHelper = null;\r
50   \r
51   protected List<ErrorInterface> configurationErrors = null;\r
52   protected SearchClient searchClient = null;   \r
53   protected SingleTargetFilter singleTargetFilter = null;  \r
54   protected ResultsPager pager = null; \r
55     \r
56   public Pz2Session () {\r
57     logger.info("Instantiating pz2 session object [" + Utils.objectId(this) + "]");        \r
58   }\r
59   \r
60   @PostConstruct\r
61   public void listenToStateManager() {\r
62     logger.debug("in post-construct of Pz2Session stateMgr is " + stateMgr);\r
63     logger.debug("in post-construct req is " + req);\r
64     stateMgr.addStateListener(this);\r
65   }\r
66     \r
67   public void configureClient(SearchClient searchClient, ConfigurationReader configReader) {\r
68     configurationErrors = new ArrayList<ErrorInterface>();\r
69     errorHelper = new ErrorHelper(configReader);    \r
70     logger.debug(Utils.objectId(this) + " will configure search client for the session");\r
71     try {\r
72       searchClient.configure(configReader);            \r
73       // At the time of writing this search client is injected using Weld. \r
74       // However, the client is used for asynchronously sending off requests\r
75       // to the server AND propagation of context to threads is currently \r
76       // not supported. Trying to do so throws a WELD-001303 error. \r
77       // To avoid that, a context free client is cloned from the context \r
78       // dependent one. \r
79       // If propagation to threads gets supported, the cloning can go. \r
80       this.searchClient = searchClient.cloneMe();         \r
81     } catch (ConfigurationException e) {\r
82       configurationErrors.add(new ConfigurationError("Search Client","Configuration",e.getMessage(),new ErrorHelper(configReader)));          \r
83     } \r
84     logger.info(configReader.document());\r
85     resetDataObjects();\r
86   }\r
87       \r
88   public void doSearch(String query) {\r
89     setCommandParameter("search",new CommandParameter("query","=",query));     \r
90     doSearch();\r
91   }\r
92 \r
93   public void doSearch() { \r
94     stateMgr.hasPendingStateChange("search",false);\r
95     resetDataObjects();\r
96     removeCommand("record");\r
97     setCommandParameter("show",new CommandParameter("start","=",0));    \r
98     logger.debug(Utils.objectId(this) + " is searching using "+req.getCommandReadOnly("search").getUrlEncodedParameterValue("query"));\r
99     doCommand("search");    \r
100   }\r
101       \r
102   /**\r
103    * Refreshes 'show', 'stat', 'termlist', and 'bytarget' data object from pazpar2\r
104    * \r
105    * @return Number of activeclients at the time of the 'show' command.\r
106    */\r
107   public String update () {\r
108     logger.debug("Updating show,stat,termlist,bytarget from pazpar2");\r
109     return update("show,stat,termlist,bytarget");\r
110   }\r
111    \r
112   /**\r
113    * Refreshes the data objects listed in 'commands' from pazpar2\r
114    * \r
115    * @param commands\r
116    * @return Number of activeclients at the time of the 'show' command\r
117    */\r
118   public String update (String commands) {\r
119     if (! hasConfigurationErrors()) {\r
120       if (hasQuery()) {\r
121         handleQueryStateChanges(commands);\r
122         logger.debug("Processing request for " + commands); \r
123         List<CommandThread> threadList = new ArrayList<CommandThread>();\r
124         StringTokenizer tokens = new StringTokenizer(commands,",");\r
125         while (tokens.hasMoreElements()) {          \r
126           threadList.add(new CommandThread(req.getCommandReadOnly(tokens.nextToken()),searchClient));            \r
127         }\r
128         for (CommandThread thread : threadList) {\r
129           thread.start();\r
130         }\r
131         for (CommandThread thread : threadList) {\r
132           try {\r
133             thread.join();\r
134           } catch (InterruptedException e) {\r
135             e.printStackTrace();\r
136           }\r
137         }\r
138         for (CommandThread thread : threadList) {\r
139            String commandName = thread.getCommand().getName();\r
140            String response = thread.getResponse();\r
141            logger.debug("Response was: " + response);\r
142            Pazpar2ResponseData responseObject = Pazpar2ResponseParser.getParser().getDataObject(response);\r
143            dataObjects.put(commandName, responseObject);        \r
144         }\r
145         if (commands.equals("record")) {\r
146           logger.debug("Record: Active clients: "+getRecord().getActiveClients());\r
147           return getRecord().getActiveClients();\r
148         } else {\r
149           return getActiveClients();\r
150         }  \r
151       } else {\r
152         logger.debug("Skipped requests for " + commands + " as there's not yet a query."); \r
153         resetDataObjects();\r
154         return "0";\r
155       }\r
156     } else {\r
157       logger.error("Did not attempt to execute query since there are configuration errors.");\r
158       return "0";\r
159     }\r
160     \r
161   }\r
162             \r
163                     \r
164   public String toggleRecord (String recId) {\r
165     if (hasRecord(recId)) {\r
166       removeCommand("record");  \r
167       dataObjects.put("record", new RecordResponse());\r
168       return "";\r
169     } else {\r
170       req.getRecord().setRecordId(recId);\r
171       return doCommand("record");\r
172     }\r
173   }\r
174   \r
175   @Override\r
176   public boolean hasRecord (String recId) {\r
177     return req.getCommandReadOnly("record").hasParameters() && getRecord().getRecId().equals(recId);\r
178   }\r
179       \r
180   public ShowResponse getShow () {\r
181     return ((ShowResponse) dataObjects.get("show"));\r
182   }\r
183   \r
184   public StatResponse getStat () {\r
185     return ((StatResponse) dataObjects.get("stat"));\r
186   }\r
187   \r
188   public RecordResponse getRecord() {\r
189     return ((RecordResponse) dataObjects.get("record"));\r
190   }\r
191   \r
192   public TermListsResponse getTermLists () {\r
193     return ((TermListsResponse) dataObjects.get("termlist"));\r
194   }\r
195   \r
196   public List<TermResponse> getFacetTerms (String facet, int count) {\r
197     return (getTermLists().getTermList(facet).getTerms(count));\r
198   }\r
199     \r
200   public List<TermResponse> getFacetTerms (String facet) {\r
201     return (getTermLists().getTermList(facet).getTerms());\r
202   }\r
203   \r
204   public ByTarget getByTarget() {\r
205     return ((ByTarget) dataObjects.get("bytarget"));\r
206   }\r
207   \r
208   \r
209   public String getCurrentStateKey () {    \r
210     return stateMgr.getCurrentState().getKey();\r
211   }\r
212       \r
213   public void setCurrentStateKey(String key) {       \r
214     stateMgr.setCurrentStateKey(key);\r
215   }\r
216   \r
217   public boolean hasConfigurationErrors () {\r
218       return (configurationErrors.size()>0);      \r
219   }\r
220   \r
221   public boolean hasCommandErrors () {\r
222     if (dataObjects.get("search").hasApplicationError()) {\r
223       logger.info("Error detected in search");\r
224       return true;\r
225     }\r
226     for (String name : dataObjects.keySet()) {\r
227       if (dataObjects.get(name).hasApplicationError()) {\r
228         logger.info("Error detected in " + name);\r
229         return true;\r
230       }\r
231     }    \r
232     return false;    \r
233   }\r
234   \r
235   /**\r
236    * Returns true if application error found in any response data objects \r
237    */\r
238   public boolean hasErrors () {\r
239     return hasConfigurationErrors() || hasCommandErrors();\r
240   }\r
241 \r
242   public List<ErrorInterface> getConfigurationErrors() {    \r
243     return configurationErrors;\r
244   }\r
245   \r
246   /**\r
247    * Returns a search command error, if any, otherwise the first\r
248    * error found for an arbitrary command, if any, otherwise\r
249    * an empty dummy error. \r
250    */    \r
251   public ErrorInterface getCommandError() {\r
252     CommandError error = new CommandError();    \r
253     if (dataObjects.get("search").hasApplicationError()) {\r
254       error = dataObjects.get("search").getApplicationError();                        \r
255     } else {\r
256       for (String name : dataObjects.keySet()) {     \r
257         if (dataObjects.get(name).hasApplicationError()) {     \r
258           error = dataObjects.get(name).getApplicationError(); \r
259           break;\r
260         } \r
261       }\r
262     }\r
263     error.setErrorHelper(errorHelper);\r
264     return error;         \r
265   }\r
266   \r
267   protected boolean hasQuery() {    \r
268     return req.getSearch().getParameter("query") != null && req.getSearch().getParameter("query").getValueWithExpressions().length()>0;\r
269   }\r
270     \r
271   public boolean hasRecords () {\r
272     return getStat().getRecords() > 0            \r
273            && getShow().getHits() != null \r
274            && getShow().getHits().size()>0;\r
275   }\r
276     \r
277   public ResultsPager getPager () {\r
278     if (pager == null) {\r
279       pager = new ResultsPager(this);      \r
280     } \r
281     return pager;      \r
282   }\r
283   \r
284   public ResultsPager setPager (int pageRange) {\r
285     pager =  new ResultsPager(this,pageRange,req);\r
286     return pager;\r
287   }\r
288   \r
289   protected ErrorHelper getTroubleshooter() {\r
290     return errorHelper;\r
291   }\r
292   \r
293   protected void handleQueryStateChanges (String commands) {\r
294     if (stateMgr.hasPendingStateChange("search") && hasQuery()) { \r
295       logger.debug("Found pending search change. Doing search before updating " + commands);      \r
296       doSearch();\r
297     } \r
298     if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {        \r
299       logger.debug("Found pending record ID change. Doing record before updating " + commands);\r
300       stateMgr.hasPendingStateChange("record",false);\r
301       if (req.getCommandReadOnly("record").hasParameters()) {\r
302         update("record");\r
303       } else {\r
304         removeCommand("record");  \r
305         dataObjects.put("record", new RecordResponse());\r
306       }\r
307     }\r
308   }\r
309 \r
310   protected String getActiveClients() {    \r
311     if (getShow()!=null) {\r
312       logger.debug("Active clients: "+getShow().getActiveClients());\r
313       return getShow().getActiveClients();\r
314     } else {\r
315       return "";\r
316     }\r
317   }\r
318 \r
319   /**\r
320    * Returns a Pazpar2 command 'detached' from the current Pazpar2 state.\r
321    * \r
322    * 'Detached' is meant to imply that this is a copy of a command in the \r
323    * current state, detached so as to NOT change the current state if \r
324    * modified. It can be viewed and executed, however. \r
325    * \r
326    * In order to modify the command with effect for subsequent searches,\r
327    * it must be checked back into the StateManager, which will\r
328    * then create a new current Pazpar2 state as needed.\r
329    *  \r
330    * @param name\r
331    * @return\r
332    */\r
333   protected Pazpar2Command getCommand(String name) {\r
334     return req.getCommand(name);\r
335   }\r
336   \r
337   /** \r
338    * Returns an interface to a Pazpar2Command with only String getters.\r
339    * \r
340    * Since the command cannot be modified (unless it is cast) we can avoid \r
341    * cloning it before returning it from the current state. \r
342    * It can be used for log statements, checks and for performing the \r
343    * actual pazpar2 request. \r
344    * \r
345    * @param name\r
346    * @return\r
347    */\r
348   protected CommandReadOnly getCommandReadOnly(String name) {\r
349     return req.getCommandReadOnly(name);\r
350   }\r
351 \r
352   \r
353   protected void setCommandParameter(String commandName, CommandParameter parameter) {\r
354     logger.debug("Setting parameter for " + commandName + ": " + parameter);\r
355     Pazpar2Command command = req.getCommand(commandName);\r
356     command.setParameter(parameter);\r
357     stateMgr.checkIn(command);    \r
358   }\r
359   \r
360   \r
361   protected void removeCommandParameter(String commandName, String parameterName) {\r
362     Pazpar2Command command = req.getCommand(commandName);\r
363     command.removeParameter(parameterName);\r
364     stateMgr.checkIn(command);    \r
365   }\r
366   \r
367   protected void removeCommand (String commandName) {\r
368     Pazpar2Command command = req.getCommand(commandName);\r
369     command.removeParameters();\r
370     stateMgr.checkIn(command);\r
371   }\r
372     \r
373   protected String getCommandParameterValue (String commandName, String parameterName, String defaultValue) {    \r
374     CommandReadOnly command = req.getCommandReadOnly(commandName);\r
375     if (command != null) {\r
376       String parameter = command.getParameterValue(parameterName);\r
377       if (parameter != null) {\r
378         return parameter;\r
379       }\r
380     }\r
381     return defaultValue;    \r
382   }\r
383     \r
384   protected int getCommandParameterValue (String commandName, String parameterName, int defaultValue) {\r
385     CommandReadOnly command = req.getCommandReadOnly(commandName);\r
386     if (command != null) {\r
387       String parameter = command.getParameterValue(parameterName);\r
388       if (parameter != null) {\r
389         return Integer.parseInt(parameter);\r
390       }\r
391     }\r
392     return defaultValue;    \r
393   }\r
394 \r
395   protected String doCommand(String commandName) {             \r
396     logger.debug(req.getCommandReadOnly(commandName).getEncodedQueryString() + ": Results for "+ req.getCommandReadOnly("search").getEncodedQueryString());\r
397     return update(commandName);\r
398   }\r
399   \r
400   protected void resetDataObjects() {\r
401     logger.debug("Resetting show,stat,termlist,bytarget,search response objects.");\r
402     dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();\r
403     dataObjects.put("show", new ShowResponse());\r
404     dataObjects.put("stat", new StatResponse());\r
405     dataObjects.put("termlist", new TermListsResponse());\r
406     dataObjects.put("bytarget", new ByTarget());\r
407     dataObjects.put("record", new RecordResponse());\r
408     dataObjects.put("search", new SearchResponse());\r
409   }\r
410   \r
411 \r
412   @Override\r
413   public void stateUpdated(String commandName) {\r
414     logger.debug("State change reported for [" + commandName + "]");\r
415     if (commandName.equals("show")) {\r
416       logger.debug("Updating show");\r
417       update(commandName);\r
418     } \r
419   }\r
420   \r
421 }\r