Documents configuration schemes in more detail
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / mkjsf / pazpar2 / Pz2Client.java
index a68e67f..9e02137 100644 (file)
@@ -27,6 +27,35 @@ import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;
 import com.indexdata.mkjsf.pazpar2.data.CommandError;\r
 import com.indexdata.mkjsf.utils.Utils;\r
 \r
+/**\r
+ * Search client handling straight Pazpar2 requests. \r
+ * \r
+ * <p>Although it is described here as straight Pazpar2, the client itself \r
+ * actually represents a layer between Pazpar2 and the JSF application because it \r
+ * uses the Pazpar2 client from the library masterkey-common.</p>\r
+ * That client, which is the one also used by the Service Proxy, does perform certain \r
+ * types of session handling, bootstraps lost sessions, avoids repeating already \r
+ * executed queries etc, so it is -- in other words -- still a mediated interaction \r
+ * with Pazpar2 that takes place. At least for now.</p>  \r
+ * \r
+ * <h3>Configuration</h3>\r
+ *\r
+ * Configuration name: pz2client.\r
+ *  \r
+ * <p>When configuring the client using the Mk2Config scheme, this is the prefix to\r
+ * use in the .properties file. When using web.xml context parameters for configuration\r
+ * the configuration name has no effect.</p> \r
+ * \r
+ * <p>Pz2Client will acknowledge following configuration parameters:\r
+ * \r
+ * <ul>\r
+ *  <li>(pz2client.)PAZPAR2_URL</li>\r
+ *  <li>(pz2client.)SERVICE_ID</li>\r
+ * </ul> \r
+ *  \r
+ * @author Niels Erik\r
+ *\r
+ */\r
 public class Pz2Client implements SearchClient {\r
 \r
   private static final long serialVersionUID = 5414266730169982028L;\r
@@ -34,10 +63,15 @@ public class Pz2Client implements SearchClient {
   private transient Pazpar2Client client = null;\r
   private Pazpar2ClientConfiguration cfg = null;\r
   public static final String MODULENAME = "pz2client";\r
+  \r
+  /**\r
+   * PAZPAR2_URL=none, PROXY_MODE=1, SERIALIZE_REQUESTS=false, STREAMBUFF_SIZE=4096, PARSE_RESPONSES=true\r
+   */\r
   public static Map<String,String> DEFAULTS = new HashMap<String,String>();\r
-  Configuration config = null;\r
+  Configuration config = null;  \r
   \r
   static {    \r
+    DEFAULTS.put("PAZPAR2_URL", "");\r
     DEFAULTS.put("PROXY_MODE","1");\r
     DEFAULTS.put("SERIALIZE_REQUESTS", "false");\r
     DEFAULTS.put("STREAMBUFF_SIZE", "4096");\r
@@ -50,7 +84,7 @@ public class Pz2Client implements SearchClient {
   public void configure(ConfigurationReader configReader) throws ConfigurationException {    \r
     logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));\r
     try {\r
-      config = configReader.getConfiguration(this);\r
+      config = configReader.getConfiguration(this);      \r
       cfg = new Pazpar2ClientConfiguration(new ConfigurationGetter(config));\r
     } catch (ProxyErrorException pe) {\r
       logger.error("Could not configure Pazpar2 client: " + pe.getMessage());\r
@@ -58,7 +92,7 @@ public class Pz2Client implements SearchClient {
     } \r
     if (cfg != null) {\r
       try {\r
-        client = new Pazpar2ClientGeneric(cfg);  \r
+        client = new Pazpar2ClientGeneric(cfg);        \r
       } catch (ProxyErrorException pe) {\r
         logger.error("Could not configure Pazpar2 client: " + pe.getMessage());\r
         throw new ConfigurationException("Could not configure Pz2Client:  "+ pe.getMessage(),pe);\r
@@ -87,38 +121,58 @@ public class Pz2Client implements SearchClient {
     client.setSearchCommand(clientCommand);    \r
   }\r
 \r
+  /**\r
+   * Runs the give Pazpar2 command and returns a response wrapper with either the received response or \r
+   * with some form of error message. \r
+   * \r
+   * It is intended that this method never throws an exception. All events are supposed to be captured and\r
+   * returned in some form of response. \r
+   */\r
   @Override\r
-  public CommandResponse executeCommand(Pazpar2Command command) {\r
-    Pz2CommandResponse commandResponse = null;\r
+  public HttpResponseWrapper executeCommand(Pazpar2Command command) {\r
+    ClientCommandResponse commandResponse = null;\r
     ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
     ClientCommand clientCommand = new ClientCommand(command.getCommandName(), command.getEncodedQueryString());\r
     Pazpar2HttpResponse pz2HttpResponse = null;\r
     long start = System.currentTimeMillis();\r
     try {\r
       pz2HttpResponse = client.executeCommand(clientCommand, baos);\r
-      if (pz2HttpResponse.getStatusCode()==200) {\r
-        commandResponse = new Pz2CommandResponse(pz2HttpResponse,baos);\r
+      if (pz2HttpResponse.getStatusCode()==200 && pz2HttpResponse.getContentType().contains("xml")) {\r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse,baos);\r
+      } else if (pz2HttpResponse.getStatusCode()==200 && pz2HttpResponse.getContentType().contains("octet-stream")) {\r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse,baos);\r
+        logger.info("Content type: " + commandResponse.getContentType() + ". isBinary?: " + commandResponse.isBinary());\r
       } else if (pz2HttpResponse.getStatusCode()==417) {\r
         logger.error("Pazpar2 status code 417: " + baos.toString("UTF-8"));\r
-        commandResponse = new Pz2CommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Pazpar2: Expectation failed (417)", baos.toString("UTF-8")),"text/xml");                       \r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()) ,"Pazpar2: Expectation failed (417)", baos.toString("UTF-8")),"text/xml");                       \r
+      } else if (pz2HttpResponse.getContentType().contains("html")) {\r
+        String resp = baos.toString("UTF-8");\r
+        logger.error("HTML response where XML was expected. Status code was " + pz2HttpResponse.getStatusCode() + ": " + resp);\r
+        String htmlStrippedOfTags = resp.replaceAll("\\<[^>]*>","");\r
+        String errorXml = "";\r
+        if (htmlStrippedOfTags.toLowerCase().contains("domain")) {\r
+          errorXml = CommandError.createErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()), "Unexpected response type from Pazpar2", "Error: Expected XML response from Pazpar2 but got HTML. The HTML contains the word domain suggesting that the Pazpar2 address was not found.", htmlStrippedOfTags);\r
+        } else {  \r
+          errorXml = CommandError.createErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()), "Unexpected response type from Pazpar2: " + pz2HttpResponse.getContentType(),"Expected XML response from Pazpar2, got HTML", htmlStrippedOfTags);\r
+        } \r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),errorXml,pz2HttpResponse.getContentType());        \r
       } else {\r
         String resp = baos.toString("UTF-8");\r
         logger.error("Pazpar2 status code was " + pz2HttpResponse.getStatusCode() + ": " + resp);\r
-        commandResponse = new Pz2CommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Pazpar2 error occurred", baos.toString("UTF-8")),"text/xml");\r
-        throw new Pazpar2ErrorException(resp,pz2HttpResponse.getStatusCode(),resp,null);\r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()), "Pazpar2 error occurred", baos.toString("UTF-8")),"text/xml");        \r
       }       \r
     } catch (IOException e) {\r
       logger.error(e.getMessage());\r
       e.printStackTrace();\r
-      commandResponse = new Pz2CommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), "io", e.getMessage()),"text/xml");      \r
+      commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.createErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()), "IO exception", e.getMessage(), ""),"text/xml");      \r
     } catch (Pazpar2ErrorException e) {\r
       logger.error(e.getMessage());\r
       e.printStackTrace();\r
       logger.error("Creating error XML");\r
-      commandResponse = new Pz2CommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), "io", e.getMessage()),"text/xml");\r
+      commandResponse = new ClientCommandResponse(0,CommandError.createErrorXml(command.getCommandName(), "", "ServiceError", e.getMessage(),""),"text/xml");\r
     }\r
     long end = System.currentTimeMillis();      \r
