44cb05bfdaf398e1267384a86f2bf82b585ccc63
[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         return "new";\r
198       } else if (commands.equals("record")) {\r
199         pzreq.getRecord().run();\r
200         return pzresp.getRecord().getActiveClients();\r
201       } else if (pzresp.getSearch().isNew()) {\r
202         // For returning notification of 'search started' quickly to UI\r
203         logger.info("New search. Marking it old, then returning 'new' to trigger another round-trip.");\r
204         pzresp.getSearch().setIsNew(false);\r
205         return "new";\r
206       } else {\r
207         handleQueryStateChanges(commands);\r
208         if (pzresp.getSearch().hasApplicationError()) {\r
209           logger.error("The command(s) " + commands + " cancelled because the latest search command had an error.");\r
210           return "0";\r
211         } else if (errors.hasConfigurationErrors()) {\r
212           logger.error("The command(s) " + commands + " cancelled due to configuration errors.");\r
213           return "0";\r
214         } else {\r
215           logger.debug("Processing request for " + commands); \r
216           List<CommandThread> threadList = new ArrayList<CommandThread>();\r
217           StringTokenizer tokens = new StringTokenizer(commands,",");\r
218           while (tokens.hasMoreElements()) {          \r
219             threadList.add(new CommandThread(pzreq.getCommand(tokens.nextToken()),searchClient,Pz2Service.get().getPzresp()));            \r
220           }\r
221           for (CommandThread thread : threadList) {\r
222             thread.start();\r
223           }\r
224           for (CommandThread thread : threadList) {\r
225             try {\r
226               thread.join();\r
227             } catch (InterruptedException e) {\r
228               e.printStackTrace();\r
229             }\r
230           }\r
231           return pzresp.getActiveClients();\r
232         }\r
233       }  \r
234     } catch (ClassCastException cce) {\r
235       cce.printStackTrace();    \r
236       return "";\r
237     } catch (NullPointerException npe) {\r
238       npe.printStackTrace();\r
239       return "";\r
240     } catch (Exception e) {\r
241       e.printStackTrace();\r
242       return "";\r
243     }\r
244     \r
245   }\r
246   \r
247   /**\r
248    * This methods main purpose is to support browser history.\r
249    *  \r
250    * When the browsers back or forward buttons are pressed, a  \r
251    * re-search /might/ be required - namely if the query changes.\r
252    * So, as the UI requests updates of the page (show,facets,\r
253    * etc) this method checks if a search must be executed\r
254    * before those updates are performed.\r
255    *  \r
256    * @see {@link com.indexdata.mkjsf.pazpar2.state.StateManager#setCurrentStateKey} \r
257    * @param commands\r
258    */\r
259   protected void handleQueryStateChanges (String commands) {\r
260     if (stateMgr.hasPendingStateChange("search") && hasQuery()) { \r
261       logger.info("Triggered search: Found pending search change [" + pzreq.getCommand("search").toString() + "], doing search before updating " + commands);      \r
262       pzreq.getSearch().run();\r
263     } \r
264     if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {        \r
265       logger.debug("Found pending record ID change. Doing record before updating " + commands);\r
266       stateMgr.hasPendingStateChange("record",false);\r
267       pzreq.getRecord().run();\r
268     }\r
269   }\r
270       \r
271   @Override\r
272   public void stateUpdated(String commandName) {\r
273     logger.debug("State change reported for [" + commandName + "]");\r
274     if (commandName.equals("show")) {\r
275       logger.debug("Updating show");\r
276       update(commandName);\r
277     } \r
278   }\r
279 \r
280       \r
281   /**\r
282    * Will retrieve -- or alternatively remove -- the record with the given \r
283    * recid from memory.\r
284    * \r
285    * A pazpar2 'record' command will then be issued. The part of the UI \r
286    * showing record data should thus be re-rendered.\r
287    *  \r
288    * @param recid\r
289    * @return\r
290    */\r
291   public String toggleRecord (String recId) {\r
292     if (hasRecord(recId)) {\r
293       pzreq.getRecord().removeParameters();  \r
294       pzresp.put("record", new RecordResponse());\r
295       return "";\r
296     } else {\r
297       pzreq.getRecord().setId(recId);\r
298       pzreq.getRecord().run();\r
299       // doCommand("record");\r
300       return pzresp.getRecord().getActiveClients();\r
301     }\r
302   }\r
303   \r
304   /**\r
305    * Resolves whether the backend has a record with the given recid in memory \r
306    * \r
307    * @return true if the bean currently holds the record with recid\r
308    */  \r
309   public boolean hasRecord (String recId) {\r
310     return pzreq.getCommand("record").hasParameters() && pzresp.getRecord().getRecId().equals(recId);\r
311   }\r
312         \r
313   /**\r
314    * Returns the current hash key, used for internal session state tracking\r
315    * and potentially for browser history entries\r
316    * \r
317    * A UI author would not normally be concerned with retrieving this. It's used by the\r
318    * framework internally\r
319    *  \r
320    * @return string that can be used for browsers window.location.hash\r
321    */\r
322   public String getCurrentStateKey () {    \r
323     return stateMgr.getCurrentState().getKey();\r
324   }\r
325       \r
326   /**\r
327    * Sets the current state key, i.e. when user clicks back or forward in browser history.\r
328    * Would normally be automatically handled by the frameworks components.\r
329    *  \r
330    * @param key corresponding to browsers hash string\r
331    */\r
332   public void setCurrentStateKey(String key) {       \r
333     stateMgr.setCurrentStateKey(key);\r
334   }\r
335       \r
336   protected boolean hasQuery() {        \r
337     return pzreq.getCommand("search").hasParameterValue("query"); \r
338   }\r
339     \r
340   /**\r
341    * Returns a component for drawing a pager to navigate by.\r
342    * @return ResultsPager pager component\r
343    */\r
344   public ResultsPager getPager () {\r
345     if (pager == null) {\r
346       pager = new ResultsPager(pzresp);      \r
347     } \r
348     return pager;      \r
349   }\r
350   \r
351  /**\r
352   * Initiates a pager object, a component holding the data to draw a sequence\r
353   * of page numbers to navigate by and mechanisms to navigate with\r
354   * \r
355   * @param pageRange number of pages to display in the pager\r
356   * @return ResultsPager the initiated pager component\r
357   */\r
358   public ResultsPager setPager (int pageRange) {\r
359     pager =  new ResultsPager(pzresp,pageRange,pzreq);\r
360     return pager;\r
361   }\r
362      \r
363   public void setServiceProxyUrl(String url) {\r
364     searchClient = spClient;\r
365     setServiceType(SERVICE_TYPE_SP);\r
366     setServiceUrl(url);\r
367   }\r
368   \r
369   public String getServiceProxyUrl () {\r
370     if (isServiceProxyService()) {\r
371       return spClient.getServiceUrl();\r
372     } else {\r
373       return "";\r
374     }\r
375   }\r
376   \r
377   public void setPazpar2Url(String url) {\r
378     searchClient = pz2Client;\r
379     setServiceType(SERVICE_TYPE_PZ2);\r
380     setServiceUrl(url);\r
381   }\r
382   \r
383   public String getPazpar2Url() {\r
384     if (isPazpar2Service()) {\r
385       return pz2Client.getServiceUrl();\r
386     } else {\r
387       return "";\r
388     }\r
389   }\r
390 \r
391   public void setServiceUrl(String url) {\r
392     if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) {\r
393       pzreq.getRecord().removeParametersInState();\r
394       pzreq.getSearch().removeParametersInState();\r
395       pzresp.getSp().resetAuthAndBeyond(true);      \r
396       searchClient.setServiceUrl(url);\r
397     }    \r
398   }\r
399   \r
400   public String getServiceUrl() {\r
401     return (searchClient!=null ? searchClient.getServiceUrl() : "");\r
402   }\r
403   \r
404   public void setServiceId () {\r
405     pzreq.getRecord().removeParametersInState();\r
406     pzreq.getSearch().removeParametersInState();\r
407     pzresp.resetSearchAndBeyond();\r
408     pz2Client.setServiceId(pzreq.getInit().getService());\r
409   }\r
410   \r
411   public String getServiceId () {\r
412     return pzreq.getInit().getService();\r
413   }\r
414   \r
415   public boolean getServiceUrlIsDefined() {\r
416     return (searchClient != null && searchClient.hasServiceUrl());\r
417   }\r
418   \r
419   public List<String> getServiceProxyUrls() {\r
420     List<String> urls = new ArrayList<String>();\r
421     urls.add("");\r
422     urls.addAll(serviceProxyUrls);\r
423     return urls;\r
424   }\r
425   \r
426   public List<String> getPazpar2Urls () {\r
427     List<String> urls = new ArrayList<String>();\r
428     urls.add("");\r
429     urls.addAll(pazpar2Urls);\r
430     return urls;\r
431   }\r
432   \r
433   public String getServiceType () {\r
434     return serviceType;\r
435   }\r
436   \r
437   public boolean isPazpar2Service () {\r
438     return serviceType.equals(SERVICE_TYPE_PZ2);\r
439   }\r
440   \r
441   public boolean isServiceProxyService() {\r
442     return serviceType.equals(SERVICE_TYPE_SP);\r
443   }\r
444   \r
445   public boolean serviceIsToBeDecided () {\r
446     return serviceType.equals(SERVICE_TYPE_TBD);\r
447   }\r
448   \r
449   public ServiceProxyClient getSpClient () {\r
450     return spClient;\r
451   }  \r
452   \r
453   public boolean getAuthenticationRequired () {\r
454     return spClient.isAuthenticatingClient();\r
455   }\r
456 \r
457   public String getCheckHistory () {\r
458     return ":pz2watch:stateForm:windowlocationhash";\r
459   }\r
460     \r
461   public String getWatchActiveclients () {\r
462     return ":pz2watch:activeclientsForm:activeclientsField";\r
463   }\r
464   \r
465   public String getWatchActiveclientsRecord () {\r
466     return ":pz2watch:activeclientsForm:activeclientsFieldRecord";\r
467   }\r
468 \r
469   @Override\r
470   public void configure(ConfigurationReader reader)\r
471       throws ConfigurationException {\r
472     Configuration config = reader.getConfiguration(this);\r
473     if (config == null) {\r
474       serviceType = SERVICE_TYPE_TBD;\r
475     } else {\r
476       String service = config.get("TYPE");\r
477       if (service == null || service.length()==0) {\r
478         serviceType = SERVICE_TYPE_TBD;\r
479       } else if (serviceTypes.contains(service.toUpperCase())) {        \r
480         setServiceType(service.toUpperCase());\r
481       } else {\r
482         logger.error("Unknown serviceType type in configuration [" + service + "], can be one of " + serviceTypes);\r
483         serviceType = SERVICE_TYPE_TBD;\r
484       }\r
485       serviceProxyUrls = config.getMultiProperty(SERVICE_PROXY_URL_LIST,",");\r
486       pazpar2Urls = config.getMultiProperty(PAZPAR2_URL_LIST, ",");\r
487     }\r
488     logger.info(reader.document());\r
489     logger.info("Service Type is configured to " + serviceType);\r
490     \r
491   }\r
492 \r
493   @Override\r
494   public Map<String, String> getDefaults() {\r
495     return new HashMap<String,String>();\r
496   }\r
497 \r
498   @Override\r
499   public String getModuleName() {\r
500     return MODULE_NAME;\r
501   }\r
502 \r
503   @Override\r
504   public List<String> documentConfiguration() {\r
505     return new ArrayList<String>();\r
506   }\r
507 \r
508   public void setServiceTypePZ2() {\r
509     setServiceType(SERVICE_TYPE_PZ2);    \r
510   }\r
511 \r
512   public void setServiceTypeSP() {\r
513     setServiceType(SERVICE_TYPE_SP);        \r
514   }\r
515 \r
516   public void setServiceTypeTBD() {\r
517     setServiceType(SERVICE_TYPE_TBD);    \r
518   }\r
519   \r
520   private void setServiceType(String type) {\r
521     if (!serviceType.equals(type)  &&\r
522         !serviceType.equals(SERVICE_TYPE_TBD)) {\r
523       resetSearchAndRecordCommands();\r
524       pzresp.getSp().resetAuthAndBeyond(true);\r
525     }\r
526     serviceType = type;\r
527     if (serviceType.equals(SERVICE_TYPE_PZ2)) {\r
528       searchClient = pz2Client;\r
529       logger.info("Setting a Pazpar2 client to serve requests.");\r
530     } else if (serviceType.equals(SERVICE_TYPE_SP)) {\r
531       searchClient = spClient;\r
532       logger.info("Setting a Service Proxy client to serve requests.");\r
533     } else {\r
534       logger.info("Clearing search client. No client defined to serve requests at this point.");\r
535       searchClient = null;\r
536     }\r
537   }\r
538   \r
539   public SearchClient getSearchClient() {\r
540     return searchClient;\r
541   }\r
542   \r
543 }\r