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