Fixes search state bug
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / mkjsf / pazpar2 / Pz2Service.java
1 package com.indexdata.mkjsf.pazpar2;\r
2 \r
3 import java.io.Serializable;\r
4 import java.lang.annotation.Retention;\r
5 import java.lang.annotation.Target;\r
6 import java.util.ArrayList;\r
7 import java.util.Arrays;\r
8 import java.util.HashMap;\r
9 import java.util.List;\r
10 import java.util.Map;\r
11 import java.util.StringTokenizer;\r
12 \r
13 import javax.annotation.PostConstruct;\r
14 import javax.enterprise.context.SessionScoped;\r
15 import javax.enterprise.inject.Produces;\r
16 import javax.faces.context.FacesContext;\r
17 import javax.inject.Inject;\r
18 import javax.inject.Named;\r
19 import javax.inject.Qualifier;\r
20 \r
21 import org.apache.log4j.Logger;\r
22 \r
23 import com.indexdata.mkjsf.config.Configurable;\r
24 import com.indexdata.mkjsf.config.Configuration;\r
25 import com.indexdata.mkjsf.config.ConfigurationReader;\r
26 import com.indexdata.mkjsf.controls.ResultsPager;\r
27 import com.indexdata.mkjsf.errors.ConfigurationError;\r
28 import com.indexdata.mkjsf.errors.ConfigurationException;\r
29 import com.indexdata.mkjsf.errors.ErrorCentral;\r
30 import com.indexdata.mkjsf.errors.ErrorHelper;\r
31 import com.indexdata.mkjsf.errors.MissingConfigurationContextException;\r
32 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Commands;\r
33 import com.indexdata.mkjsf.pazpar2.data.RecordResponse;\r
34 import com.indexdata.mkjsf.pazpar2.data.Responses;\r
35 import com.indexdata.mkjsf.pazpar2.state.StateListener;\r
36 import com.indexdata.mkjsf.pazpar2.state.StateManager;\r
37 import com.indexdata.mkjsf.utils.Utils;\r
38 \r
39 @Named("pz2") @SessionScoped\r
40 public class Pz2Service implements StateListener, Configurable, Serializable {\r
41 \r
42   private static final String MODULE_NAME = "service";\r
43   private static String SERVICE_TYPE_TBD = "TBD", SERVICE_TYPE_PZ2 = "PZ2", SERVICE_TYPE_SP = "SP";\r
44   private static final List<String> serviceTypes = \r
45                 Arrays.asList(SERVICE_TYPE_PZ2,SERVICE_TYPE_SP,SERVICE_TYPE_TBD);\r
46   private String serviceType = SERVICE_TYPE_TBD;\r
47   private List<String> serviceProxyUrls = new ArrayList<String>();\r
48   public static final String SERVICE_PROXY_URL_LIST = "SERVICE_PROXY_URL_LIST";\r
49   private List<String> pazpar2Urls = new ArrayList<String>();\r
50   public static final String PAZPAR2_URL_LIST = "PAZPAR2_URL_LIST";\r
51 \r
52   private static final long serialVersionUID = 3440277287081557861L;\r
53   private static Logger logger = Logger.getLogger(Pz2Service.class);  \r
54   protected Pz2Client pz2Client = null;\r
55   protected ServiceProxyClient spClient = null;\r
56   protected SearchClient searchClient = null;  \r
57     \r
58   @Inject ConfigurationReader configurator;\r
59   \r
60   private StateManager stateMgr = null;\r
61   private Pazpar2Commands pzreq = null;\r
62   private Responses pzresp = null;\r
63   private ErrorCentral errors = null;  \r
64   \r
65   protected ResultsPager pager = null; \r
66   \r
67   protected ErrorHelper errorHelper = null;\r
68               \r
69   public Pz2Service () {\r
70     logger.info("Instantiating pz2 bean [" + Utils.objectId(this) + "]");    \r
71   }\r
72   \r
73   public static Pz2Service get() {\r
74     FacesContext context = FacesContext.getCurrentInstance();\r
75     return (Pz2Service) context.getApplication().evaluateExpressionGet(context, "#{pz2}", Object.class); \r
76   }\r
77     \r
78   @PostConstruct\r
79   public void postConstruct() throws MissingConfigurationContextException {    \r
80     logger.info("Pz2Service PostConstruct of " + this);\r
81     stateMgr = new StateManager();\r
82     pzreq = new Pazpar2Commands();\r
83     pzresp = new Responses();    \r
84     errors = new ErrorCentral(); \r
85     pzresp.setErrorHelper(errors.getHelper());\r
86     \r
87     logger.debug("Pz2Service PostConstruct: Configurator is " + configurator);\r
88     logger.debug(Utils.objectId(this) + " will instantiate a Pz2Client next.");    \r
89     pz2Client = new Pz2Client();\r
90     spClient = new ServiceProxyClient();\r
91     stateMgr.addStateListener(this);\r
92     try {\r
93       configureClient(pz2Client,configurator);      \r
94       configureClient(spClient,configurator);\r
95       this.configure(configurator);\r
96     } catch (MissingConfigurationContextException mcc) {\r
97       logger.info("No configuration context available at this point");\r
98       logger.debug("Configuration invoked from a Servlet filter before application start?");\r
99       throw mcc;\r
100     } catch (ConfigurationException e) {\r
101       logger.warn("There was a problem configuring the Pz2Service and/or clients (\"pz2\")");\r
102       e.printStackTrace();\r
103     }     \r
104   }\r
105   \r
106   @Qualifier\r
107   @Target({java.lang.annotation.ElementType.TYPE,\r
108            java.lang.annotation.ElementType.METHOD,\r
109            java.lang.annotation.ElementType.PARAMETER,\r
110            java.lang.annotation.ElementType.FIELD})\r
111   @Retention(java.lang.annotation.RetentionPolicy.RUNTIME)\r
112   public  @interface Preferred{}\r
113   \r
114   @Produces @Preferred @SessionScoped @Named("pzresp") public Responses getPzresp () {\r
115     logger.trace("Producing pzresp");\r
116     return pzresp;\r
117   }\r
118   \r
119   @Produces @Preferred @SessionScoped @Named("pzreq") public Pazpar2Commands getPzreq () {\r
120     logger.trace("Producing pzreq");\r
121     return pzreq;\r
122   }\r
123   \r
124   @Produces @Preferred @SessionScoped @Named("errors") public ErrorCentral getErrors() {\r
125     logger.trace("Producing errors");\r
126     return errors;\r
127   }\r
128   \r
129   @Produces @Preferred @SessionScoped @Named("stateMgr") public StateManager getStateMgr() {\r
130     logger.trace("Producing stateMgr");\r
131     return stateMgr;\r
132   }\r
133   \r
134   public void configureClient(SearchClient client, ConfigurationReader configReader)  throws MissingConfigurationContextException {\r
135     logger.debug(Utils.objectId(this) + " will configure search client for the session");\r
136     try {\r
137       client.configure(configReader);\r
138     } catch (MissingConfigurationContextException mcce) {\r
139       logger.info("No Faces context is available to the configurator at this time of invocation");\r
140       throw mcce;\r
141     } catch (ConfigurationException e) {\r
142       logger.debug("Pz2Service adding configuration error");\r
143       errors.addConfigurationError(new ConfigurationError("Search Client","Configuration",e.getMessage()));                \r
144     }\r
145     logger.info(configReader.document());\r
146     pzresp.getSp().resetAuthAndBeyond(true);    \r
147   }\r
148   \r
149   public void resetSearchAndRecordCommands () {\r
150     pzreq.getRecord().removeParametersInState();\r
151     pzreq.getSearch().removeParametersInState();   \r
152   }\r
153      \r
154   \r
155   /**\r
156    * Updates display data objects by issuing the following pazpar2 commands: \r
157    * 'show', 'stat', 'termlist' and 'bytarget'.\r
158    * \r
159    * If there is an outstanding change to the search command, a search\r
160    * will be issued before the updates are performed. \r
161    *  \r
162    * Returns a count of the remaining active clients from the most recent search.\r
163    * \r
164    * After refreshing the data from pazpar2 the UI components displaying those \r
165    * data should be re-rendered.\r
166    * \r
167    * @return count of activeclients \r
168    */  \r
169   public String update () {\r
170     logger.debug("Updating show,stat,termlist,bytarget from pazpar2");\r
171     if (errors.hasConfigurationErrors()) {\r
172       logger.error("Ignoring show,stat,termlist,bytarget commands due to configuration errors.");\r
173       return "";\r
174     } else if (pzresp.getSearch().hasApplicationError()) {\r
175       logger.error("Ignoring show,stat,termlist,bytarget commands due to problem with most recent search.");\r
176       return "";\r
177     } else if (!hasQuery()) {\r
178       logger.debug("Ignoring show,stat,termlist,bytarget commands because there is not yet a query.");\r
179       return "";\r
180     } else {\r
181       return update("show,stat,termlist,bytarget");\r
182     }\r
183   }\r
184      \r
185   /**\r
186    * Refreshes the data objects listed in 'commands' from pazpar2\r
187    * \r
188    * @param commands\r
189    * @return Number of activeclients at the time of the 'show' command,\r
190    *         or 'new' if search was just initiated.\r
191    */\r
192   public String update (String commands) {\r
193     logger.debug("Request to update: " + commands);\r
194     try {\r
195       if (commands.equals("search")) {\r
196         pzreq.getSearch().run();\r
197         pzresp.getSearch().setIsNew(false);\r
198         return "new";\r
199       } else if (commands.equals("record")) {\r
200         pzreq.getRecord().run();\r
201         return pzresp.getRecord().getActiveClients();\r
202       } else if (pzresp.getSearch().isNew()) {\r
203         // For returning notification of 'search started' quickly to UI\r
204         logger.info("New search. Marking it old, then returning 'new' to trigger another round-trip.");\r
205         pzresp.getSearch().setIsNew(false);\r
206         return "new";\r
207       } else {\r
208         handleQueryStateChanges(commands);\r
209         if (pzresp.getSearch().hasApplicationError()) {\r
210           logger.error("The command(s) " + commands + " cancelled because the latest search command had an error.");\r
211           return "0";\r
212         } else if (errors.hasConfigurationErrors()) {\r
213           logger.error("The command(s) " + commands + " cancelled due to configuration errors.");\r
214           return "0";\r
215         } else {\r
216           logger.debug("Processing request for " + commands); \r
217           List<CommandThread> threadList = new ArrayList<CommandThread>();\r
218           StringTokenizer tokens = new StringTokenizer(commands,",");\r
219           while (tokens.hasMoreElements()) {          \r
220             threadList.add(new CommandThread(pzreq.getCommand(tokens.nextToken()),searchClient,Pz2Service.get().getPzresp()));            \r
221           }\r
222           for (CommandThread thread : threadList) {\r
223             thread.start();\r
224           }\r
225           for (CommandThread thread : threadList) {\r
226             try {\r
227               thread.join();\r
228             } catch (InterruptedException e) {\r
229               e.printStackTrace();\r
230             }\r
231           }\r
232           return pzresp.getActiveClients();\r
233         }\r
234       }  \r
235     } catch (ClassCastException cce) {\r
236       cce.printStackTrace();    \r
237       return "";\r
238     } catch (NullPointerException npe) {\r
239       npe.printStackTrace();\r
240       return "";\r
241     } catch (Exception e) {\r
242       e.printStackTrace();\r
243       return "";\r
244     }\r
245     \r
246   }\r
247   \r
248   /**\r
249    * This methods main purpose is to support browser history.\r
250    *  \r
251    * When the browsers back or forward buttons are pressed, a  \r
252    * re-search /might/ be required - namely if the query changes.\r
253    * So, as the UI requests updates of the page (show,facets,\r
254    * etc) this method checks if a search must be executed\r
255    * before those updates are performed.\r
256    *  \r
257    * @see {@link com.indexdata.mkjsf.pazpar2.state.StateManager#setCurrentStateKey} \r
258    * @param commands\r
259    */\r
260   protected void handleQueryStateChanges (String commands) {\r
261     if (stateMgr.hasPendingStateChange("search") && hasQuery()) { \r
262       logger.info("Triggered search: Found pending search change [" + pzreq.getCommand("search").toString() + "], doing search before updating " + commands);      \r
263       pzreq.getSearch().run();\r
264       pzresp.getSearch().setIsNew(false);\r
265     } \r
266     if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {        \r
267       logger.debug("Found pending record ID change. Doing record before updating " + commands);\r
268       stateMgr.hasPendingStateChange("record",false);\r
269       pzreq.getRecord().run();\r
270     }\r
271   }\r
272       \r
273   @Override\r
274   public void stateUpdated(String commandName) {\r
275     logger.debug("State change reported for [" + commandName + "]");\r
276     if (commandName.equals("show")) {\r
277       logger.debug("Updating show");\r
278       update(commandName);\r
279     } \r
280   }\r
281 \r
282       \r
283   /**\r
284    * Will retrieve -- or alternatively remove -- the record with the given \r
285    * recid from memory.\r
286    * \r
287    * A pazpar2 'record' command will then be issued. The part of the UI \r
288    * showing record data should thus be re-rendered.\r
289    *  \r
290    * @param recid\r
291    * @return\r
292    */\r
293   public String toggleRecord (String recId) {\r
294     if (hasRecord(recId)) {\r
295       pzreq.getRecord().removeParameters();  \r
296       pzresp.put("record", new RecordResponse());\r
297       return "";\r
298     } else {\r
299       pzreq.getRecord().setId(recId);\r
300       pzreq.getRecord().run();\r
301       // doCommand("record");\r
302       return pzresp.getRecord().getActiveClients();\r
303     }\r
304   }\r
305   \r
306   /**\r
307    * Resolves whether the backend has a record with the given recid in memory \r
308    * \r
309    * @return true if the bean currently holds the record with recid\r
310    */  \r
311   public boolean hasRecord (String recId) {\r
312     return pzreq.getCommand("record").hasParameters() && pzresp.getRecord().getRecId().equals(recId);\r
313   }\r
314         \r
315   /**\r
316    * Returns the current hash key, used for internal session state tracking\r
317    * and potentially for browser history entries\r
318    * \r
319    * A UI author would not normally be concerned with retrieving this. It's used by the\r
320    * framework internally\r
321    *  \r
322    * @return string that can be used for browsers window.location.hash\r
323    */\r
324   public String getCurrentStateKey () {    \r
325     return stateMgr.getCurrentState().getKey();\r
326   }\r
327       \r
328   /**\r
329    * Sets the current state key, i.e. when user clicks back or forward in browser history.\r
330    * Would normally be automatically handled by the frameworks components.\r
331    *  \r
332    * @param key corresponding to browsers hash string\r
333    */\r
334   public void setCurrentStateKey(String key) {       \r
335     stateMgr.setCurrentStateKey(key);\r
336   }\r
337       \r
338   protected boolean hasQuery() {        \r
339     return pzreq.getCommand("search").hasParameterValue("query"); \r
340   }\r
341     \r
342   /**\r
343    * Returns a component for drawing a pager to navigate by.\r
344    * @return ResultsPager pager component\r
345    */\r
346   public ResultsPager getPager () {\r
347     if (pager == null) {\r
348       pager = new ResultsPager(pzresp);      \r
349     } \r
350     return pager;      \r
351   }\r
352   \r
353  /**\r
354   * Initiates a pager object, a component holding the data to draw a sequence\r
355   * of page numbers to navigate by and mechanisms to navigate with\r
356   * \r
357   * @param pageRange number of pages to display in the pager\r
358   * @return ResultsPager the initiated pager component\r
359   */\r
360   public ResultsPager setPager (int pageRange) {\r
361     pager =  new ResultsPager(pzresp,pageRange,pzreq);\r
362     return pager;\r
363   }\r
364      \r
365   public void setServiceProxyUrl(String url) {\r
366     searchClient = spClient;\r
367     setServiceType(SERVICE_TYPE_SP);\r
368     setServiceUrl(url);\r
369   }\r
370   \r
371   public String getServiceProxyUrl () {\r
372     if (isServiceProxyService()) {\r
373       return spClient.getServiceUrl();\r
374     } else {\r
375       return "";\r
376     }\r
377   }\r
378   \r
379   public void setPazpar2Url(String url) {\r
380     searchClient = pz2Client;\r
381     setServiceType(SERVICE_TYPE_PZ2);\r
382     setServiceUrl(url);\r
383   }\r
384   \r
385   public String getPazpar2Url() {\r
386     if (isPazpar2Service()) {\r
387       return pz2Client.getServiceUrl();\r
388     } else {\r
389       return "";\r
390     }\r
391   }\r
392 \r
393   public void setServiceUrl(String url) {\r
394     if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) {\r
395       pzreq.getRecord().removeParametersInState();\r
396       pzreq.getSearch().removeParametersInState();\r
397       pzresp.getSp().resetAuthAndBeyond(true);      \r
398       searchClient.setServiceUrl(url);\r
399     }    \r
400   }\r
401   \r
402   public String getServiceUrl() {\r
403     return (searchClient!=null ? searchClient.getServiceUrl() : "");\r
404   }\r
405   \r
406   public void setServiceId () {\r
407     pzreq.getRecord().removeParametersInState();\r
408     pzreq.getSearch().removeParametersInState();\r
409     pzresp.resetSearchAndBeyond();\r
410     pz2Client.setServiceId(pzreq.getInit().getService());\r
411   }\r
412   \r
413   public String getServiceId () {\r
414     return pzreq.getInit().getService();\r
415   }\r
416   \r
417   public boolean getServiceUrlIsDefined() {\r
418     return (searchClient != null && searchClient.hasServiceUrl());\r
419   }\r
420   \r
421   public List<String> getServiceProxyUrls() {\r
422     List<String> urls = new ArrayList<String>();\r
423     urls.add("");\r
424     urls.addAll(serviceProxyUrls);\r
425     return urls;\r
426   }\r
427   \r
428   public List<String> getPazpar2Urls () {\r
429     List<String> urls = new ArrayList<String>();\r
430     urls.add("");\r
431     urls.addAll(pazpar2Urls);\r
432     return urls;\r
433   }\r
434   \r
435   public String getServiceType () {\r
436     return serviceType;\r
437   }\r
438   \r
439   public boolean isPazpar2Service () {\r
440     return serviceType.equals(SERVICE_TYPE_PZ2);\r
441   }\r
442   \r
443   public boolean isServiceProxyService() {\r
444     return serviceType.equals(SERVICE_TYPE_SP);\r
445   }\r
446   \r
447   public boolean serviceIsToBeDecided () {\r
448     return serviceType.equals(SERVICE_TYPE_TBD);\r
449   }\r
450   \r
451   public ServiceProxyClient getSpClient () {\r
452     return spClient;\r
453   }  \r
454   \r
455   public boolean getAuthenticationRequired () {\r
456     return spClient.isAuthenticatingClient();\r
457   }\r
458 \r
459   public String getCheckHistory () {\r
460     return ":pz2watch:stateForm:windowlocationhash";\r
461   }\r
462     \r
463   public String getWatchActiveclients () {\r
464     return ":pz2watch:activeclientsForm:activeclientsField";\r
465   }\r
466   \r
467   public String getWatchActiveclientsRecord () {\r
468     return ":pz2watch:activeclientsForm:activeclientsFieldRecord";\r
469   }\r
470 \r
471   @Override\r
472   public void configure(ConfigurationReader reader)\r
473       throws ConfigurationException {\r
474     Configuration config = reader.getConfiguration(this);\r
475     if (config == null) {\r
476       serviceType = SERVICE_TYPE_TBD;\r
477     } else {\r
478       String service = config.get("TYPE");\r
479       if (service == null || service.length()==0) {\r
480         serviceType = SERVICE_TYPE_TBD;\r
481       } else if (serviceTypes.contains(service.toUpperCase())) {        \r
482         setServiceType(service.toUpperCase());\r
483       } else {\r
484         logger.error("Unknown serviceType type in configuration [" + service + "], can be one of " + serviceTypes);\r
485         serviceType = SERVICE_TYPE_TBD;\r
486       }\r
487       serviceProxyUrls = config.getMultiProperty(SERVICE_PROXY_URL_LIST,",");\r
488       pazpar2Urls = config.getMultiProperty(PAZPAR2_URL_LIST, ",");\r
489     }\r
490     logger.info(reader.document());\r
491     logger.info("Service Type is configured to " + serviceType);\r
492     \r
493   }\r
494 \r
495   @Override\r
496   public Map<String, String> getDefaults() {\r
497     return new HashMap<String,String>();\r
498   }\r
499 \r
500   @Override\r
501   public String getModuleName() {\r
502     return MODULE_NAME;\r
503   }\r
504 \r
505   @Override\r
506   public List<String> documentConfiguration() {\r
507     return new ArrayList<String>();\r
508   }\r
509 \r
510   public void setServiceTypePZ2() {\r
511     setServiceType(SERVICE_TYPE_PZ2);    \r
512   }\r
513 \r
514   public void setServiceTypeSP() {\r
515     setServiceType(SERVICE_TYPE_SP);        \r
516   }\r
517 \r
518   public void setServiceTypeTBD() {\r
519     setServiceType(SERVICE_TYPE_TBD);    \r
520   }\r
521   \r
522   private void setServiceType(String type) {\r
523     if (!serviceType.equals(type)  &&\r
524         !serviceType.equals(SERVICE_TYPE_TBD)) {\r
525       resetSearchAndRecordCommands();\r
526       pzresp.getSp().resetAuthAndBeyond(true);\r
527     }\r
528     serviceType = type;\r
529     if (serviceType.equals(SERVICE_TYPE_PZ2)) {\r
530       searchClient = pz2Client;\r
531       logger.info("Setting a Pazpar2 client to serve requests.");\r
532     } else if (serviceType.equals(SERVICE_TYPE_SP)) {\r
533       searchClient = spClient;\r
534       logger.info("Setting a Service Proxy client to serve requests.");\r
535     } else {\r
536       logger.info("Clearing search client. No client defined to serve requests at this point.");\r
537       searchClient = null;\r
538     }\r
539   }\r
540   \r
541   public SearchClient getSearchClient() {\r
542     return searchClient;\r
543   }\r
544   \r
545 }\r