-    logger.debug("Executed " + command.getCommandName() + " in " + (end-start) + " ms." );\r
+    logger.info("Executed " + command.getCommandName() + " in " + (end-start) + " ms." );\r
     return commandResponse;\r
   }\r
 \r
@@ -130,11 +184,17 @@ public class Pz2Client implements SearchClient {
     return clone;\r
   }\r
 \r
+  /**\r
+   * Returns default configuration parameters for the client.\r
+   */\r
   @Override\r
   public Map<String, String> getDefaults() {\r
     return DEFAULTS;\r
   }\r
 \r
+  /**\r
+   * Returns the configuration name of the client\r
+   */\r
   @Override\r
   public String getModuleName() {\r
     return MODULENAME;\r
@@ -164,6 +224,9 @@ public class Pz2Client implements SearchClient {
     }\r
   }\r
 \r
+  /**\r
+   * Provides configuration documentation -- mostly for diagnosing problems   \r
+   */\r
   @Override\r
   public List<String> documentConfiguration() {\r
     List<String> doc = new ArrayList<String>();\r
@@ -175,4 +238,48 @@ public class Pz2Client implements SearchClient {
     return config;\r
   }\r
 \r
+  /**\r
+   * Returns the currently configured Papzar2 URL.\r
+   */\r
+  @Override\r
+  public String getServiceUrl() {\r
+    return cfg.PAZPAR2_URL;    \r
+  }\r
+\r
+  /**\r
+   * Returns true if a Papzar2 URL was defined yet. \r
+   */\r
+  @Override\r
+  public boolean hasServiceUrl() {\r
+    return cfg.PAZPAR2_URL != null && cfg.PAZPAR2_URL.length()>0;\r
+  }\r
+  \r
+  /**\r
+   * Sets the Pazpar2 URL to use for requests. \r
+   */\r
+  @Override \r
+  public void setServiceUrl (String serviceUrl) {    \r
+    cfg.PAZPAR2_URL = serviceUrl;    \r
+  }\r
+  \r
+  /**\r
+   * Returns the Pazpar2 Service ID \r
+   */\r
+  public String getServiceId () {\r
+    return cfg.PAZPAR2_SERVICE_ID;\r
+  }\r
+  \r
+  /**\r
+   * Sets the service ID that Pazpar2 should use when servicing requests\r
+   * @param serviceId\r
+   */\r
+  public void setServiceId(String serviceId) {\r
+    cfg.PAZPAR2_SERVICE_ID = serviceId;\r
+    try {\r
+      client = new Pazpar2ClientGeneric(cfg);  \r
+    } catch (ProxyErrorException pe) {\r
+      logger.error("Could not configure Pazpar2 client: " + pe.getMessage());      \r
+    }\r
+  }\r
+\r
 }\r