More work on commands, statemgmt, EL references
[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.enterprise.context.SessionScoped;\r
11 import javax.inject.Inject;\r
12 \r
13 import org.apache.log4j.Logger;\r
14 \r
15 import com.indexdata.pz2utils4jsf.config.ConfigurationReader;\r
16 import com.indexdata.pz2utils4jsf.controls.ResultsPager;\r
17 import com.indexdata.pz2utils4jsf.errors.ConfigurationError;\r
18 import com.indexdata.pz2utils4jsf.errors.ConfigurationException;\r
19 import com.indexdata.pz2utils4jsf.errors.ErrorHelper;\r
20 import com.indexdata.pz2utils4jsf.errors.ErrorInterface;\r
21 import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandParameter;\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 "+getCommand("search").getParameter("query").getEncodedQueryString());\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(getCommand(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   public void setQuery (String query) {\r
164     logger.debug("Creating new command parameter for " + query);\r
165     setCommandParameter("search",new CommandParameter("query","=",query));\r
166   }\r
167   \r
168   public String getQuery () {\r
169     return getCommandParameterValueSimple("search","query",null);\r
170   }\r
171   \r
172   public void setFacet (String facetKey, String term) {           \r
173     if (term != null && term.length()>0) {   \r
174       Pazpar2Command command = getCommand("search");\r
175       command.getParameter("query").addExpression(new Expression(facetKey,"=",term));\r
176       stateMgr.checkIn(command);\r
177       doSearch();\r
178     }            \r
179   }\r
180   \r
181   public void setFacetOnQuery (String facetKey, String term) {\r
182     String facetExpression = facetKey + "=" + term;    \r
183     if (term != null && term.length()>0) {\r
184       setCommandParameter("search",new CommandParameter("query","=", getQuery() + " and " + facetExpression));\r
185       doSearch();        \r
186     }            \r
187   }\r
188       \r
189   public void removeFacet(String facetKey, String term) {\r
190     Pazpar2Command command = getCommand("search");\r
191     command.getParameter("query").removeExpression(new Expression(facetKey,"=",term));\r
192     stateMgr.checkIn(command);\r
193     doSearch();\r
194   }\r
195   \r
196   public void setSingleTargetFilter (String targetId, String targetName) {    \r
197     if (hasSingleTargetFilter(new SingleTargetFilter(targetId,targetName))) {\r
198       logger.debug("Already using target filter " + this.singleTargetFilter.getFilterExpression());\r
199     } else {      \r
200       this.singleTargetFilter = new SingleTargetFilter(targetId,targetName);\r
201       setCommandParameter("search",new CommandParameter("filter","=",this.singleTargetFilter.getFilterExpression()));      \r
202       doSearch();\r
203     }    \r
204   }\r
205 \r
206   public SingleTargetFilter getSingleTargetFilter () {\r
207     return singleTargetFilter;\r
208   }\r
209     \r
210   public void removeSingleTargetFilter () {\r
211     logger.debug("Removing target filter " + singleTargetFilter.getFilterExpression());\r
212     this.singleTargetFilter = null;\r
213     removeCommandParameter("search","filter");         \r
214     doSearch();\r
215   }\r
216   \r
217   public boolean hasSingleTargetFilter() {\r
218     return singleTargetFilter != null;    \r
219   }\r
220         \r
221   public void setSort (String sortOption) {\r
222     logger.debug("Setting sort option: " + sortOption);\r
223     setCommandParameter("show",new CommandParameter("sort","=",sortOption));\r
224     update("show");\r
225   }\r
226   \r
227   public String getSort () {\r
228     return getCommandParameterValue("show","sort","relevance");\r
229   }\r
230     \r
231   public void setPageSize (int perPageOption) {\r
232     if (getPageSize()!=perPageOption) {\r
233      logger.debug("Setting perpage option to " + perPageOption + " and resetting start page.");\r
234      setCommandParameter("show",new CommandParameter("num","=",perPageOption));\r
235      setCommandParameter("show",new CommandParameter("start","=",0));\r
236      update("show");\r
237     } else {\r
238       logger.debug("Not updating page size, already is " + perPageOption);\r
239     }\r
240   }\r
241   \r
242   public int getPageSize () {\r
243     return getCommandParameterValue("show","num",20);\r
244   }\r
245   \r
246   public void setStart (int start) {\r
247     logger.debug("Setting start num to " + start);\r
248     setCommandParameter("show", new CommandParameter("start","=",start));  \r
249     update("show");\r
250   }\r
251   \r
252   public int getStart() {\r
253     return getCommandParameterValue("show","start",0);\r
254   }\r
255           \r
256   public String toggleRecord (String recId) {\r
257     if (hasRecord(recId)) {\r
258       removeCommand("record");  \r
259       dataObjects.put("record", new RecordResponse());\r
260       return "";\r
261     } else {\r
262       setRecordId(recId);\r
263       return doCommand("record");\r
264     }\r
265   }\r
266   \r
267   @Override\r
268   public void setRecordId(String recId) {\r
269     setCommandParameter("record",new CommandParameter("id","=",recId));\r
270   }\r
271   \r
272   @Override\r
273   public String getRecordId () {\r
274     return getCommandParameterValue("record","recid","");\r
275   }\r
276   \r
277   @Override\r
278   public boolean hasRecord (String recId) {\r
279     return getCommand("record").hasParameters() && getRecord().getRecId().equals(recId);\r
280   }\r
281       \r
282   public ShowResponse getShow () {\r
283     return ((ShowResponse) dataObjects.get("show"));\r
284   }\r
285   \r
286   public StatResponse getStat () {\r
287     return ((StatResponse) dataObjects.get("stat"));\r
288   }\r
289   \r
290   public RecordResponse getRecord() {\r
291     return ((RecordResponse) dataObjects.get("record"));\r
292   }\r
293   \r
294   public TermListsResponse getTermLists () {\r
295     return ((TermListsResponse) dataObjects.get("termlist"));\r
296   }\r
297   \r
298   public List<TermResponse> getFacetTerms (String facet, int count) {\r
299     return (getTermLists().getTermList(facet).getTerms(count));\r
300   }\r
301     \r
302   public List<TermResponse> getFacetTerms (String facet) {\r
303     return (getTermLists().getTermList(facet).getTerms());\r
304   }\r
305   \r
306   public ByTarget getByTarget() {\r
307     return ((ByTarget) dataObjects.get("bytarget"));\r
308   }\r
309   \r
310   \r
311   public String getCurrentStateKey () {    \r
312     return stateMgr.getCurrentState().getKey();\r
313   }\r
314       \r
315   public void setCurrentStateKey(String key) {       \r
316     stateMgr.setCurrentStateKey(key);\r
317   }\r
318   \r
319   public boolean hasConfigurationErrors () {\r
320       return (configurationErrors.size()>0);      \r
321   }\r
322   \r
323   public boolean hasCommandErrors () {\r
324     if (dataObjects.get("search").hasApplicationError()) {\r
325       logger.info("Error detected in search");\r
326       return true;\r
327     }\r
328     for (String name : dataObjects.keySet()) {\r
329       if (dataObjects.get(name).hasApplicationError()) {\r
330         logger.info("Error detected in " + name);\r
331         return true;\r
332       }\r
333     }    \r
334     return false;    \r
335   }\r
336   \r
337   /**\r
338    * Returns true if application error found in any response data objects \r
339    */\r
340   public boolean hasErrors () {\r
341     return hasConfigurationErrors() || hasCommandErrors();\r
342   }\r
343 \r
344   public List<ErrorInterface> getConfigurationErrors() {    \r
345     return configurationErrors;\r
346   }\r
347   \r
348   /**\r
349    * Returns a search command error, if any, otherwise the first\r
350    * error found for an arbitrary command, if any, otherwise\r
351    * an empty dummy error. \r
352    */    \r
353   public ErrorInterface getCommandError() {\r
354     CommandError error = new CommandError();    \r
355     if (dataObjects.get("search").hasApplicationError()) {\r
356       error = dataObjects.get("search").getApplicationError();                        \r
357     } else {\r
358       for (String name : dataObjects.keySet()) {     \r
359         if (dataObjects.get(name).hasApplicationError()) {     \r
360           error = dataObjects.get(name).getApplicationError(); \r
361           break;\r
362         } \r
363       }\r
364     }\r
365     error.setErrorHelper(errorHelper);\r
366     return error;         \r
367   }\r
368 \r
369     \r
370   protected boolean hasSingleTargetFilter(SingleTargetFilter targetFilter) {\r
371     return hasSingleTargetFilter() && targetFilter.equals(this.singleTargetFilter);\r
372   }\r
373   \r
374   protected boolean hasQuery() {\r
375     logger.debug("req is " + req);\r
376     return req.getSearch().getParameter("query") != null && req.getSearch().getParameter("query").getValueWithExpressions().length()>0;\r
377   }\r
378     \r
379   public boolean hasRecords () {\r
380     return getStat().getRecords() > 0            \r
381            && getShow().getHits() != null \r
382            && getShow().getHits().size()>0;\r
383   }\r
384     \r
385   public ResultsPager getPager () {\r
386     if (pager == null) {\r
387       pager = new ResultsPager(this);      \r
388     } \r
389     return pager;      \r
390   }\r
391   \r
392   public ResultsPager setPager (int pageRange) {\r
393     pager =  new ResultsPager(this,pageRange);\r
394     return pager;\r
395   }\r
396   \r
397   protected ErrorHelper getTroubleshooter() {\r
398     return errorHelper;\r
399   }\r
400   \r
401   protected void handleQueryStateChanges (String commands) {\r
402     if (stateMgr.hasPendingStateChange("search") && hasQuery()) { \r
403       logger.debug("Found pending search change. Doing search before updating " + commands);      \r
404       doSearch();\r
405     } \r
406     if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {        \r
407       logger.debug("Found pending record ID change. Doing record before updating " + commands);\r
408       stateMgr.hasPendingStateChange("record",false);\r
409       if (getCommand("record").hasParameters()) {\r
410         update("record");\r
411       } else {\r
412         removeCommand("record");  \r
413         dataObjects.put("record", new RecordResponse());\r
414       }\r
415     }\r
416   }\r
417 \r
418   protected String getActiveClients() {    \r
419     if (getShow()!=null) {\r
420       logger.debug("Active clients: "+getShow().getActiveClients());\r
421       return getShow().getActiveClients();\r
422     } else {\r
423       return "";\r
424     }\r
425   }\r
426 \r
427   /**\r
428    * Returns a Pazpar2 command 'detached' from the current Pazpar2 state.\r
429    * \r
430    * 'Detached' is meant to imply that this is a copy of a command in the \r
431    * current state, detached so as to NOT change the current state if \r
432    * modified. It can be viewed and executed, however. \r
433    * \r
434    * In order to modify the command with effect for subsequent searches,\r
435    * it must be checked back into the StateManager, which will\r
436    * then create a new current Pazpar2 state as needed.\r
437    *  \r
438    * @param name\r
439    * @return\r
440    */\r
441   protected Pazpar2Command getCommand(String name) {\r
442     return stateMgr.checkOut(name);\r
443   }\r
444   \r
445   protected void setCommandParameter(String commandName, CommandParameter parameter) {\r
446     logger.debug("Setting parameter for " + commandName + ": " + parameter);\r
447     Pazpar2Command command = getCommand(commandName);\r
448     command.setParameter(parameter);\r
449     stateMgr.checkIn(command);    \r
450   }\r
451   \r
452   \r
453   protected void removeCommandParameter(String commandName, String parameterName) {\r
454     Pazpar2Command command = getCommand(commandName);\r
455     command.removeParameter(parameterName);\r
456     stateMgr.checkIn(command);    \r
457   }\r
458   \r
459   protected void removeCommand (String commandName) {\r
460     Pazpar2Command command = getCommand(commandName);\r
461     command.removeParameters();\r
462     stateMgr.checkIn(command);\r
463   }\r
464     \r
465   protected String getCommandParameterValue (String commandName, String parameterName, String defaultValue) {    \r
466     Pazpar2Command command = getCommand(commandName);\r
467     if (command != null) {\r
468       CommandParameter parameter = command.getParameter(parameterName);\r
469       if (parameter != null) {\r
470         return parameter.getValueWithExpressions();\r
471       }\r
472     }\r
473     return defaultValue;    \r
474   }\r
475   \r
476   protected String getCommandParameterValueSimple (String commandName, String parameterName, String defaultValue) {    \r
477     Pazpar2Command command = getCommand(commandName);\r
478     if (command != null) {\r
479       CommandParameter parameter = command.getParameter(parameterName);\r
480       if (parameter != null) {\r
481         return parameter.getSimpleValue();\r
482       }\r
483     }\r
484     return defaultValue;    \r
485   }\r
486 \r
487   \r
488   protected int getCommandParameterValue (String commandName, String parameterName, int defaultValue) {\r
489     Pazpar2Command command = getCommand(commandName);\r
490     if (command != null) {\r
491       CommandParameter parameter = command.getParameter(parameterName);\r
492       if (parameter != null) {\r
493         return Integer.parseInt(parameter.getSimpleValue());\r
494       }\r
495     }\r
496     return defaultValue;    \r
497   }\r
498 \r
499   protected String doCommand(String commandName) {     \r
500     Pazpar2Command command = req.getCommand(commandName);    \r
501     logger.debug(command.getEncodedQueryString() + ": Results for "+ getCommand("search").getEncodedQueryString());\r
502     return update(commandName);\r
503   }\r
504   \r
505   protected void resetDataObjects() {\r
506     logger.debug("Resetting show,stat,termlist,bytarget,search response objects.");\r
507     dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();\r
508     dataObjects.put("show", new ShowResponse());\r
509     dataObjects.put("stat", new StatResponse());\r
510     dataObjects.put("termlist", new TermListsResponse());\r
511     dataObjects.put("bytarget", new ByTarget());\r
512     dataObjects.put("record", new RecordResponse());\r
513     dataObjects.put("search", new SearchResponse());\r
514   }\r
515   \r
516   @Override\r
517   public void setFilter(String filterExpression) {\r
518     logger.debug("Setting filter to " + filterExpression);\r
519     setCommandParameter("search",new CommandParameter("filter","=",filterExpression));    \r
520   }\r
521   \r
522   public String getFilter() {\r
523     return getCommandParameterValueSimple("search", "filter", "");\r
524   }\r
525   \r
526   public boolean hasFilter () {\r
527     return getFilter().length()>0;\r
528   }\r
529 \r
530   @Override\r
531   public void stateUpdate(String commandName) {\r
532     logger.debug("State change reported for [" + commandName + "]");\r
533     if (commandName.equals("show")) {\r
534       logger.debug("Updating show");\r
535       update(commandName);\r
536     }\r
537   }\r
538   \r
539 }\r