Javadoc
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / mkjsf / pazpar2 / Pz2Service.java
index f38d90d..fea4a44 100644 (file)
@@ -28,17 +28,31 @@ import com.indexdata.mkjsf.errors.ConfigurationError;
 import com.indexdata.mkjsf.errors.ConfigurationException;\r
 import com.indexdata.mkjsf.errors.ErrorCentral;\r
 import com.indexdata.mkjsf.errors.ErrorHelper;\r
-import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;\r
+import com.indexdata.mkjsf.errors.MissingConfigurationContextException;\r
 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Commands;\r
 import com.indexdata.mkjsf.pazpar2.data.RecordResponse;\r
-import com.indexdata.mkjsf.pazpar2.data.ResponseDataObject;\r
 import com.indexdata.mkjsf.pazpar2.data.Responses;\r
 import com.indexdata.mkjsf.pazpar2.state.StateListener;\r
 import com.indexdata.mkjsf.pazpar2.state.StateManager;\r
 import com.indexdata.mkjsf.utils.Utils;\r
 \r
+/**  \r
+ * Pz2Service is the main controller of the search logic, used for selecting the service \r
+ * type (which can be done by configuration and/or run-time), selecting which search client \r
+ * to use, and performing high-level control of request cycles and state management. \r
+ * <p>\r
+ * Command and response beans are also obtained through Pz2Service - although it is \r
+ * transparent to the UI that they are retrieved through this object.\r
+ * </p>\r
+ * <p>\r
+ * Pz2Service is exposed to the UI as 'pz2'. However, if the service is pre-configured, \r
+ * the Faces pages might never need to reference 'pz2' explicitly. Indirectly they UI will, \r
+ * though, if the polling mechanism in the tag &lt;pz2utils:pz2watch&gt; is used.\r
+ * \r
+ * \r
+ **/ \r
 @Named("pz2") @SessionScoped\r
-public class Pz2Service implements Pz2Interface, StateListener, Configurable, Serializable {\r
+public class Pz2Service implements StateListener, Configurable, Serializable {\r
 \r
   private static final String MODULE_NAME = "service";\r
   private static String SERVICE_TYPE_TBD = "TBD", SERVICE_TYPE_PZ2 = "PZ2", SERVICE_TYPE_SP = "SP";\r
@@ -50,9 +64,8 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
   private List<String> pazpar2Urls = new ArrayList<String>();\r
   public static final String PAZPAR2_URL_LIST = "PAZPAR2_URL_LIST";\r
 \r
-\r
   private static final long serialVersionUID = 3440277287081557861L;\r
-  private static Logger logger = Logger.getLogger(Pz2Service.class);     \r
+  private static Logger logger = Logger.getLogger(Pz2Service.class);  \r
   protected Pz2Client pz2Client = null;\r
   protected ServiceProxyClient spClient = null;\r
   protected SearchClient searchClient = null;  \r
@@ -76,9 +89,9 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     FacesContext context = FacesContext.getCurrentInstance();\r
     return (Pz2Service) context.getApplication().evaluateExpressionGet(context, "#{pz2}", Object.class); \r
   }\r
-  \r
+    \r
   @PostConstruct\r
-  public void postConstruct() {\r
+  public void postConstruct() throws MissingConfigurationContextException {    \r
     logger.info("Pz2Service PostConstruct of " + this);\r
     stateMgr = new StateManager();\r
     pzreq = new Pazpar2Commands();\r
@@ -87,18 +100,22 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     pzresp.setErrorHelper(errors.getHelper());\r
     \r
     logger.debug("Pz2Service PostConstruct: Configurator is " + configurator);\r
-    logger.debug(Utils.objectId(this) + " will instantiate a Pz2Client next.");\r
+    logger.debug(Utils.objectId(this) + " will instantiate a Pz2Client next.");    \r
     pz2Client = new Pz2Client();\r
-    configureClient(pz2Client,configurator);\r
     spClient = new ServiceProxyClient();\r
-    configureClient(spClient,configurator);\r
+    stateMgr.addStateListener(this);\r
     try {\r
+      configureClient(pz2Client,configurator);      \r
+      configureClient(spClient,configurator);\r
       this.configure(configurator);\r
+    } catch (MissingConfigurationContextException mcc) {\r
+      logger.info("No configuration context available at this point");\r
+      logger.debug("Configuration invoked from a Servlet filter before application start?");\r
+      throw mcc;\r
     } catch (ConfigurationException e) {\r
-      logger.error("There was a problem configuring the Pz2Service (\"pz2\")");\r
+      logger.warn("There was a problem configuring the Pz2Service and/or clients (\"pz2\")");\r
       e.printStackTrace();\r
-    }    \r
-    stateMgr.addStateListener(this);    \r
+    }     \r
   }\r
   \r
   @Qualifier\r
@@ -129,14 +146,27 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     return stateMgr;\r
   }\r
   \r
