Merge branch 'master' of ssh://git.indexdata.com/home/git/private/mkjsf.git into...
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / mkjsf / pazpar2 / Pz2Service.java
diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Service.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Service.java
new file mode 100644 (file)
index 0000000..4d6d05f
--- /dev/null
@@ -0,0 +1,627 @@
+package com.indexdata.mkjsf.pazpar2;\r
+\r
+import java.io.Serializable;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.Target;\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.StringTokenizer;\r
+\r
+import javax.annotation.PostConstruct;\r
+import javax.enterprise.context.SessionScoped;\r
+import javax.enterprise.inject.Produces;\r
+import javax.faces.context.FacesContext;\r
+import javax.inject.Inject;\r
+import javax.inject.Named;\r
+import javax.inject.Qualifier;\r
+\r
+import org.apache.log4j.Logger;\r
+\r
+import com.indexdata.mkjsf.config.Configurable;\r
+import com.indexdata.mkjsf.config.Configuration;\r
+import com.indexdata.mkjsf.config.ConfigurationReader;\r
+import com.indexdata.mkjsf.controls.ResultsPager;\r
+import com.indexdata.mkjsf.errors.ConfigurationError;\r
+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.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.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 <code>pz2</code>. However, if the service is pre-configured, \r
+ * the Faces pages might never need to reference <code>pz2</code> explicitly. Indirectly they will, \r
+ * though, if the polling mechanism in the tag <code>&lt;pz2utils:pz2watch&gt;</code> is used.\r
+ * \r
+ * \r
+ **/ \r
+@Named("pz2") @SessionScoped\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
+  private static final List<String> serviceTypes = \r
+                Arrays.asList(SERVICE_TYPE_PZ2,SERVICE_TYPE_SP,SERVICE_TYPE_TBD);\r
+  private String serviceType = SERVICE_TYPE_TBD;\r
+  private List<String> serviceProxyUrls = new ArrayList<String>();\r
+  public static final String SERVICE_PROXY_URL_LIST = "SERVICE_PROXY_URL_LIST";\r
+  private List<String> pazpar2Urls = new ArrayList<String>();\r
+  public static final String PAZPAR2_URL_LIST = "PAZPAR2_URL_LIST";\r
+\r
+  private static final long serialVersionUID = 3440277287081557861L;\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
+    \r
+  @Inject ConfigurationReader configurator;\r
+  \r
+  private StateManager stateMgr = null;\r
+  private Pazpar2Commands pzreq = null;\r
+  private Responses pzresp = null;\r
+  private ErrorCentral errors = null;  \r
+  \r
+  protected ResultsPager pager = null; \r
+  \r
+  protected ErrorHelper errorHelper = null;\r
+              \r
+  public Pz2Service () {\r
+    logger.info("Instantiating pz2 bean [" + Utils.objectId(this) + "]");    \r
+  }\r
+  \r
+  public static Pz2Service get() {\r
+    FacesContext context = FacesContext.getCurrentInstance();\r
+    return (Pz2Service) context.getApplication().evaluateExpressionGet(context, "#{pz2}", Object.class); \r
+  }\r
+    \r
+  @PostConstruct\r
+  public void postConstruct() throws MissingConfigurationContextException {    \r
+    logger.info("Pz2Service PostConstruct of " + this);\r
+    stateMgr = new StateManager();\r
+    pzreq = new Pazpar2Commands();\r
+    pzresp = new Responses();    \r
+    errors = new ErrorCentral(); \r
+    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
+    pz2Client = new Pz2Client();\r
+    spClient = new ServiceProxyClient();\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.warn("There was a problem configuring the Pz2Service and/or clients (\"pz2\")");\r
+      e.printStackTrace();\r
+    }     \r
+  }\r
+  \r
+  @Qualifier\r
+  @Target({java.lang.annotation.ElementType.TYPE,\r
+           java.lang.annotation.ElementType.METHOD,\r
+           java.lang.annotation.ElementType.PARAMETER,\r
+           java.lang.annotation.ElementType.FIELD})\r
+  @Retention(java.lang.annotation.RetentionPolicy.RUNTIME)\r
+  public  @interface Preferred{}\r
+  \r
+  @Produces @Preferred @SessionScoped @Named("pzresp") public Responses getPzresp () {\r
+    logger.trace("Producing pzresp");\r
+    return pzresp;\r
+  }\r
+  \r
+  @Produces @Preferred @SessionScoped @Named("pzreq") public Pazpar2Commands getPzreq () {\r
+    logger.trace("Producing pzreq");\r
+    return pzreq;\r
+  }\r
+  \r
+  @Produces @Preferred @SessionScoped @Named("errors") public ErrorCentral getErrors() {\r
+    logger.trace("Producing errors");\r
+    return errors;\r
+  }\r
+  \r
+  @Produces @Preferred @SessionScoped @Named("stateMgr") public StateManager getStateMgr() {\r
+    logger.trace("Producing stateMgr");\r
+    return stateMgr;\r
+  }\r
+  \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
+    } 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
+    logger.info(configReader.document());\r
+    pzresp.getSp().resetAuthAndBeyond(true);    \r
+  }\r
+  \r
+  public void resetSearchAndRecordCommands () {\r
+    pzreq.getRecord().removeParametersInState();\r
+    pzreq.getSearch().removeParametersInState();   \r
+  }\r
+     \r
+  \r
+  /**\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 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
+      logger.error("Ignoring show,stat,termlist,bytarget commands due to configuration errors.");\r
+      return "";\r
+    } else if (pzresp.getSearch().hasApplicationError()) {\r
+      logger.error("Ignoring show,stat,termlist,bytarget commands due to problem with most recent search.");\r
+      return "";\r
+    } else if (!hasQuery()) {\r
+      logger.debug("Ignoring show,stat,termlist,bytarget commands because there is not yet a query.");\r
+      return "";\r
+    } else {\r
+      return update("show,stat,termlist,bytarget");\r
+    }\r
+  }\r
+     \r
+  /**\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
+   * @return Number of activeclients at the time of the 'show' command,\r
+   *         or 'new' if search was just initiated.\r
+   */\r
+  public String update (String commands) {\r
+    logger.debug("Request to update: " + commands);\r
+    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
+        return pzresp.getRecord().getActiveClients();\r
+      } else if (pzresp.getSearch().isNew()) {\r
+        // For returning notification of 'search started' quickly to UI\r
+        logger.info("New search. Marking it old, then returning 'new' to trigger another round-trip.");\r
+        pzresp.getSearch().setIsNew(false);\r
+        return "new";\r
+      } else {\r
+        handleQueryStateChanges(commands);\r
+        if (pzresp.getSearch().hasApplicationError()) {\r
+          logger.error("The command(s) " + commands + " cancelled because the latest search command had an error.");\r
+          return "0";\r
+        } else if (errors.hasConfigurationErrors()) {\r
+          logger.error("The command(s) " + commands + " cancelled due to configuration errors.");\r
+          return "0";\r
+        } else {\r
+          logger.debug("Processing request for " + commands); \r
+          List<CommandThread> threadList = new ArrayList<CommandThread>();\r
+          StringTokenizer tokens = new StringTokenizer(commands,",");\r
+          while (tokens.hasMoreElements()) {          \r
+            threadList.add(new CommandThread(pzreq.getCommand(tokens.nextToken()),searchClient,Pz2Service.get().getPzresp()));            \r
+          }\r
+          for (CommandThread thread : threadList) {\r
+            thread.start();\r
+          }\r
+          for (CommandThread thread : threadList) {\r
+            try {\r
+              thread.join();\r
+            } catch (InterruptedException e) {\r
+              e.printStackTrace();\r
+            }\r
+          }\r
+          return pzresp.getActiveClients();\r
+        }\r
+      }  \r
+    } catch (ClassCastException cce) {\r
+      cce.printStackTrace();    \r
+      return "";\r
+    } catch (NullPointerException npe) {\r
+      npe.printStackTrace();\r
+      return "";\r
+    } catch (Exception e) {\r
+      e.printStackTrace();\r
+      return "";\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
+  /**\r
+   * Used by the state manager to notify Pz2Service about state changes\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
+      pzresp.put("record", new RecordResponse());\r
+      return "";\r
+    } else {\r
+      pzreq.getRecord().setId(recId);\r
+      pzreq.getRecord().run();\r
+      return pzresp.getRecord().getActiveClients();\r
+    }\r
+  }\r
+  \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
+      \r
+  protected boolean hasQuery() {        \r
+    return pzreq.getCommand("search").hasParameterValue("query"); \r
+  }\r
+    \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
+    } \r
+    return pager;      \r
+  }\r
+  \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
+   * Sets the URL of the Service Proxy to use for requests\r
+   * \r
+   * @param url\r
+   */\r
+  public void setServiceProxyUrl(String url) {\r
+    searchClient = spClient;\r
+    setServiceType(SERVICE_TYPE_SP);\r
+    setServiceUrl(url);\r
+  }\r
+  \r
+  /**\r
+   * Returns the Service Proxy URL currently defined for servicing requests\r
+   * \r
+   */\r
+  public String getServiceProxyUrl () {\r
+    if (isServiceProxyService()) {\r
+      return spClient.getServiceUrl();\r
+    } else {\r
+      return "";\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Sets the URL of the Pazpar2 to use for requests\r
+   * \r
+   * @param url\r
+   */\r
+  public void setPazpar2Url(String url) {\r
+    searchClient = pz2Client;\r
+    setServiceType(SERVICE_TYPE_PZ2);\r
+    setServiceUrl(url);\r
+  }\r
+  \r
+  /**\r
+   * Returns the Pazpar2 URL currently defined for servicing requests\r
+   * \r
+   */  \r
+  public String getPazpar2Url() {\r
+    if (isPazpar2Service()) {\r
+      return pz2Client.getServiceUrl();\r
+    } else {\r
+      return "";\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Sets the URL to be used by the currently selected search client \r
+   * when running requests. \r
+   * \r
+   * @param url\r
+   */\r
+  public void setServiceUrl(String url) {\r
+    if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) {\r
+      pzreq.getRecord().removeParametersInState();\r
+      pzreq.getSearch().removeParametersInState();\r
+      pzresp.getSp().resetAuthAndBeyond(true);      \r
+      searchClient.setServiceUrl(url);\r
+    }    \r
+  }\r
+  \r
+  /**\r
+   * Gets the currently selected URL used for executing requests. \r
+   * @return\r
+   */\r
+  public String getServiceUrl() {\r
+    return (searchClient!=null ? searchClient.getServiceUrl() : "");\r
+  }\r
+  \r
+  public void setServiceId () {\r
+    pzreq.getRecord().removeParametersInState();\r
+    pzreq.getSearch().removeParametersInState();\r
+    pzresp.resetSearchAndBeyond();\r
+    pz2Client.setServiceId(pzreq.getInit().getService());\r
+  }\r
+  \r
+  public String getServiceId () {\r
+    return pzreq.getInit().getService();\r
+  }\r
+  \r
+  public boolean getServiceUrlIsDefined() {\r
+    return (searchClient != null && searchClient.hasServiceUrl());\r
+  }\r
+  \r
+  public List<String> getServiceProxyUrls() {\r
+    List<String> urls = new ArrayList<String>();\r
+    urls.add("");\r
+    urls.addAll(serviceProxyUrls);\r
+    return urls;\r
+  }\r
+  \r
+  public List<String> getPazpar2Urls () {\r
+    List<String> urls = new ArrayList<String>();\r
+    urls.add("");\r
+    urls.addAll(pazpar2Urls);\r
+    return urls;\r
+  }\r
+  \r
+  public String getServiceType () {\r
+    return serviceType;\r
+  }\r
+  \r
+  public boolean isPazpar2Service () {\r
+    return serviceType.equals(SERVICE_TYPE_PZ2);\r
+  }\r
+  \r
+  public boolean isServiceProxyService() {\r
+    return serviceType.equals(SERVICE_TYPE_SP);\r
+  }\r
+  \r
+  public boolean serviceIsToBeDecided () {\r
+    return serviceType.equals(SERVICE_TYPE_TBD);\r
+  }\r
+  \r
+  public ServiceProxyClient getSpClient () {\r
+    return spClient;\r
+  }  \r
+  \r
+  public boolean getAuthenticationRequired () {\r
+    return spClient.isAuthenticatingClient();\r
+  }\r
+\r
+  public String getCheckHistory () {\r
+    return ":pz2watch:stateForm:windowlocationhash";\r
+  }\r
+    \r
+  public String getWatchActiveclients () {\r
+    return ":pz2watch:activeclientsForm:activeclientsField";\r
+  }\r
+  \r
+  public String getWatchActiveclientsRecord () {\r
+    return ":pz2watch:activeclientsForm:activeclientsFieldRecord";\r
+  }\r
+\r
+  @Override\r
+  public void configure(ConfigurationReader reader)\r
+      throws ConfigurationException {\r
+    Configuration config = reader.getConfiguration(this);\r
+    if (config == null) {\r
+      serviceType = SERVICE_TYPE_TBD;\r
+    } else {\r
+      String service = config.get("TYPE");\r
+      if (service == null || service.length()==0) {\r
+        serviceType = SERVICE_TYPE_TBD;\r
+      } else if (serviceTypes.contains(service.toUpperCase())) {        \r
+        setServiceType(service.toUpperCase());\r
+      } else {\r
+        logger.error("Unknown serviceType type in configuration [" + service + "], can be one of " + serviceTypes);\r
+        serviceType = SERVICE_TYPE_TBD;\r
+      }\r
+      serviceProxyUrls = config.getMultiProperty(SERVICE_PROXY_URL_LIST,",");\r
+      pazpar2Urls = config.getMultiProperty(PAZPAR2_URL_LIST, ",");\r
+    }\r
+    logger.info(reader.document());\r
+    logger.info("Service Type is configured to " + serviceType);\r
+    \r
+  }\r
+\r
+  @Override\r
+  public Map<String, String> getDefaults() {\r
+    return new HashMap<String,String>();\r
+  }\r
+\r
+  @Override\r
+  public String getModuleName() {\r
+    return MODULE_NAME;\r
+  }\r
+\r
+  @Override\r
+  public List<String> documentConfiguration() {\r
+    return new ArrayList<String>();\r
+  }\r
+\r
+  public void setServiceTypePZ2() {\r
+    setServiceType(SERVICE_TYPE_PZ2);    \r
+  }\r
+\r
+  public void setServiceTypeSP() {\r
+    setServiceType(SERVICE_TYPE_SP);        \r
+  }\r
+\r
+  public void setServiceTypeTBD() {\r
+    setServiceType(SERVICE_TYPE_TBD);    \r
+  }\r
+  \r
+  private void setServiceType(String type) {\r
+    if (!serviceType.equals(type)  &&\r
+        !serviceType.equals(SERVICE_TYPE_TBD)) {\r
+      resetSearchAndRecordCommands();\r
+      pzresp.getSp().resetAuthAndBeyond(true);\r
+    }\r
+    serviceType = type;\r
+    if (serviceType.equals(SERVICE_TYPE_PZ2)) {\r
+      searchClient = pz2Client;\r
+      logger.info("Setting a Pazpar2 client to serve requests.");\r
+    } else if (serviceType.equals(SERVICE_TYPE_SP)) {\r
+      searchClient = spClient;\r
+      logger.info("Setting a Service Proxy client to serve requests.");\r
+    } else {\r
+      logger.info("Clearing search client. No client defined to serve requests at this point.");\r
+      searchClient = null;\r
+    }\r
+  }\r
+  \r
+  public SearchClient getSearchClient() {\r
+    return searchClient;\r
+  }\r
+  \r
+}\r