Creates read-only command for optimization
[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.commands.SearchCommand;\r
25 import com.indexdata.pz2utils4jsf.pazpar2.data.ByTarget;\r
26 import com.indexdata.pz2utils4jsf.pazpar2.data.CommandError;\r
27 import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData;\r
28 import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseParser;\r
29 import com.indexdata.pz2utils4jsf.pazpar2.data.RecordResponse;\r
30 import com.indexdata.pz2utils4jsf.pazpar2.data.SearchResponse;\r
31 import com.indexdata.pz2utils4jsf.pazpar2.data.ShowResponse;\r
32 import com.indexdata.pz2utils4jsf.pazpar2.data.StatResponse;\r
33 import com.indexdata.pz2utils4jsf.pazpar2.data.TermListsResponse;\r
34 import com.indexdata.pz2utils4jsf.pazpar2.data.TermResponse;\r
35 import com.indexdata.pz2utils4jsf.pazpar2.state.StateListener;\r
36 import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager;\r
37 import com.indexdata.pz2utils4jsf.utils.Utils;\r
38 \r
39 @ForStraightPz2\r
40 public class Pz2Session implements Pz2Interface, StateListener {\r
41     \r
42   private static final long serialVersionUID = 3947514708343320514L;\r
43   private static Logger logger = Logger.getLogger(Pz2Session.class);\r
44   \r
45   protected Map<String,Pazpar2ResponseData> dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();\r
46   \r
47   @Inject StateManager stateMgr;\r
48   @Inject Pazpar2Commands req;\r
49   \r
50   protected ErrorHelper errorHelper = null;\r
51   \r
52   protected List<ErrorInterface> configurationErrors = null;\r
53   protected SearchClient searchClient = null;   \r
54   protected SingleTargetFilter singleTargetFilter = null;  \r
55   protected ResultsPager pager = null; \r
56     \r
57   public Pz2Session () {\r
58     logger.info("Instantiating pz2 session object [" + Utils.objectId(this) + "]");        \r
59   }\r
60   \r
61   @PostConstruct\r
62   public void listenToStateManager() {\r
63     logger.debug("in post-construct of Pz2Session stateMgr is " + stateMgr);\r
64     logger.debug("in post-construct req is " + req);\r
65     stateMgr.addStateListener(this);\r
66   }\r
67     \r
68   public void configureClient(SearchClient searchClient, ConfigurationReader configReader) {\r
69     configurationErrors = new ArrayList<ErrorInterface>();\r
70     errorHelper = new ErrorHelper(configReader);    \r
71     logger.debug(Utils.objectId(this) + " will configure search client for the session");\r
72     try {\r
73       searchClient.configure(configReader);            \r
74       // At the time of writing this search client is injected using Weld. \r
75       // However, the client is used for asynchronously sending off requests\r
76       // to the server AND propagation of context to threads is currently \r
77       // not supported. Trying to do so throws a WELD-001303 error. \r
78       // To avoid that, a context free client is cloned from the context \r
79       // dependent one. \r
80       // If propagation to threads gets supported, the cloning can go. \r
81       this.searchClient = searchClient.cloneMe();         \r
82     } catch (ConfigurationException e) {\r
83       configurationErrors.add(new ConfigurationError("Search Client","Configuration",e.getMessage(),new ErrorHelper(configReader)));          \r
84     } \r
85     logger.info(configReader.document());\r
86     resetDataObjects();\r
87   }\r
88       \r
89   public void doSearch(String query) {\r
90     setCommandParameter("search",new CommandParameter("query","=",query));     \r
91     doSearch();\r
92   }\r
93 \r
94   public void doSearch() { \r
95     stateMgr.hasPendingStateChange("search",false);\r
96     resetDataObjects();\r
97     removeCommand("record");\r
98     setCommandParameter("show",new CommandParameter("start","=",0));    \r
99     logger.debug(Utils.objectId(this) + " is searching using "+req.getCommandReadOnly("search").getUrlEncodedParameterValue("query"));\r
100     doCommand("search");    \r
101   }\r
102       \r
103   /**\r
104    * Refreshes 'show', 'stat', 'termlist', and 'bytarget' data object from pazpar2\r
105    * \r
106    * @return Number of activeclients at the time of the 'show' command.\r
107    */\r
108   public String update () {\r
109     logger.debug("Updating show,stat,termlist,bytarget from pazpar2");\r
110     return update("show,stat,termlist,bytarget");\r
111   }\r
112    \r
113   /**\r
114    * Refreshes the data objects listed in 'commands' from pazpar2\r
115    * \r
116    * @param commands\r
117    * @return Number of activeclients at the time of the 'show' command\r
118    */\r
119   public String update (String commands) {\r
120     if (! hasConfigurationErrors()) {\r
121       if (hasQuery()) {\r
122         handleQueryStateChanges(commands);\r
123         logger.debug("Processing request for " + commands); \r
124         List<CommandThread> threadList = new ArrayList<CommandThread>();\r
125         StringTokenizer tokens = new StringTokenizer(commands,",");\r
126         while (tokens.hasMoreElements()) {          \r
127           threadList.add(new CommandThread(req.getCommandReadOnly(tokens.nextToken()),searchClient));            \r
128         }\r
129         for (CommandThread thread : threadList) {\r
130           thread.start();\r
131         }\r
132         for (CommandThread thread : threadList) {\r
133           try {\r
134             thread.join();\r
135           } catch (InterruptedException e) {\r
136             e.printStackTrace();\r
137           }\r
138         }\r
139         for (CommandThread thread : threadList) {\r
140            String commandName = thread.getCommand().getName();\r
141            String response = thread.getResponse();\r
142            logger.debug("Response was: " + response);\r
143            Pazpar2ResponseData responseObject = Pazpar2ResponseParser.getParser().getDataObject(response);\r
144            dataObjects.put(commandName, responseObject);        \r
145         }\r
146         if (commands.equals("record")) {\r
147           logger.debug("Record: Active clients: "+getRecord().getActiveClients());\r
148           return getRecord().getActiveClients();\r
149         } else {\r
150           return getActiveClients();\r
151         }  \r
152       } else {\r
153         logger.debug("Skipped requests for " + commands + " as there's not yet a query."); \r
154         resetDataObjects();\r
155         return "0";\r
156       }\r
157     } else {\r
158       logger.error("Did not attempt to execute query since there are configuration errors.");\r
159       return "0";\r
160     }\r
161     \r
162   }\r
163         \r
164   /*\r
165   public void setQuery (String query) {\r
166     logger.debug("Creating new command parameter for " + query);\r
167     setCommandParameter("search",new CommandParameter("query","=",query));\r
168   }\r
169   \r
170   public String getQuery () {\r
171     return getCommandParameterValueSimple("search","query",null);\r
172   }\r
173   */\r
174   \r
175   public void setFacet (String facetKey, String term) {           \r
176     if (term != null && term.length()>0) {   \r
177       Pazpar2Command command = req.getCommand("search");\r
178       command.getParameter("query").addExpression(new Expression(facetKey,"=",term));\r
179       stateMgr.checkIn(command);\r
180       doSearch();\r
181     }            \r
182   }\r
183   \r
184   public void setFacetOnQuery (String facetKey, String term) {\r
185     String facetExpression = facetKey + "=" + term;    \r
186     if (term != null && term.length()>0) {\r
187       String currentQuery= req.getCommandReadOnly("search").getParameterValue("query");\r
188       setCommandParameter("search",new CommandParameter("query","=", currentQuery + " and " + facetExpression));\r
189       doSearch();        \r
190     }            \r
191   }\r
192       \r
193   public void removeFacet(String facetKey, String term) {\r
194     SearchCommand command = req.getSearch();\r
195     command.getParameter("query").removeExpression(new Expression(facetKey,"=",term));\r
196     stateMgr.checkIn(command);\r
197     doSearch();\r
198   }\r
199   \r
200   public void setSingleTargetFilter (String targetId, String targetName) {    \r
201     if (hasSingleTargetFilter(new SingleTargetFilter(targetId,targetName))) {\r
202       logger.debug("Already using target filter " + this.singleTargetFilter.getFilterExpression());\r
203     } else {      \r
204       this.singleTargetFilter = new SingleTargetFilter(targetId,targetName);\r
205       setCommandParameter("search",new CommandParameter("filter","=",this.singleTargetFilter.getFilterExpression()));      \r
206       doSearch();\r
207     }    \r
208   }\r
209 \r
210   public SingleTargetFilter getSingleTargetFilter () {\r
211     return singleTargetFilter;\r
212   }\r
213     \r
214   public void removeSingleTargetFilter () {\r
215     logger.debug("Removing target filter " + singleTargetFilter.getFilterExpression());\r
216     this.singleTargetFilter = null;\r
217     removeCommandParameter("search","filter");         \r
218     doSearch();\r
219   }\r
220   \r
221   public boolean hasSingleTargetFilter() {\r
222     return singleTargetFilter != null;    \r
223   }\r
224         \r
225   public void setSort (String sortOption) {\r
226     logger.debug("Setting sort option: " + sortOption);\r
227     setCommandParameter("show",new CommandParameter("sort","=",sortOption));\r
228     update("show");\r
229   }\r
230   \r
231   public String getSort () {\r
232     return getCommandParameterValue("show","sort","relevance");\r
233   }\r
234     \r
235   public void setPageSize (int perPageOption) {\r
236     if (getPageSize()!=perPageOption) {\r
237      logger.debug("Setting perpage option to " + perPageOption + " and resetting start page.");\r
238      setCommandParameter("show",new CommandParameter("num","=",perPageOption));\r
239      setCommandParameter("show",new CommandParameter("start","=",0));\r
240      update("show");\r
241     } else {\r
242       logger.debug("Not updating page size, already is " + perPageOption);\r
243     }\r
244   }\r
245   \r
246   public int getPageSize () {\r
247     return getCommandParameterValue("show","num",20);\r
248   }\r
249   \r
250   public void setStart (int start) {\r
251     logger.debug("Setting start num to " + start);\r
252     setCommandParameter("show", new CommandParameter("start","=",start));  \r
253     update("show");\r
254   }\r
255   \r
256   public int getStart() {\r
257     return getCommandParameterValue("show","start",0);\r
258   }\r
259           \r
260   public String toggleRecord (String recId) {\r
261     if (hasRecord(recId)) {\r
262       removeCommand("record");  \r
263       dataObjects.put("record", new RecordResponse());\r
264       return "";\r
265     } else {\r
266       setRecordId(recId);\r
267       return doCommand("record");\r
268     }\r
269   }\r
270   \r
271   @Override\r
272   public void setRecordId(String recId) {\r
273     setCommandParameter("record",new CommandParameter("id","=",recId));\r
274   }\r
275   \r
276   @Override\r
277   public String getRecordId () {\r
278     return getCommandParameterValue("record","recid","");\r
279   }\r
280   \r
281   @Override\r
282   public boolean hasRecord (String recId) {\r
283     return req.getCommandReadOnly("record").hasParameters() && getRecord().getRecId().equals(recId);\r
284   }\r
285       \r
286   public ShowResponse getShow () {\r
287     return ((ShowResponse) dataObjects.get("show"));\r
288   }\r
289   \r
290   public StatResponse getStat () {\r
291     return ((StatResponse) dataObjects.get("stat"));\r
292   }\r
293   \r
294   public RecordResponse getRecord() {\r
295     return ((RecordResponse) dataObjects.get("record"));\r
296   }\r
297   \r
298   public TermListsResponse getTermLists () {\r
299     return ((TermListsResponse) dataObjects.get("termlist"));\r
300   }\r
301   \r
302   public List<TermResponse> getFacetTerms (String facet, int count) {\r
303     return (getTermLists().getTermList(facet).getTerms(count));\r
304   }\r
305     \r
306   public List<TermResponse> getFacetTerms (String facet) {\r
307     return (getTermLists().getTermList(facet).getTerms());\r
308   }\r
309   \r
310   public ByTarget getByTarget() {\r
311     return ((ByTarget) dataObjects.get("bytarget"));\r
312   }\r
313   \r
314   \r
315   public String getCurrentStateKey () {    \r
316     return stateMgr.getCurrentState().getKey();\r
317   }\r
318       \r
319   public void setCurrentStateKey(String key) {       \r
320     stateMgr.setCurrentStateKey(key);\r
321   }\r
322   \r
323   public boolean hasConfigurationErrors () {\r
324       return (configurationErrors.size()>0);      \r
325   }\r
326   \r
327   public boolean hasCommandErrors () {\r
328     if (dataObjects.get("search").hasApplicationError()) {\r
329       logger.info("Error detected in search");\r
330       return true;\r
331     }\r
332     for (String name : dataObjects.keySet()) {\r
333       if (dataObjects.get(name).hasApplicationError()) {\r
334         logger.info("Error detected in " + name);\r
335         return true;\r
336       }\r
337     }    \r
338     return false;    \r
339   }\r
340   \r
341   /**\r
342    * Returns true if application error found in any response data objects \r
343    */\r
344   public boolean hasErrors () {\r
345     return hasConfigurationErrors() || hasCommandErrors();\r
346   }\r
347 \r
348   public List<ErrorInterface> getConfigurationErrors() {    \r
349     return configurationErrors;\r
350   }\r
351   \r
352   /**\r
353    * Returns a search command error, if any, otherwise the first\r
354    * error found for an arbitrary command, if any, otherwise\r
355    * an empty dummy error. \r
356    */    \r
357   public ErrorInterface getCommandError() {\r
358     CommandError error = new CommandError();    \r
359     if (dataObjects.get("search").hasApplicationError()) {\r
360       error = dataObjects.get("search").getApplicationError();                        \r
361     } else {\r
362       for (String name : dataObjects.keySet()) {     \r
363         if (dataObjects.get(name).hasApplicationError()) {     \r
364           error = dataObjects.get(name).getApplicationError(); \r
365           break;\r
366         } \r
367       }\r
368     }\r
369     error.setErrorHelper(errorHelper);\r
370     return error;         \r
371   }\r
372 \r
373     \r
374   protected boolean hasSingleTargetFilter(SingleTargetFilter targetFilter) {\r
375     return hasSingleTargetFilter() && targetFilter.equals(this.singleTargetFilter);\r
376   }\r
377   \r
378   protected boolean hasQuery() {    \r
379     return req.getSearch().getParameter("query") != null && req.getSearch().getParameter("query").getValueWithExpressions().length()>0;\r
380   }\r
381     \r
382   public boolean hasRecords () {\r
383     return getStat().getRecords() > 0            \r
384            && getShow().getHits() != null \r
385            && getShow().getHits().size()>0;\r
386   }\r
387     \r
388   public ResultsPager getPager () {\r
389     if (pager == null) {\r
390       pager = new ResultsPager(this);      \r
391     } \r
392     return pager;      \r
393   }\r
394   \r
395   public ResultsPager setPager (int pageRange) {\r
396     pager =  new ResultsPager(this,pageRange);\r
397     return pager;\r
398   }\r
399   \r
400   protected ErrorHelper getTroubleshooter() {\r
401     return errorHelper;\r
402   }\r
403   \r
404   protected void handleQueryStateChanges (String commands) {\r
405     if (stateMgr.hasPendingStateChange("search") && hasQuery()) { \r
406       logger.debug("Found pending search change. Doing search before updating " + commands);      \r
407       doSearch();\r
408     } \r
409     if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {        \r
410       logger.debug("Found pending record ID change. Doing record before updating " + commands);\r
411       stateMgr.hasPendingStateChange("record",false);\r
412       if (req.getCommandReadOnly("record").hasParameters()) {\r
413         update("record");\r
414       } else {\r
415         removeCommand("record");  \r
416         dataObjects.put("record", new RecordResponse());\r
417       }\r
418     }\r
419   }\r
420 \r
421   protected String getActiveClients() {    \r
422     if (getShow()!=null) {\r
423       logger.debug("Active clients: "+getShow().getActiveClients());\r
424       return getShow().getActiveClients();\r
425     } else {\r
426       return "";\r
427     }\r
428   }\r
429 \r
430   /**\r
431    * Returns a Pazpar2 command 'detached' from the current Pazpar2 state.\r
432    * \r
433    * 'Detached' is meant to imply that this is a copy of a command in the \r
434    * current state, detached so as to NOT change the current state if \r
435    * modified. It can be viewed and executed, however. \r
436    * \r
437    * In order to modify the command with effect for subsequent searches,\r
438    * it must be checked back into the StateManager, which will\r
439    * then create a new current Pazpar2 state as needed.\r
440    *  \r
441    * @param name\r
442    * @return\r
443    */\r
444   protected Pazpar2Command getCommand(String name) {\r
445     return req.getCommand(name);\r
446   }\r
447   \r
448   /** \r
449    * Returns an interface to a Pazpar2Command with only String getters.\r
450    * \r
451    * Since the command cannot be modified (unless it is cast) we can avoid \r
452    * cloning it before returning it from the current state. \r
453    * It can be used for log statements, checks and for performing the \r
454    * actual pazpar2 request. \r
455    * \r
456    * @param name\r
457    * @return\r
458    */\r
459   protected CommandReadOnly getCommandReadOnly(String name) {\r
460     return req.getCommandReadOnly(name);\r
461   }\r
462 \r
463   \r
464   protected void setCommandParameter(String commandName, CommandParameter parameter) {\r
465     logger.debug("Setting parameter for " + commandName + ": " + parameter);\r
466     Pazpar2Command command = req.getCommand(commandName);\r
467     command.setParameter(parameter);\r
468     stateMgr.checkIn(command);    \r
469   }\r
470   \r
471   \r
472   protected void removeCommandParameter(String commandName, String parameterName) {\r
473     Pazpar2Command command = req.getCommand(commandName);\r
474     command.removeParameter(parameterName);\r
475     stateMgr.checkIn(command);    \r
476   }\r
477   \r
478   protected void removeCommand (String commandName) {\r
479     Pazpar2Command command = req.getCommand(commandName);\r
480     command.removeParameters();\r
481     stateMgr.checkIn(command);\r
482   }\r
483     \r
484   protected String getCommandParameterValue (String commandName, String parameterName, String defaultValue) {    \r
485     CommandReadOnly command = req.getCommandReadOnly(commandName);\r
486     if (command != null) {\r
487       String parameter = command.getParameterValue(parameterName);\r
488       if (parameter != null) {\r
489         return parameter;\r
490       }\r
491     }\r
492     return defaultValue;    \r
493   }\r
494     \r
495   protected int getCommandParameterValue (String commandName, String parameterName, int defaultValue) {\r
496     CommandReadOnly command = req.getCommandReadOnly(commandName);\r
497     if (command != null) {\r
498       String parameter = command.getParameterValue(parameterName);\r
499       if (parameter != null) {\r
500         return Integer.parseInt(parameter);\r
501       }\r
502     }\r
503     return defaultValue;    \r
504   }\r
505 \r
506   protected String doCommand(String commandName) {             \r
507     logger.debug(req.getCommandReadOnly(commandName).getEncodedQueryString() + ": Results for "+ req.getCommandReadOnly("search").getEncodedQueryString());\r
508     return update(commandName);\r
509   }\r
510   \r
511   protected void resetDataObjects() {\r
512     logger.debug("Resetting show,stat,termlist,bytarget,search response objects.");\r
513     dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();\r
514     dataObjects.put("show", new ShowResponse());\r
515     dataObjects.put("stat", new StatResponse());\r
516     dataObjects.put("termlist", new TermListsResponse());\r
517     dataObjects.put("bytarget", new ByTarget());\r
518     dataObjects.put("record", new RecordResponse());\r
519     dataObjects.put("search", new SearchResponse());\r
520   }\r
521   \r
522   @Override\r
523   public void setFilter(String filterExpression) {\r
524     logger.debug("Setting filter to " + filterExpression);\r
525     setCommandParameter("search",new CommandParameter("filter","=",filterExpression));    \r
526   }\r
527   \r
528   public String getFilter() {\r
529     return getCommandParameterValue("search", "filter", "");\r
530   }\r
531   \r
532   public boolean hasFilter () {\r
533     return getFilter().length()>0;\r
534   }\r
535 \r
536   @Override\r
537   public void stateUpdate(String commandName) {\r
538     logger.debug("State change reported for [" + commandName + "]");\r
539     if (commandName.equals("show")) {\r
540       logger.debug("Updating show");\r
541       update(commandName);\r
542     }\r
543   }\r
544   \r
545 }\r