-  public void configureClient(SearchClient client, ConfigurationReader configReader) {\r
+  /**\r
+   * Configures the selected search client using the selected configuration reader.\r
+   * \r
+   * The configuration reader is select deploy-time - by configuration in the application's beans.xml.\r
+   * \r
+   * @param client search client to use\r
+   * @param configReader the selected configuration mechanism\r
+   * @throws MissingConfigurationContextException if this object is injected before there is a Faces context\r
+   * for example in a Servlet filter.\r
+   */\r
+  public void configureClient(SearchClient client, ConfigurationReader configReader)  throws MissingConfigurationContextException {\r
     logger.debug(Utils.objectId(this) + " will configure search client for the session");\r
     try {\r
-      client.configure(configReader);            \r
+      client.configure(configReader);\r
+    } catch (MissingConfigurationContextException mcce) {\r
+      logger.info("No Faces context is available to the configurator at this time of invocation");\r
+      throw mcce;\r
     } catch (ConfigurationException e) {\r
       logger.debug("Pz2Service adding configuration error");\r
       errors.addConfigurationError(new ConfigurationError("Search Client","Configuration",e.getMessage()));                \r
-    } \r
+    }\r
     logger.info(configReader.document());\r
     pzresp.getSp().resetAuthAndBeyond(true);    \r
   }\r
@@ -145,12 +175,43 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     pzreq.getRecord().removeParametersInState();\r
     pzreq.getSearch().removeParametersInState();   \r
   }\r
