Moves Auth response class to SP data package
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / mkjsf / pazpar2 / Pz2Bean.java
index d7a9235..29d9280 100644 (file)
@@ -26,6 +26,7 @@ import com.indexdata.mkjsf.errors.ErrorHelper;
 import com.indexdata.mkjsf.pazpar2.commands.CommandParameter;\r
 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;\r
 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Commands;\r
+import com.indexdata.mkjsf.pazpar2.commands.sp.ServiceProxyCommand;\r
 import com.indexdata.mkjsf.pazpar2.data.RecordResponse;\r
 import com.indexdata.mkjsf.pazpar2.data.ResponseDataObject;\r
 import com.indexdata.mkjsf.pazpar2.data.ResponseParser;\r
@@ -104,35 +105,46 @@ public class Pz2Bean implements Pz2Interface, StateListener, Configurable, Seria
     pzreq.getRecord().removeParametersInState();\r
     pzreq.getSearch().removeParametersInState();   \r
   }\r
-\r
     \r
   public void doSearch(String query) {\r
     pzreq.getSearch().setParameter(new CommandParameter("query","=",query));     \r
     doSearch();\r
   }\r
 \r
-  public void doSearch() { \r
-    stateMgr.hasPendingStateChange("search",false);\r
-    pzresp.resetSearchResponses();\r
-    // resets some record and show command parameters without \r
-    // changing state or creating state change feedback\r
-    pzreq.getRecord().removeParametersInState();        \r
-    pzreq.getShow().setParameterInState(new CommandParameter("start","=",0));    \r
-    logger.debug(Utils.objectId(this) + " is searching using "+pzreq.getCommand("search").getUrlEncodedParameterValue("query"));\r
-    doCommand("search");      \r
+  public void doSearch() {\r
+    if (errors.hasConfigurationErrors()) {\r
+      logger.error("Ignoring search request due to configuration errors.");\r
+    } else if (searchClient == null){\r
+      logger.error("No search client defined. A client must either be pre-configured or selected before searching.");\r
+      errors.addConfigurationError(new ConfigurationError("No client defined","Client is null","No search client defined. A client must be pre-configured or selected runtime, prior to searching."));\r
+    } else {\r
+      stateMgr.hasPendingStateChange("search",false);\r
+      pzresp.resetSearchResponses();\r
+      // resets some record and show command parameters without \r
+      // changing state or creating state change feedback\r
+      pzreq.getRecord().removeParametersInState();        \r
+      pzreq.getShow().setParameterInState(new CommandParameter("start","=",0));    \r
+      logger.debug(Utils.objectId(this) + " is searching using "+pzreq.getCommand("search").getUrlEncodedParameterValue("query"));\r
+      searchClient.setSearchCommand(pzreq.getCommand("search"));\r
+      doCommand("search");\r
+    }\r
   }\r
   \r
   public String doRecord() {\r
-    ResponseDataObject responseObject = doCommand("record");\r
-    if (pzreq.getRecord().hasParameterValue("offset") ||\r
-          pzreq.getRecord().hasParameterValue("checksum")) {\r
-        RecordResponse recordResponse = new RecordResponse();\r
-        recordResponse.setType("record");\r
-        recordResponse.setXml(responseObject.getXml());\r
-        recordResponse.setAttribute("activeclients", "0");\r
-        pzresp.put("record", recordResponse);\r
-     }\r
-     return pzresp.getRecord().getActiveClients();    \r
+    if (errors.hasConfigurationErrors()) {\r
+      logger.error("Ignoring record request due to configuration errors.");\r
+      return "";\r
+    } else if (!pzreq.getCommand("record").hasParameterValue("id")) {\r
+      logger.debug("Ignoring record request due to no id parameter.");\r
+      return "";\r
+    } else if (pzresp.getSearch().hasApplicationError()) {\r
+      logger.debug("Ignoring record request due search error.");\r
+      return "";\r
+    } else {\r
+      logger.debug("Executing record command");\r
+      doCommand("record");\r
+      return pzresp.getRecord().getActiveClients();\r
+    }\r
   }\r
       \r
   /**\r
@@ -142,57 +154,50 @@ public class Pz2Bean implements Pz2Interface, StateListener, Configurable, Seria
    */\r
   public String update () {\r
     logger.debug("Updating show,stat,termlist,bytarget from pazpar2");\r
-    return update("show,stat,termlist,bytarget");\r
-  }\r
-  \r
-  public boolean validateUpdateRequest(String commands) {\r
     if (errors.hasConfigurationErrors()) {\r
-      logger.error("The command(s) " + commands + " are cancelled due to configuration errors.");\r
-      return false;\r
-    } else if (!commands.equals("search") && pzresp.getSearch().hasApplicationError()) {\r
-      logger.error("The command(s) " + commands + " are cancelled because the latest search command had an error.");\r
-      return false;\r
-    } else if (!commandsAreValid(commands)) {\r
-      logger.debug("The command(s) " + commands + " are cancelled because the were not found to be ready/valid.");\r
-      return false;\r
-    } else if (!hasQuery() &&  !(commands.equals("record") && pzreq.getCommand("record").hasParameterValue("recordquery"))) {\r
-      logger.debug("The command(s) " + commands + " are held off because there's not yet a query.");\r
-      return false;\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 true;\r
+      return update("show,stat,termlist,bytarget");\r
     }\r
-    \r
-    \r
   }\r
-   \r
+     \r
   /**\r
    * Refreshes the data objects listed in 'commands' from pazpar2\r
    * \r
    * @param commands\r
-   * @return Number of activeclients at the time of the 'show' command\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.info("Request to update: " + commands);\r
+    logger.debug("Request to update: " + commands);\r
     try {\r
-      if (!validateUpdateRequest(commands)) {\r
-        return "0";\r
-      } else if (commands.equals("search")) {\r
+      if (commands.equals("search")) {\r
         doSearch();\r
-        return "";\r
+        return "new";\r
       } else if (commands.equals("record")) {\r
         return doRecord();\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 + " are cancelled because the latest search command had an error.");\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
-          \r
           List<CommandThread> threadList = new ArrayList<CommandThread>();\r
           StringTokenizer tokens = new StringTokenizer(commands,",");\r
           while (tokens.hasMoreElements()) {          \r
@@ -234,17 +239,7 @@ public class Pz2Bean implements Pz2Interface, StateListener, Configurable, Seria
     }\r
     \r
   }\r
-  \r
-  public boolean commandsAreValid(String commands) {\r
-    if (commands.equals("record")) {\r
-      if (!pzreq.getCommand("record").hasParameterValue("id")) {\r
-        logger.debug("Skips sending record command due to lacking id parameter");\r
-        return false;\r
-      }\r
-    }\r
-    return true;\r
-  }\r
-                                \r
+                                  \r
   public String toggleRecord (String recId) {\r
     if (hasRecord(recId)) {\r
       pzreq.getRecord().removeParameters();  \r
@@ -288,10 +283,22 @@ public class Pz2Bean implements Pz2Interface, StateListener, Configurable, Seria
     pager =  new ResultsPager(pzresp,pageRange,pzreq);\r
     return pager;\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
+   * @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, doing search before updating " + commands);      \r
+      logger.info("Triggered search: Found pending search change [" + pzreq.getCommand("search").toString() + "], doing search before updating " + commands);      \r
       doSearch();\r
     } \r
     if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {        \r
@@ -306,28 +313,53 @@ public class Pz2Bean implements Pz2Interface, StateListener, Configurable, Seria
   }\r
   \r
   /**\r
-   * Validates the request then executes the command and parses the response.\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
-    ResponseDataObject responseObject = null; \r
-    if (validateUpdateRequest(commandName)) {\r
-      logger.debug(pzreq.getCommand(commandName).getEncodedQueryString() + ": Results for "+ pzreq.getCommand("search").getEncodedQueryString());\r
+    if (pzreq.getCommand(commandName).spOnly() && isPazpar2Service()) {\r
+      logger.warn("Skipping " + commandName + " - SP-only command, un-supported by Pazpar2");\r
+      return new ResponseDataObject();\r
+    } else {\r
+      ResponseDataObject responseObject = null;     \r
+      logger.info("Request "+commandName + ": "+ pzreq.getCommand("search").toString());\r
       Pazpar2Command command = pzreq.getCommand(commandName);\r
       long start = System.currentTimeMillis();\r
       HttpResponseWrapper commandResponse = searchClient.executeCommand(command);\r
       long end = System.currentTimeMillis();\r
       logger.debug("Executed " + command.getCommandName() + " in " + (end-start) + " ms." );\r
       responseLogger.debug("Response was: " + commandResponse.getResponseString());\r
-      responseObject = ResponseParser.getParser().getDataObject((ClientCommandResponse)commandResponse);\r
-      if (ResponseParser.docTypes.contains(responseObject.getType())) {\r
-        pzresp.put(commandName, responseObject);\r
-      }      \r
+      if (commandResponse.getContentType().contains("xml")) {\r
+        responseObject = ResponseParser.getParser().getDataObject((ClientCommandResponse)commandResponse);\r
+        if (ResponseParser.docTypes.contains(responseObject.getType())) {\r
+          logger.debug("Storing " + responseObject.getType() + " in pzresp. ");\r
+          pzresp.put(commandName, responseObject);\r
+        } else {\r
+          if (commandName.equals("record")) {\r
+            logger.debug("Command was 'record' but response not '<record>' - assuming raw record response.");\r
+            ResponseDataObject recordResponse = new RecordResponse(); \r
+            recordResponse.setType("record");\r
+            recordResponse.setXml(responseObject.getXml());          \r
+            recordResponse.setAttribute("activeclients", "0");\r
+            pzresp.put("record", recordResponse); \r
+          }        \r
+        }\r
+      } else if (commandResponse.isBinary()) {\r
+        responseObject = new RecordResponse(); \r
+        responseObject.setType(commandName);\r
+        logger.info("Binary response");\r
+        responseObject.setAttribute("activeclients", "0");\r
+        responseObject.setXml("<record>binary response</record>");\r
+        responseObject.setBinary(commandResponse.getBytes());\r
+        pzresp.put("record", responseObject);\r
+      } else {\r
+        logger.error("Response was not found to be XML or binary. The response was not handled.");\r
+      }\r
+      return responseObject;\r
     }\r
-    return responseObject;\r
   }\r
     \r
   @Override\r
@@ -383,6 +415,17 @@ public class Pz2Bean implements Pz2Interface, StateListener, Configurable, Seria
     return (searchClient!=null ? searchClient.getServiceUrl() : "");\r
   }\r
   \r
+  public void setServiceId () {\r
+    pzreq.getRecord().removeParametersInState();\r
+    pzreq.getSearch().removeParametersInState();\r
+    pzresp.resetSearchResponses();\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
@@ -460,6 +503,7 @@ public class Pz2Bean implements Pz2Interface, StateListener, Configurable, Seria
       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