-      \r
+     \r
+  \r
   /**\r
-   * Refreshes 'show', 'stat', 'termlist', and 'bytarget' data object from pazpar2\r
+   * Updates display data objects by simultaneously issuing the following Pazpar2 commands: \r
+   * 'show', 'stat', 'termlist' and 'bytarget'. \r
+   * <p>\r
+   * If there are outstanding changes to the search command, a search\r
+   * will be issued before the updates are performed. Outstanding changes could come \r
+   * from the UI changing a search parameter and not executing search before starting \r
+   * the update cycle - OR - it could come from the user clicking the browsers back/forward\r
+   * buttons. \r
+   * </p>\r
+   * <p>\r
+   * This method is invoked from the composite 'pz2watch', which uses Ajax\r
+   * to keep invoking this method until it returns '0' (for zero active clients).\r
+   * </p>\r
+   * <p>\r
+   * UI components that display data from show, stat, termlist or bytarget, \r
+   * should be re-rendered after each update. \r
+   * </p>\r
+   * Example of invocation in UI:\r
+   * <pre>\r
+   *    &lt;pz2utils:pz2watch id="pz2watch"\r
+   *       renderWhileActiveclients="myshowui mystatui mytermsui" /&lt; \r
+   *       \r
+   *    &lt;h:form&gt;\r
+   *     &lt;h:inputText id="query" value="#{pzreq.search.query}" size="50"/&gt;                            \r
+   *      &lt;h:commandButton id="button" value="Search"&gt;              \r
+   *       &lt;f:ajax execute="query" render="${pz2.watchActiveclients}"/&gt;\r
+   *      &lt;/h:commandButton&gt;\r
+   *     &lt;/h:form&gt;\r
+   * </pre>\r
+   * The expression pz2.watchActiveClients will invoke the method repeatedly, and the\r
+   * UI sections myshowui, mystatui, and mytermsui will be rendered on each poll. \r
    * \r
-   * @return Number of activeclients at the time of the 'show' command.\r
-   */\r
+   * @return a count of the remaining active clients from the most recent search. \r
+   */  \r
   public String update () {\r
     logger.debug("Updating show,stat,termlist,bytarget from pazpar2");\r
     if (errors.hasConfigurationErrors()) {\r
@@ -168,9 +229,11 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
   }\r
      \r
   /**\r
-   * Refreshes the data objects listed in 'commands' from pazpar2\r
+   * Simultaneously refreshes the data objects listed in 'commands' from pazpar2, potentially running a\r
+   * search or a record command first if any of these two commands have outstanding parameter changes.\r
+   * \r
+   * @param commands, a comma-separated list of Pazpar2 commands to execute\r
    * \r
-   * @param commands\r
    * @return Number of activeclients at the time of the 'show' command,\r
    *         or 'new' if search was just initiated.\r
    */\r
@@ -179,6 +242,7 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     try {\r
       if (commands.equals("search")) {\r
         pzreq.getSearch().run();\r
+        pzresp.getSearch().setIsNew(false);\r
         return "new";\r
       } else if (commands.equals("record")) {\r
         pzreq.getRecord().run();\r
@@ -228,7 +292,56 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     }\r
     \r
   }\r
-                                  \r
+  \r
+  /**\r
+   * This methods main purpose is to support browser history.\r
+   *  \r
+   * When the browsers back or forward buttons are pressed, a  \r
+   * re-search /might/ be required - namely if the query changes.\r
+   * So, as the UI requests updates of the page (show,facets,\r
+   * etc) this method checks if a search must be executed\r
+   * before those updates are performed.\r
+   *  \r
+   * It will consequently also run a search if the UI updates a\r
+   * search parameter without actually explicitly executing the search \r
+   * before setting of the polling.\r
+   *  \r
+   * @see {@link com.indexdata.mkjsf.pazpar2.state.StateManager#setCurrentStateKey} \r
+   * @param commands\r
+   */\r
+  protected void handleQueryStateChanges (String commands) {\r
+    if (stateMgr.hasPendingStateChange("search") && hasQuery()) { \r
+      logger.info("Triggered search: Found pending search change [" + pzreq.getCommand("search").toString() + "], doing search before updating " + commands);      \r
+      pzreq.getSearch().run();\r
+      pzresp.getSearch().setIsNew(false);\r
+    } \r
+    if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {        \r
+      logger.debug("Found pending record ID change. Doing record before updating " + commands);\r
+      stateMgr.hasPendingStateChange("record",false);\r
+      pzreq.getRecord().run();\r
+    }\r
+  }\r
+      \r
+  @Override\r
+  public void stateUpdated(String commandName) {\r
+    logger.debug("State change reported for [" + commandName + "]");\r
+    if (commandName.equals("show")) {\r
+      logger.debug("Updating show");\r
+      update(commandName);\r
+    } \r
+  }\r
+\r
+      \r
+  /**\r
+   * Will retrieve -- or alternatively remove -- the record with the given \r
+   * recid from memory.\r
+   * \r
+   * A pazpar2 'record' command will then be issued. The part of the UI \r
+   * showing record data should thus be re-rendered.\r
+   *  \r
+   * @param recid\r
+   * @return\r
+   */\r
   public String toggleRecord (String recId) {\r
     if (hasRecord(recId)) {\r
       pzreq.getRecord().removeParameters();  \r
@@ -236,20 +349,39 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
       return "";\r
     } else {\r
       pzreq.getRecord().setId(recId);\r
-      doCommand("record");\r
+      pzreq.getRecord().run();\r
       return pzresp.getRecord().getActiveClients();\r
     }\r
   }\r
   \r
-  @Override\r
+  /**\r
+   * Resolves whether the back-end has a record with the given recid in memory \r
+   * \r
+   * @return true if the bean currently holds the record with recid\r
+   */  \r
   public boolean hasRecord (String recId) {\r
     return pzreq.getCommand("record").hasParameters() && pzresp.getRecord().getRecId().equals(recId);\r
   }\r
         \r
+  /**\r
+   * Returns the current hash key, used for internal session state tracking\r
+   * and potentially for browser history entries\r
+   * \r
+   * A UI author would not normally be concerned with retrieving this. It's used by the\r
+   * framework internally\r
+   *  \r
+   * @return string that can be used for browsers window.location.hash\r
+   */\r
   public String getCurrentStateKey () {    \r
     return stateMgr.getCurrentState().getKey();\r
   }\r
       \r
+  /**\r
+   * Sets the current state key, i.e. when user clicks back or forward in browser history.\r
+   * Would normally be automatically handled by the frameworks components.\r
+   *  \r
+   * @param key corresponding to browsers hash string\r
+   */\r
   public void setCurrentStateKey(String key) {       \r
     stateMgr.setCurrentStateKey(key);\r
   }\r
@@ -258,8 +390,10 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     return pzreq.getCommand("search").hasParameterValue("query"); \r
   }\r
     \r
-    \r
-  @Override\r
+  /**\r
+   * Returns a component for drawing a pager to navigate by.\r
+   * @return ResultsPager pager component\r
+   */\r
   public ResultsPager getPager () {\r
     if (pager == null) {\r
       pager = new ResultsPager(pzresp);      \r
@@ -267,67 +401,18 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     return pager;      \r
   }\r
   \r
-  @Override\r
+ /**\r
+  * Initiates a pager object, a component holding the data to draw a sequence\r
+  * of page numbers to navigate by and mechanisms to navigate with\r
+  * \r
+  * @param pageRange number of pages to display in the pager\r
+  * @return ResultsPager the initiated pager component\r
+  */\r
   public ResultsPager setPager (int pageRange) {\r
     pager =  new ResultsPager(pzresp,pageRange,pzreq);\r
     return pager;\r
   }\r
-   \r
-  /**\r
-   * This methods main purpose is to support browser history.\r
-   *  \r
-   * When the browsers back or forward buttons are pressed, a  \r
-   * re-search /might/ be required - namely if the query changes.\r
-   * So, as the UI requests updates of the page (show,facets,\r
-   * etc) this method checks if a search must be executed\r
-   * before those updates are performed.\r
-   *  \r
-   * @see {@link com.indexdata.mkjsf.pazpar2.state.StateManager#setCurrentStateKey} \r
-   * @param commands\r
-   */\r
-  protected void handleQueryStateChanges (String commands) {\r
-    if (stateMgr.hasPendingStateChange("search") && hasQuery()) { \r
-      logger.info("Triggered search: Found pending search change [" + pzreq.getCommand("search").toString() + "], doing search before updating " + commands);      \r
-      pzreq.getSearch().run();\r
-    } \r
-    if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {        \r
-      logger.debug("Found pending record ID change. Doing record before updating " + commands);\r
-      stateMgr.hasPendingStateChange("record",false);\r
-      pzreq.getRecord().run();\r
-    }\r
-  }\r
-  \r
-  /**\r
-   * Executes the command and parses the response to create data objects.\r
-   * If the parsed response is of a known type it will be cached in 'pzresp'\r
-   * \r
-   * @param commandName The command to be executed\r
-   * @return An XML response parsed to form a response data object\r
-   */\r
-  protected ResponseDataObject doCommand(String commandName) {\r
-    Pazpar2Command command = pzreq.getCommand(commandName);\r
-    if (command.spOnly() && isPazpar2Service()) {\r
-      logger.warn("Skipping " + commandName + " - SP-only command, not supported by Pazpar2");\r
-      return new ResponseDataObject();\r
-    } else {\r
-      logger.info("Request "+commandName + ". Search command is: "+ pzreq.getCommand("search").toString());      \r
-      long start = System.currentTimeMillis();\r
-      ResponseDataObject responseObject = command.run();      \r
-      long end = System.currentTimeMillis();\r
-      logger.debug("Executed " + command.getCommandName() + " in " + (end-start) + " ms." );\r
-      return responseObject;\r
-    }\r
-  }\r
-    \r
-  @Override\r
-  public void stateUpdated(String commandName) {\r
-    logger.debug("State change reported for [" + commandName + "]");\r
-    if (commandName.equals("show")) {\r
-      logger.debug("Updating show");\r
-      update(commandName);\r
-    } \r
-  }\r
-  \r
+     \r
   public void setServiceProxyUrl(String url) {\r
     searchClient = spClient;\r
     setServiceType(SERVICE_TYPE_SP);\r
@@ -356,8 +441,6 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     }\r
   }\r
 \r
-  \r
-  @Override\r
   public void setServiceUrl(String url) {\r
     if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) {\r
       pzreq.getRecord().removeParametersInState();\r
@@ -420,22 +503,18 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     return spClient;\r
   }  \r
   \r
-  @Override\r
   public boolean getAuthenticationRequired () {\r
     return spClient.isAuthenticatingClient();\r
   }\r
 \r
-  @Override\r
   public String getCheckHistory () {\r
     return ":pz2watch:stateForm:windowlocationhash";\r
   }\r
     \r
-  @Override\r
   public String getWatchActiveclients () {\r
     return ":pz2watch:activeclientsForm:activeclientsField";\r
   }\r
   \r
-  @Override\r
   public String getWatchActiveclientsRecord () {\r
     return ":pz2watch:activeclientsForm:activeclientsFieldRecord";\r
   }\r
@@ -479,17 +558,14 @@ public class Pz2Service implements Pz2Interface, StateListener, Configurable, Se
     return new ArrayList<String>();\r
   }\r
 \r
-  @Override\r
   public void setServiceTypePZ2() {\r
     setServiceType(SERVICE_TYPE_PZ2);    \r
   }\r
 \r
-  @Override\r
   public void setServiceTypeSP() {\r
     setServiceType(SERVICE_TYPE_SP);        \r
   }\r
 \r
-  @Override\r
   public void setServiceTypeTBD() {\r
     setServiceType(SERVICE_TYPE_TBD);    \r
   }\r